1from __future__ import annotations
2
3import itertools
4import logging
5import re
6import typing as t
7from builtins import type as Type
8from collections import defaultdict
9from collections.abc import Sequence
10from enum import Enum, auto
11
12from sqlglot import exp
13from sqlglot._typing import F
14from sqlglot.errors import (
15 ErrorLevel,
16 ParseError,
17 TokenError,
18 concat_messages,
19 highlight_sql,
20 merge_errors,
21)
22from sqlglot.expressions import apply_index_offset
23from sqlglot.helper import ensure_list, i64, seq_get
24from sqlglot.optimizer.scope import find_in_scope
25from sqlglot.time import format_time
26from sqlglot.tokens import Token, Tokenizer, TokenType
27from sqlglot.trie import TrieResult, in_trie, new_trie
28
29if t.TYPE_CHECKING:
30 from re import Pattern
31
32 from sqlglot._typing import BuilderArgs, E
33 from sqlglot.dialects.dialect import Dialect, DialectType
34 from sqlglot.expressions import ExpOrStr
35
36 T = t.TypeVar("T")
37 TCeilFloor = t.TypeVar("TCeilFloor", exp.Ceil, exp.Floor)
38
39logger = logging.getLogger("sqlglot")
40
41OPTIONS_TYPE = dict[str, Sequence[t.Union[Sequence[str], str]]]
42
43# Excludes bare strings, which are also collections of strings, so that a single keyword
44# can't accidentally be matched with substring semantics (e.g. _match_texts("FOO"))
45TEXTS_TYPE = t.Union[tuple[str, ...], list[str], t.AbstractSet[str], t.Mapping[str, t.Any]]
46
47# Used to detect alphabetical characters and +/- in timestamp literals
48TIME_ZONE_RE: Pattern[str] = re.compile(r":.*?[a-zA-Z\+\-]")
49
50
51def build_var_map(args: BuilderArgs) -> exp.StarMap | exp.VarMap:
52 if len(args) == 1 and args[0].is_star:
53 return exp.StarMap(this=args[0])
54
55 keys: list[ExpOrStr] = []
56 values: list[ExpOrStr] = []
57 for i in range(0, len(args), 2):
58 keys.append(args[i])
59 values.append(args[i + 1])
60
61 return exp.VarMap(keys=exp.array(*keys, copy=False), values=exp.array(*values, copy=False))
62
63
64def build_like(args: BuilderArgs) -> exp.Escape | exp.Like:
65 like = exp.Like(this=seq_get(args, 1), expression=seq_get(args, 0))
66 return exp.Escape(this=like, expression=seq_get(args, 2)) if len(args) > 2 else like
67
68
69def build_sort_array(args: BuilderArgs) -> exp.ArraySort