Edit on GitHub

sqlglot expressions core - base classes, traits, operators, and helpers.

   1"""sqlglot expressions core - base classes, traits, operators, and helpers."""
   2
   3from __future__ import annotations
   4
   5import datetime
   6import logging
   7import math
   8import numbers
   9import re
  10import sys
  11import textwrap
  12import typing as t
  13from builtins import type as Type
  14from collections import deque
  15from collections.abc import Collection, Iterator, Mapping, MutableMapping, Sequence
  16from copy import deepcopy
  17from decimal import Decimal, InvalidOperation
  18from functools import reduce
  19
  20from sqlglot._typing import E, GeneratorNoDialectArgs, ParserNoDialectArgs, T
  21from sqlglot.errors import ParseError
  22from sqlglot.helper import (
  23    camel_to_snake_case,
  24    ensure_list,
  25    seq_get,
  26    to_bool,
  27    trait,
  28)
  29from sqlglot.tokenizer_core import Token
  30
  31if t.TYPE_CHECKING:
  32    from typing_extensions import Concatenate, Self, Unpack
  33
  34    from sqlglot._typing import P
  35    from sqlglot.dialects.dialect import DialectType
  36    from sqlglot.expressions.datatypes import DATA_TYPE, DataType, DType, Interval
  37    from sqlglot.expressions.query import Select
  38
  39    R = t.TypeVar("R")
  40
  41logger = logging.getLogger("sqlglot")
  42
  43SQLGLOT_META: str = "sqlglot.meta"
  44SQLGLOT_ANONYMOUS = "sqlglot.anonymous"
  45TABLE_PARTS = ("this", "db", "catalog")
  46COLUMN_PARTS = ("this", "table", "db", "catalog")
  47POSITION_META_KEYS: tuple[str, ...] = ("line", "col", "start", "end")
  48UNITTEST: bool = "unittest" in sys.modules or "pytest" in sys.modules
  49_IMMUTABLE_META_TYPES: frozenset[type] = frozenset((int, str, bool, float, type(None)))
  50
  51
  52@trait
  53class Expr:
  54    """
  55    The base class for all expressions in a syntax tree. Each Expr encapsulates any necessary
  56    context, such as its child expressions, their names (arg keys), and whether a given child expression
  57    is optional or not.
  58
  59    Attributes:
  60        key: a unique key for each class in the Expr hierarchy. This is useful for hashing
  61            and representing expressions as strings.
  62        arg_types: determines the arguments (child nodes) supported by an expression. It maps
  63            arg keys to booleans that indicate whether the corresponding args are optional.
  64        parent: a reference to the parent expression (or None, in case of root expressions).
  65        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  66            uses to refer to it.
  67        index: the index of an expression if it is inside of a list argument in its parent.
  68        comments: a list of comments that are associated with a given expression. This is used in
  69            order to preserve comments when transpiling SQL code.
  70        type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  71            optimizer, in order to enable some transformations that require type information.
  72        meta: a dictionary that can be used to store useful metadata for a given expression.
  73
  74    Example:
  75        >>> class Foo(Expr):
  76        ...     arg_types = {"this": True, "expression": False}
  77
  78        The above definition informs us that Foo is an Expr that requires an argument called
  79        "this" and may also optionally receive an argument called "expression".
  80
  81    Args:
  82        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  83    """
  84
  85    key: t.ClassVar[str] = "expression"
  86    arg_types: t.ClassVar[dict[str, bool]] = {"this": True}
  87    required_args: t.ClassVar[set[str]] = {"this"}
  88    is_var_len_args: t.ClassVar[bool] = False
  89    var_len_arg_key: t.ClassVar[str] = "expressions"
  90    _hash_raw_args: t.ClassVar[bool] = False
  91    is_subquery: t.ClassVar[bool] = False
  92    is_cast: t.ClassVar[bool] = False
  93    is_data_type: t.ClassVar[bool] = False
  94
  95    args: dict[str, t.Any]
  96    parent: Expr | None
  97    arg_key: str | None
  98    index: int | None
  99    comments: list[str] | None
 100    _type: DataType | None
 101    _meta: dict[str, t.Any] | None
 102    _hash: int | None
 103
 104    @classmethod
 105    def __init_subclass__(cls, **kwargs: t.Any) -> None:
 106        super().__init_subclass__(**kwargs)
 107        # When an Expr class is created, its key is automatically set
 108        # to be the lowercase version of the class' name.
 109        cls.key = cls.__name__.lower()
 110        cls.required_args = {k for k, v in cls.arg_types.items() if v}
 111        # This is so that docstrings are not inherited in pdoc
 112        setattr(cls, "__doc__", getattr(cls, "__doc__", None) or "")
 113
 114    is_primitive: t.ClassVar[bool] = False
 115
 116    def __init__(self, **args: object) -> None:
 117        self.args: dict[str, t.Any] = args
 118        self.parent: Expr | None = None
 119        self.arg_key: str | None = None
 120        self.index: int | None = None
 121        self.comments: list[str] | None = None
 122        self._type: DataType | None = None
 123        self._meta: dict[str, t.Any] | None = None
 124        self._hash: int | None = None
 125
 126        if not self.is_primitive:
 127            for arg_key, value in self.args.items():
 128                self._set_parent(arg_key, value)
 129
 130    @property
 131    def this(self) -> t.Any:
 132        """
 133        Retrieves the argument with key "this".
 134        """
 135        raise NotImplementedError
 136
 137    @property
 138    def expression(self) -> t.Any:
 139        """
 140        Retrieves the argument with key "expression".
 141        """
 142        raise NotImplementedError
 143
 144    @property
 145    def expressions(self) -> list[t.Any]:
 146        """
 147        Retrieves the argument with key "expressions".
 148        """
 149        raise NotImplementedError
 150
 151    def text(self, key: str) -> str:
 152        """
 153        Returns a textual representation of the argument corresponding to "key". This can only be used
 154        for args that are strings or leaf Expr instances, such as identifiers and literals.
 155        """
 156        raise NotImplementedError
 157
 158    @property
 159    def is_string(self) -> bool:
 160        """
 161        Checks whether a Literal expression is a string.
 162        """
 163        raise NotImplementedError
 164
 165    @property
 166    def is_number(self) -> bool:
 167        """
 168        Checks whether a Literal expression is a number.
 169        """
 170        raise NotImplementedError
 171
 172    def to_py(self) -> t.Any:
 173        """
 174        Returns a Python object equivalent of the SQL node.
 175        """
 176        raise NotImplementedError
 177
 178    @property
 179    def is_int(self) -> bool:
 180        """
 181        Checks whether an expression is an integer.
 182        """
 183        raise NotImplementedError
 184
 185    @property
 186    def is_star(self) -> bool:
 187        """Checks whether an expression is a star."""
 188        raise NotImplementedError
 189
 190    @property
 191    def alias(self) -> str:
 192        """
 193        Returns the alias of the expression, or an empty string if it's not aliased.
 194        """
 195        raise NotImplementedError
 196
 197    @property
 198    def alias_column_names(self) -> list[str]:
 199        raise NotImplementedError
 200
 201    @property
 202    def name(self) -> str:
 203        raise NotImplementedError
 204
 205    @property
 206    def alias_or_name(self) -> str:
 207        raise NotImplementedError
 208
 209    @property
 210    def output_name(self) -> str:
 211        """
 212        Name of the output column if this expression is a selection.
 213
 214        If the Expr has no output name, an empty string is returned.
 215
 216        Example:
 217            >>> from sqlglot import parse_one
 218            >>> parse_one("SELECT a").expressions[0].output_name
 219            'a'
 220            >>> parse_one("SELECT b AS c").expressions[0].output_name
 221            'c'
 222            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 223            ''
 224        """
 225        raise NotImplementedError
 226
 227    @property
 228    def type(self) -> DataType | None:
 229        raise NotImplementedError
 230
 231    @type.setter
 232    def type(self, dtype: DataType | DType | str | None) -> None:
 233        raise NotImplementedError
 234
 235    def is_type(self, *dtypes: DATA_TYPE) -> bool:
 236        raise NotImplementedError
 237
 238    def is_leaf(self) -> bool:
 239        raise NotImplementedError
 240
 241    @property
 242    def meta(self) -> dict[str, t.Any]:
 243        raise NotImplementedError
 244
 245    def meta_get(self, key: str, default: t.Any = None) -> t.Any:
 246        raise NotImplementedError
 247
 248    def __deepcopy__(self, memo: t.Any) -> Expr:
 249        raise NotImplementedError
 250
 251    def copy(self: E) -> E:
 252        """
 253        Returns a deep copy of the expression.
 254        """
 255        raise NotImplementedError
 256
 257    def add_comments(self, comments: list[str] | None = None, prepend: bool = False) -> None:
 258        raise NotImplementedError
 259
 260    def pop_comments(self) -> list[str]:
 261        raise NotImplementedError
 262
 263    def append(self, arg_key: str, value: t.Any) -> None:
 264        """
 265        Appends value to arg_key if it's a list or sets it as a new list.
 266
 267        Args:
 268            arg_key (str): name of the list expression arg
 269            value (Any): value to append to the list
 270        """
 271        raise NotImplementedError
 272
 273    def set(
 274        self,
 275        arg_key: str,
 276        value: object,
 277        index: int | None = None,
 278        overwrite: bool = True,
 279    ) -> None:
 280        """
 281        Sets arg_key to value.
 282
 283        Args:
 284            arg_key: name of the expression arg.
 285            value: value to set the arg to.
 286            index: if the arg is a list, this specifies what position to add the value in it.
 287            overwrite: assuming an index is given, this determines whether to overwrite the
 288                list entry instead of only inserting a new value (i.e., like list.insert).
 289        """
 290        raise NotImplementedError
 291
 292    def _set_parent(self, arg_key: str, value: object, index: int | None = None) -> None:
 293        raise NotImplementedError
 294
 295    @property
 296    def depth(self) -> int:
 297        """
 298        Returns the depth of this tree.
 299        """
 300        raise NotImplementedError
 301
 302    def iter_expressions(self: E, reverse: bool = False) -> Iterator[E]:
 303        """Yields the key and expression for all arguments, exploding list args."""
 304        raise NotImplementedError
 305
 306    def find(self, *expression_types: Type[E], bfs: bool = True) -> E | None:
 307        """
 308        Returns the first node in this tree which matches at least one of
 309        the specified types.
 310
 311        Args:
 312            expression_types: the expression type(s) to match.
 313            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 314
 315        Returns:
 316            The node which matches the criteria or None if no such node was found.
 317        """
 318        raise NotImplementedError
 319
 320    def find_all(self, *expression_types: Type[E], bfs: bool = True) -> Iterator[E]:
 321        """
 322        Returns a generator object which visits all nodes in this tree and only
 323        yields those that match at least one of the specified expression types.
 324
 325        Args:
 326            expression_types: the expression type(s) to match.
 327            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 328
 329        Returns:
 330            The generator object.
 331        """
 332        raise NotImplementedError
 333
 334    def find_ancestor(self, *expression_types: Type[E]) -> E | None:
 335        """
 336        Returns a nearest parent matching expression_types.
 337
 338        Args:
 339            expression_types: the expression type(s) to match.
 340
 341        Returns:
 342            The parent node.
 343        """
 344        raise NotImplementedError
 345
 346    @property
 347    def parent_select(self) -> Select | None:
 348        """
 349        Returns the parent select statement.
 350        """
 351        raise NotImplementedError
 352
 353    @property
 354    def same_parent(self) -> bool:
 355        """Returns if the parent is the same class as itself."""
 356        raise NotImplementedError
 357
 358    def root(self) -> Expr:
 359        """
 360        Returns the root expression of this tree.
 361        """
 362        raise NotImplementedError
 363
 364    def walk(
 365        self, bfs: bool = True, prune: t.Callable[[Expr], bool] | None = None
 366    ) -> Iterator[Expr]:
 367        """
 368        Returns a generator object which visits all nodes in this tree.
 369
 370        Args:
 371            bfs: if set to True the BFS traversal order will be applied,
 372                otherwise the DFS traversal will be used instead.
 373            prune: callable that returns True if the generator should stop traversing
 374                this branch of the tree.
 375
 376        Returns:
 377            the generator object.
 378        """
 379        raise NotImplementedError
 380
 381    def dfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
 382        """
 383        Returns a generator object which visits all nodes in this tree in
 384        the DFS (Depth-first) order.
 385
 386        Returns:
 387            The generator object.
 388        """
 389        raise NotImplementedError
 390
 391    def bfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
 392        """
 393        Returns a generator object which visits all nodes in this tree in
 394        the BFS (Breadth-first) order.
 395
 396        Returns:
 397            The generator object.
 398        """
 399        raise NotImplementedError
 400
 401    def unnest(self) -> Expr:
 402        """
 403        Returns the first non parenthesis child or self.
 404        """
 405        raise NotImplementedError
 406
 407    def unalias(self) -> Expr:
 408        """
 409        Returns the inner expression if this is an Alias.
 410        """
 411        raise NotImplementedError
 412
 413    def unnest_operands(self) -> tuple[Expr, ...]:
 414        """
 415        Returns unnested operands as a tuple.
 416        """
 417        raise NotImplementedError
 418
 419    def flatten(self, unnest: bool = True) -> Iterator[Expr]:
 420        """
 421        Returns a generator which yields child nodes whose parents are the same class.
 422
 423        A AND B AND C -> [A, B, C]
 424        """
 425        raise NotImplementedError
 426
 427    def to_s(self) -> str:
 428        """
 429        Same as __repr__, but includes additional information which can be useful
 430        for debugging, like empty or missing args and the AST nodes' object IDs.
 431        """
 432        raise NotImplementedError
 433
 434    def sql(
 435        self, dialect: DialectType = None, copy: bool = True, **opts: Unpack[GeneratorNoDialectArgs]
 436    ) -> str:
 437        """
 438        Returns SQL string representation of this tree.
 439
 440        Args:
 441            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 442            opts: other `sqlglot.generator.Generator` options.
 443
 444        Returns:
 445            The SQL string.
 446        """
 447        raise NotImplementedError
 448
 449    def transform(
 450        self, fun: t.Callable[..., T], *args: object, copy: bool = True, **kwargs: object
 451    ) -> T:
 452        """
 453        Visits all tree nodes (excluding already transformed ones)
 454        and applies the given transformation function to each node.
 455
 456        Args:
 457            fun: a function which takes a node as an argument and returns a
 458                new transformed node or the same node without modifications. If the function
 459                returns None, then the corresponding node will be removed from the syntax tree.
 460            copy: if set to True a new tree instance is constructed, otherwise the tree is
 461                modified in place.
 462
 463        Returns:
 464            The transformed tree.
 465        """
 466        raise NotImplementedError
 467
 468    def replace(self, expression: T) -> T:
 469        """
 470        Swap out this expression with a new expression.
 471
 472        For example::
 473
 474            >>> import sqlglot
 475            >>> tree = sqlglot.parse_one("SELECT x FROM tbl")
 476            >>> tree.find(sqlglot.exp.Column).replace(sqlglot.exp.column("y"))
 477            Column(
 478              this=Identifier(this=y, quoted=False))
 479            >>> tree.sql()
 480            'SELECT y FROM tbl'
 481
 482        Args:
 483            expression (T): new node
 484
 485        Returns:
 486            T: The new expression or expressions.
 487        """
 488        raise NotImplementedError
 489
 490    def pop(self: E) -> E:
 491        """
 492        Remove this expression from its AST.
 493
 494        Returns:
 495            The popped expression.
 496        """
 497        raise NotImplementedError
 498
 499    def assert_is(self, type_: Type[E]) -> E:
 500        """
 501        Assert that this `Expr` is an instance of `type_`.
 502
 503        If it is NOT an instance of `type_`, this raises an assertion error.
 504        Otherwise, this returns this expression.
 505
 506        Examples:
 507            This is useful for type security in chained expressions:
 508
 509            >>> import sqlglot
 510            >>> sqlglot.parse_one("SELECT x from y").assert_is(sqlglot.exp.Select).select("z").sql()
 511            'SELECT x, z FROM y'
 512        """
 513        raise NotImplementedError
 514
 515    def error_messages(self, args: Sequence[object] | None = None) -> list[str]:
 516        """
 517        Checks if this expression is valid (e.g. all mandatory args are set).
 518
 519        Args:
 520            args: a sequence of values that were used to instantiate a Func expression. This is used
 521                to check that the provided arguments don't exceed the function argument limit.
 522
 523        Returns:
 524            A list of error messages for all possible errors that were found.
 525        """
 526        raise NotImplementedError
 527
 528    def dump(self) -> list[dict[str, t.Any]]:
 529        """
 530        Dump this Expr to a JSON-serializable dict.
 531        """
 532        from sqlglot.serde import dump
 533
 534        return dump(self)
 535
 536    @classmethod
 537    def load(cls, obj: list[dict[str, Any]] | None) -> Expr:
 538        """
 539        Load a dict (as returned by `Expr.dump`) into an Expr instance.
 540        """
 541        from sqlglot.serde import load
 542
 543        result = load(obj)
 544        assert isinstance(result, Expr)
 545        return result
 546
 547    def and_(
 548        self,
 549        *expressions: ExpOrStr | None,
 550        dialect: DialectType = None,
 551        copy: bool = True,
 552        wrap: bool = True,
 553        **opts: Unpack[ParserNoDialectArgs],
 554    ) -> Condition:
 555        """
 556        AND this condition with one or multiple expressions.
 557
 558        Example:
 559            >>> condition("x=1").and_("y=1").sql()
 560            'x = 1 AND y = 1'
 561
 562        Args:
 563            *expressions: the SQL code strings to parse.
 564                If an `Expr` instance is passed, it will be used as-is.
 565            dialect: the dialect used to parse the input expression.
 566            copy: whether to copy the involved expressions (only applies to Exprs).
 567            wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
 568                precedence issues, but can be turned off when the produced AST is too deep and
 569                causes recursion-related issues.
 570            opts: other options to use to parse the input expressions.
 571
 572        Returns:
 573            The new And condition.
 574        """
 575        raise NotImplementedError
 576
 577    def or_(
 578        self,
 579        *expressions: ExpOrStr | None,
 580        dialect: DialectType = None,
 581        copy: bool = True,
 582        wrap: bool = True,
 583        **opts: Unpack[ParserNoDialectArgs],
 584    ) -> Condition:
 585        """
 586        OR this condition with one or multiple expressions.
 587
 588        Example:
 589            >>> condition("x=1").or_("y=1").sql()
 590            'x = 1 OR y = 1'
 591
 592        Args:
 593            *expressions: the SQL code strings to parse.
 594                If an `Expr` instance is passed, it will be used as-is.
 595            dialect: the dialect used to parse the input expression.
 596            copy: whether to copy the involved expressions (only applies to Exprs).
 597            wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
 598                precedence issues, but can be turned off when the produced AST is too deep and
 599                causes recursion-related issues.
 600            opts: other options to use to parse the input expressions.
 601
 602        Returns:
 603            The new Or condition.
 604        """
 605        raise NotImplementedError
 606
 607    def not_(self, copy: bool = True) -> Not:
 608        """
 609        Wrap this condition with NOT.
 610
 611        Example:
 612            >>> condition("x=1").not_().sql()
 613            'NOT x = 1'
 614
 615        Args:
 616            copy: whether to copy this object.
 617
 618        Returns:
 619            The new Not instance.
 620        """
 621        raise NotImplementedError
 622
 623    def update_positions(
 624        self: E,
 625        other: Token | Expr | None = None,
 626        line: int | None = None,
 627        col: int | None = None,
 628        start: int | None = None,
 629        end: int | None = None,
 630    ) -> E:
 631        """
 632        Update this expression with positions from a token or other expression.
 633
 634        Args:
 635            other: a token or expression to update this expression with.
 636            line: the line number to use if other is None
 637            col: column number
 638            start: start char index
 639            end:  end char index
 640
 641        Returns:
 642            The updated expression.
 643        """
 644        raise NotImplementedError
 645
 646    def as_(
 647        self,
 648        alias: str | Identifier,
 649        quoted: bool | None = None,
 650        dialect: DialectType = None,
 651        copy: bool = True,
 652        table: bool | Sequence[str | Identifier] = False,
 653        **opts: Unpack[ParserNoDialectArgs],
 654    ) -> Expr:
 655        raise NotImplementedError
 656
 657    def _binop(self, klass: Type[E], other: t.Any, reverse: bool = False) -> E:
 658        raise NotImplementedError
 659
 660    def __getitem__(self, other: ExpOrStr | tuple[ExpOrStr, ...]) -> Bracket:
 661        raise NotImplementedError
 662
 663    def __iter__(self) -> Iterator:
 664        raise NotImplementedError
 665
 666    def isin(
 667        self,
 668        *expressions: t.Any,
 669        query: ExpOrStr | None = None,
 670        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
 671        dialect: DialectType = None,
 672        copy: bool = True,
 673        **opts: Unpack[ParserNoDialectArgs],
 674    ) -> In:
 675        raise NotImplementedError
 676
 677    def between(
 678        self, low: t.Any, high: t.Any, copy: bool = True, symmetric: bool | None = None
 679    ) -> Between:
 680        raise NotImplementedError
 681
 682    def is_(self, other: ExpOrStr) -> Is:
 683        raise NotImplementedError
 684
 685    def like(self, other: ExpOrStr) -> Like:
 686        raise NotImplementedError
 687
 688    def ilike(self, other: ExpOrStr) -> ILike:
 689        raise NotImplementedError
 690
 691    def eq(self, other: t.Any) -> EQ:
 692        raise NotImplementedError
 693
 694    def neq(self, other: t.Any) -> NEQ:
 695        raise NotImplementedError
 696
 697    def rlike(self, other: ExpOrStr) -> RegexpLike:
 698        raise NotImplementedError
 699
 700    def div(self, other: ExpOrStr, typed: bool = False, safe: bool = False) -> Div:
 701        raise NotImplementedError
 702
 703    def asc(self, nulls_first: bool = True) -> Ordered:
 704        raise NotImplementedError
 705
 706    def desc(self, nulls_first: bool = False) -> Ordered:
 707        raise NotImplementedError
 708
 709    def __lt__(self, other: t.Any) -> LT:
 710        raise NotImplementedError
 711
 712    def __le__(self, other: t.Any) -> LTE:
 713        raise NotImplementedError
 714
 715    def __gt__(self, other: t.Any) -> GT:
 716        raise NotImplementedError
 717
 718    def __ge__(self, other: t.Any) -> GTE:
 719        raise NotImplementedError
 720
 721    def __add__(self, other: t.Any) -> Add:
 722        raise NotImplementedError
 723
 724    def __radd__(self, other: t.Any) -> Add:
 725        raise NotImplementedError
 726
 727    def __sub__(self, other: t.Any) -> Sub:
 728        raise NotImplementedError
 729
 730    def __rsub__(self, other: t.Any) -> Sub:
 731        raise NotImplementedError
 732
 733    def __mul__(self, other: t.Any) -> Mul:
 734        raise NotImplementedError
 735
 736    def __rmul__(self, other: t.Any) -> Mul:
 737        raise NotImplementedError
 738
 739    def __truediv__(self, other: t.Any) -> Div:
 740        raise NotImplementedError
 741
 742    def __rtruediv__(self, other: t.Any) -> Div:
 743        raise NotImplementedError
 744
 745    def __floordiv__(self, other: t.Any) -> IntDiv:
 746        raise NotImplementedError
 747
 748    def __rfloordiv__(self, other: t.Any) -> IntDiv:
 749        raise NotImplementedError
 750
 751    def __mod__(self, other: t.Any) -> Mod:
 752        raise NotImplementedError
 753
 754    def __rmod__(self, other: t.Any) -> Mod:
 755        raise NotImplementedError
 756
 757    def __pow__(self, other: t.Any) -> Pow:
 758        raise NotImplementedError
 759
 760    def __rpow__(self, other: t.Any) -> Pow:
 761        raise NotImplementedError
 762
 763    def __and__(self, other: t.Any) -> And:
 764        raise NotImplementedError
 765
 766    def __rand__(self, other: t.Any) -> And:
 767        raise NotImplementedError
 768
 769    def __or__(self, other: t.Any) -> Or:
 770        raise NotImplementedError
 771
 772    def __ror__(self, other: t.Any) -> Or:
 773        raise NotImplementedError
 774
 775    def __neg__(self) -> Neg:
 776        raise NotImplementedError
 777
 778    def __invert__(self) -> Not:
 779        raise NotImplementedError
 780
 781    def pipe(
 782        self, func: t.Callable[Concatenate[Self, P], R], *args: P.args, **kwargs: P.kwargs
 783    ) -> R:
 784        """Apply a function to `Self` (the current instance) and return the result.
 785
 786        Doing `expr.pipe(func, *args, **kwargs)` is equivalent to `func(expr, *args, **kwargs)`.
 787
 788        It allows you to chain operations in a fluent way on any given function that takes `Self` as its first argument.
 789
 790        Tip:
 791            If `func` doesn't take `Self` as it's first argument, you can use a lambda to work around it.
 792
 793        Args:
 794            func: The function to apply. It should take `Self` as its first argument, followed by any additional arguments specified in `*args` and `**kwargs`.
 795            *args: Additional positional arguments to pass to `func` after `Self`.
 796            **kwargs: Additional keyword arguments to pass to `func`.
 797
 798        Returns:
 799            The result of applying `func` to `Self` with the given arguments.
 800        """
 801        return func(self, *args, **kwargs)
 802
 803    def apply(
 804        self, func: t.Callable[Concatenate[Self, P], t.Any], *args: P.args, **kwargs: P.kwargs
 805    ) -> Self:
 806        """Apply a function to `Self` (the current instance) for side effects, and return `Self`.
 807
 808        Useful for inspecting intermediate expressions in a method chain by simply adding/removing `apply` calls, especially when combined with `pipe`.
 809
 810        Tip:
 811            If `func` doesn't take `Self` as it's first argument, you can use a lambda to work around it.
 812
 813        Args:
 814            func: The function to apply. It should take `Self` as its first argument, followed by any additional arguments specified in `*args` and `**kwargs`.
 815            *args: Additional positional arguments to pass to `func` after `Self`.
 816            **kwargs: Additional keyword arguments to pass to `func`.
 817
 818        Returns:
 819            The same instance.
 820        """
 821        func(self, *args, **kwargs)
 822        return self
 823
 824
 825class Expression(Expr):
 826    __slots__ = (
 827        "args",
 828        "parent",
 829        "arg_key",
 830        "index",
 831        "comments",
 832        "_type",
 833        "_meta",
 834        "_hash",
 835    )
 836
 837    def __eq__(self, other: object) -> bool:
 838        return self is other or (type(self) is type(other) and hash(self) == hash(other))
 839
 840    def __ne__(self, other: object) -> bool:
 841        return not self.__eq__(other)
 842
 843    def __hash__(self) -> int:
 844        if self._hash is None:
 845            nodes: list[Expr] = []
 846            stack: list[Expr] = [self]
 847
 848            # Collect nodes, finding child expressions inline instead of via the
 849            # iter_expressions generator (whose per-node generator object dominates the
 850            # hash's cost). reversed(nodes) is a valid post-order regardless of DFS/BFS.
 851            while stack:
 852                node = stack.pop()
 853                nodes.append(node)
 854
 855                for v in node.args.values():
 856                    if isinstance(v, Expr):
 857                        if v._hash is None:
 858                            stack.append(v)
 859                    elif type(v) is list:
 860                        for x in v:
 861                            if isinstance(x, Expr) and x._hash is None:
 862                                stack.append(x)
 863
 864            for node in reversed(nodes):
 865                hash_ = hash(node.key)
 866
 867                if node._hash_raw_args:
 868                    for k in sorted(node.args):
 869                        v = node.args[k]
 870                        if v:
 871                            hash_ = hash((hash_, k, tuple(v) if type(v) is list else v))
 872                else:
 873                    for k in sorted(node.args):
 874                        v = node.args[k]
 875                        vt = type(v)
 876
 877                        if vt is list:
 878                            for x in v:
 879                                if x is not None and x is not False:
 880                                    hash_ = hash((hash_, k, x.lower() if type(x) is str else x))
 881                                else:
 882                                    hash_ = hash((hash_, k))
 883                        elif v is not None and v is not False:
 884                            hash_ = hash((hash_, k, v.lower() if vt is str else v))
 885
 886                node._hash = hash_
 887        assert self._hash
 888        return self._hash
 889
 890    def __reduce__(
 891        self,
 892    ) -> tuple[
 893        t.Callable[[list[dict[str, t.Any]] | None], Expr | DType | None],
 894        tuple[list[dict[str, t.Any]]],
 895    ]:
 896        from sqlglot.serde import dump, load
 897
 898        return (load, (dump(self),))
 899
 900    @property
 901    def this(self) -> t.Any:
 902        return self.args.get("this")
 903
 904    @property
 905    def expression(self) -> t.Any:
 906        return self.args.get("expression")
 907
 908    @property
 909    def expressions(self) -> list[t.Any]:
 910        return self.args.get("expressions") or []
 911
 912    def text(self, key: str) -> str:
 913        field = self.args.get(key)
 914        if isinstance(field, str):
 915            return field
 916        if isinstance(field, (Identifier, Literal, Var)):
 917            return field.this
 918        if isinstance(field, (Star, Null)):
 919            return field.name
 920        return ""
 921
 922    @property
 923    def is_string(self) -> bool:
 924        return isinstance(self, Literal) and self.args["is_string"]
 925
 926    @property
 927    def is_number(self) -> bool:
 928        return (isinstance(self, Literal) and not self.args["is_string"]) or (
 929            isinstance(self, Neg) and self.this.is_number
 930        )
 931
 932    def to_py(self) -> t.Any:
 933        raise ValueError(f"{self} cannot be converted to a Python object.")
 934
 935    @property
 936    def is_int(self) -> bool:
 937        try:
 938            return self.is_number and isinstance(self.to_py(), int)
 939        except ValueError:
 940            return False
 941
 942    @property
 943    def is_star(self) -> bool:
 944        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 945
 946    @property
 947    def alias(self) -> str:
 948        alias = self.args.get("alias")
 949        if isinstance(alias, Expression):
 950            return alias.name
 951        return self.text("alias")
 952
 953    @property
 954    def alias_column_names(self) -> list[str]:
 955        table_alias = self.args.get("alias")
 956        if not table_alias:
 957            return []
 958        return [c.name for c in table_alias.args.get("columns") or []]
 959
 960    @property
 961    def name(self) -> str:
 962        return self.text("this")
 963
 964    @property
 965    def alias_or_name(self) -> str:
 966        return self.alias or self.name
 967
 968    @property
 969    def output_name(self) -> str:
 970        return ""
 971
 972    @property
 973    def type(self) -> DataType | None:
 974        if self.is_data_type:
 975            return self  # type: ignore[return-value]
 976        if self.is_cast:
 977            return self._type or self.to  # type: ignore[attr-defined]
 978        return self._type
 979
 980    @type.setter
 981    def type(self, dtype: DataType | DType | str | None) -> None:
 982        if dtype and type(dtype).__name__ != "DataType":
 983            from sqlglot.expressions.datatypes import DataType as _DataType
 984
 985            dtype = _DataType.build(dtype)
 986        self._type = dtype  # type: ignore[assignment]
 987
 988    def is_type(self, *dtypes: DATA_TYPE) -> bool:
 989        t = self._type
 990        return t is not None and t.is_type(*dtypes)
 991
 992    def is_leaf(self) -> bool:
 993        return not any((isinstance(v, Expr) or type(v) is list) and v for v in self.args.values())
 994
 995    @property
 996    def meta(self) -> dict[str, t.Any]:
 997        if self._meta is None:
 998            self._meta = {}
 999        return self._meta
1000
1001    def meta_get(self, key: str, default: t.Any = None) -> t.Any:
1002        """Reads a meta value without allocating the meta dict (unlike the `meta` property)."""
1003        meta = self._meta
1004        return meta.get(key, default) if meta is not None else default
1005
1006    def __deepcopy__(self, memo: t.Any) -> Expr:
1007        root = self.__class__()
1008        stack: list[tuple[Expr, Expr]] = [(self, root)]
1009
1010        while stack:
1011            node, copy = stack.pop()
1012
1013            if node.comments is not None:
1014                copy.comments = deepcopy(node.comments)
1015            if node._type is not None:
1016                copy._type = deepcopy(node._type)
1017            if node._meta is not None:
1018                # Positions and flags are immutable, so only other values need a deep copy
1019                meta = copy._meta = dict(node._meta)
1020                for k, v in meta.items():
1021                    if type(v) not in _IMMUTABLE_META_TYPES:
1022                        meta[k] = deepcopy(v)
1023            if node._hash is not None:
1024                copy._hash = node._hash
1025
1026            for k, vs in node.args.items():
1027                if isinstance(vs, Expr):
1028                    stack.append((vs, vs.__class__()))
1029                    copy.set(k, stack[-1][-1])
1030                elif type(vs) is list:
1031                    copy.args[k] = []
1032
1033                    for v in vs:
1034                        if isinstance(v, Expr):
1035                            stack.append((v, v.__class__()))
1036                            copy.append(k, stack[-1][-1])
1037                        else:
1038                            copy.append(k, v)
1039                else:
1040                    copy.args[k] = vs
1041
1042        return root
1043
1044    def copy(self: E) -> E:
1045        return deepcopy(self)
1046
1047    def add_comments(self, comments: list[str] | None = None, prepend: bool = False) -> None:
1048        if self.comments is None:
1049            self.comments = []
1050
1051        if comments:
1052            for comment in comments:
1053                _, *meta = comment.split(SQLGLOT_META)
1054                if meta:
1055                    for kv in "".join(meta).split(","):
1056                        k, *v = kv.split("=")
1057                        self.meta[k.strip()] = to_bool(v[0].strip() if v else True)
1058
1059                if not prepend:
1060                    self.comments.append(comment)
1061
1062            if prepend:
1063                self.comments = comments + self.comments
1064
1065    def pop_comments(self) -> list[str]:
1066        comments = self.comments or []
1067        self.comments = None
1068        return comments
1069
1070    def append(self, arg_key: str, value: t.Any) -> None:
1071        node: Expr | None = self
1072        while node and node._hash is not None:
1073            node._hash = None
1074            node = node.parent
1075
1076        if type(self.args.get(arg_key)) is not list:
1077            self.args[arg_key] = []
1078        self._set_parent(arg_key, value)
1079        values = self.args[arg_key]
1080        if isinstance(value, Expr):
1081            value.index = len(values)
1082        values.append(value)
1083
1084    def set(
1085        self,
1086        arg_key: str,
1087        value: object,
1088        index: int | None = None,
1089        overwrite: bool = True,
1090    ) -> None:
1091        node: Expr | None = self
1092
1093        while node and node._hash is not None:
1094            node._hash = None
1095            node = node.parent
1096
1097        if index is not None:
1098            expressions = self.args.get(arg_key) or []
1099
1100            if seq_get(expressions, index) is None:
1101                return
1102
1103            if value is None:
1104                expressions.pop(index)
1105                for v in expressions[index:]:
1106                    v.index = v.index - 1
1107                return
1108
1109            if isinstance(value, list):
1110                expressions.pop(index)
1111                expressions[index:index] = value
1112            elif overwrite:
1113                expressions[index] = value
1114            else:
1115                expressions.insert(index, value)
1116
1117            value = expressions
1118        elif value is None:
1119            self.args.pop(arg_key, None)
1120            return
1121
1122        self.args[arg_key] = value
1123        self._set_parent(arg_key, value, index)
1124
1125    def _set_parent(self, arg_key: str, value: object, index: int | None = None) -> None:
1126        if isinstance(value, Expr):
1127            value.parent = self
1128            value.arg_key = arg_key
1129            value.index = index
1130        elif isinstance(value, list):
1131            for i, v in enumerate(value):
1132                if isinstance(v, Expr):
1133                    v.parent = self
1134                    v.arg_key = arg_key
1135                    v.index = i
1136
1137    def set_kwargs(self, kwargs: Mapping[str, object]) -> Self:
1138        """Set multiples keyword arguments at once, using `.set()` method.
1139
1140        Args:
1141            kwargs (Mapping[str, object]): a `Mapping` of arg keys to values to set.
1142        Returns:
1143            Self: The same `Expression` with the updated arguments.
1144        """
1145        if kwargs:
1146            for k, v in kwargs.items():
1147                self.set(k, v)
1148        return self
1149
1150    @property
1151    def depth(self) -> int:
1152        if self.parent:
1153            return self.parent.depth + 1
1154        return 0
1155
1156    def iter_expressions(self: E, reverse: bool = False) -> Iterator[E]:
1157        for vs in reversed(self.args.values()) if reverse else self.args.values():
1158            if isinstance(vs, list):
1159                for v in reversed(vs) if reverse else vs:
1160                    if isinstance(v, Expr):
1161                        yield t.cast(E, v)
1162            elif isinstance(vs, Expr):
1163                yield t.cast(E, vs)
1164
1165    def find(self, *expression_types: Type[E], bfs: bool = True) -> E | None:
1166        return next(self.find_all(*expression_types, bfs=bfs), None)
1167
1168    def find_all(self, *expression_types: Type[E], bfs: bool = True) -> Iterator[E]:
1169        for expression in self.walk(bfs=bfs):
1170            if isinstance(expression, expression_types):
1171                yield expression
1172
1173    def find_ancestor(self, *expression_types: Type[E]) -> E | None:
1174        ancestor = self.parent
1175        while ancestor and not isinstance(ancestor, expression_types):
1176            ancestor = ancestor.parent
1177        return ancestor  # type: ignore[return-value]
1178
1179    @property
1180    def parent_select(self) -> Select | None:
1181        from sqlglot.expressions.query import Select as _Select
1182
1183        return self.find_ancestor(_Select)
1184
1185    @property
1186    def same_parent(self) -> bool:
1187        return type(self.parent) is self.__class__
1188
1189    def root(self) -> Expr:
1190        expression: Expr = self
1191        while expression.parent:
1192            expression = expression.parent
1193        return expression
1194
1195    def walk(
1196        self, bfs: bool = True, prune: t.Callable[[Expr], bool] | None = None
1197    ) -> Iterator[Expr]:
1198        if bfs:
1199            yield from self.bfs(prune=prune)
1200        else:
1201            yield from self.dfs(prune=prune)
1202
1203    def dfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
1204        stack = [self]
1205
1206        while stack:
1207            node = stack.pop()
1208            yield node
1209            if prune and prune(node):
1210                continue
1211            for v in node.iter_expressions(reverse=True):
1212                stack.append(v)
1213
1214    def bfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
1215        queue: deque[Expr] = deque()
1216        queue.append(self)
1217
1218        while queue:
1219            node = queue.popleft()
1220            yield node
1221            if prune and prune(node):
1222                continue
1223            for v in node.iter_expressions():
1224                queue.append(v)
1225
1226    def unnest(self) -> Expr:
1227        expression = self
1228        while type(expression) is Paren:
1229            expression = expression.this
1230        return expression
1231
1232    def unalias(self) -> Expr:
1233        if isinstance(self, Alias):
1234            return self.this
1235        return self
1236
1237    def unnest_operands(self) -> tuple[Expr, ...]:
1238        return tuple(arg.unnest() for arg in self.iter_expressions())
1239
1240    def flatten(self, unnest: bool = True) -> Iterator[Expr]:
1241        for node in self.dfs(prune=lambda n: bool(n.parent and type(n) is not self.__class__)):
1242            if type(node) is not self.__class__:
1243                yield node.unnest() if unnest and not node.is_subquery else node
1244
1245    def __str__(self) -> str:
1246        return self.sql()
1247
1248    def __repr__(self) -> str:
1249        return _to_s(self)
1250
1251    def to_s(self) -> str:
1252        return _to_s(self, verbose=True)
1253
1254    def sql(
1255        self, dialect: DialectType = None, copy: bool = True, **opts: Unpack[GeneratorNoDialectArgs]
1256    ) -> str:
1257        from sqlglot.dialects.dialect import Dialect
1258
1259        return Dialect.get_or_raise(dialect).generate(self, copy=copy, **opts)
1260
1261    def transform(
1262        self, fun: t.Callable[..., T], *args: object, copy: bool = True, **kwargs: object
1263    ) -> T:
1264        root: t.Any = None
1265        new_node: t.Any = None
1266
1267        for node in (self.copy() if copy else self).dfs(prune=lambda n: n is not new_node):
1268            parent, arg_key, index = node.parent, node.arg_key, node.index
1269            new_node = fun(node, *args, **kwargs)
1270
1271            if not root:
1272                root = new_node
1273            elif parent and arg_key and new_node is not node:
1274                parent.set(arg_key, new_node, index)
1275
1276        assert root
1277        return root
1278
1279    def replace(self, expression: T) -> T:
1280        parent = self.parent
1281
1282        if not parent or parent is expression:
1283            return expression
1284
1285        key = self.arg_key
1286
1287        if key:
1288            value = parent.args.get(key)
1289
1290            if type(expression) is list and isinstance(value, Expr):
1291                # We are trying to replace an Expr with a list, so it's assumed that
1292                # the intention was to really replace the parent of this expression.
1293                if value.parent:
1294                    value.parent.replace(expression)
1295            else:
1296                parent.set(key, expression, self.index)
1297
1298        if expression is not self:
1299            self.parent = None
1300            self.arg_key = None
1301            self.index = None
1302
1303        return expression
1304
1305    def pop(self: E) -> E:
1306        self.replace(None)
1307        return self
1308
1309    def assert_is(self, type_: Type[E]) -> E:
1310        if not isinstance(self, type_):
1311            raise AssertionError(f"{self} is not {type_}.")
1312        return self
1313
1314    def error_messages(self, args: Sequence[object] | None = None) -> list[str]:
1315        if UNITTEST:
1316            for k in self.args:
1317                if k not in self.arg_types:
1318                    raise TypeError(f"Unexpected keyword: '{k}' for {self.__class__}")
1319
1320        errors: list[str] | None = None
1321
1322        for k in self.required_args:
1323            v = self.args.get(k)
1324            if v is None or (isinstance(v, list) and not v):
1325                if errors is None:
1326                    errors = []
1327                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
1328
1329        if (
1330            args
1331            and isinstance(self, Func)
1332            and len(args) > len(self.arg_types)
1333            and not self.is_var_len_args
1334        ):
1335            if errors is None:
1336                errors = []
1337            errors.append(
1338                f"The number of provided arguments ({len(args)}) is greater than "
1339                f"the maximum number of supported arguments ({len(self.arg_types)})"
1340            )
1341
1342        return errors or []
1343
1344    def and_(
1345        self,
1346        *expressions: ExpOrStr | None,
1347        dialect: DialectType = None,
1348        copy: bool = True,
1349        wrap: bool = True,
1350        **opts: Unpack[ParserNoDialectArgs],
1351    ) -> Condition:
1352        return and_(self, *expressions, dialect=dialect, copy=copy, wrap=wrap, **opts)
1353
1354    def or_(
1355        self,
1356        *expressions: ExpOrStr | None,
1357        dialect: DialectType = None,
1358        copy: bool = True,
1359        wrap: bool = True,
1360        **opts: Unpack[ParserNoDialectArgs],
1361    ) -> Condition:
1362        return or_(self, *expressions, dialect=dialect, copy=copy, wrap=wrap, **opts)
1363
1364    def not_(self, copy: bool = True) -> Not:
1365        return not_(self, copy=copy)
1366
1367    def update_positions(
1368        self: E,
1369        other: Token | Expr | None = None,
1370        line: int | None = None,
1371        col: int | None = None,
1372        start: int | None = None,
1373        end: int | None = None,
1374    ) -> E:
1375        if isinstance(other, Token):
1376            meta = self.meta
1377            meta["line"] = other.line
1378            meta["col"] = other.col
1379            meta["start"] = other.start
1380            meta["end"] = other.end
1381        elif other is not None:
1382            other_meta = other._meta
1383            if other_meta:
1384                meta = self.meta
1385                for k in POSITION_META_KEYS:
1386                    if k in other_meta:
1387                        meta[k] = other_meta[k]
1388        else:
1389            meta = self.meta
1390            meta["line"] = line
1391            meta["col"] = col
1392            meta["start"] = start
1393            meta["end"] = end
1394        return self
1395
1396    def as_(
1397        self,
1398        alias: str | Identifier,
1399        quoted: bool | None = None,
1400        dialect: DialectType = None,
1401        copy: bool = True,
1402        table: bool | Sequence[str | Identifier] = False,
1403        **opts: Unpack[ParserNoDialectArgs],
1404    ) -> Expr:
1405        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, table=table, **opts)
1406
1407    def _binop(self, klass: Type[E], other: t.Any, reverse: bool = False) -> E:
1408        left: Expr = self.copy()
1409        right = convert(other, copy=True)
1410        if reverse:
1411            left, right = right, left
1412
1413        # NOT binds more tightly than AND and OR, but more loosely than comparisons and arithmetic.
1414        if not issubclass(klass, Connector):
1415            left = _wrap(left, Not)
1416            right = _wrap(right, Not)
1417
1418        # A repeated operator can chain on the left, but SQL may reject chained predicates.
1419        if not isinstance(left, klass) or isinstance(left, Predicate):
1420            left = _wrap(left, Binary)
1421        return klass(this=left, expression=_wrap(right, Binary))
1422
1423    def __getitem__(self, other: ExpOrStr | tuple[ExpOrStr, ...]) -> Bracket:
1424        return Bracket(
1425            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
1426        )
1427
1428    def __iter__(self) -> Iterator:
1429        if "expressions" in self.arg_types:
1430            return iter(self.args.get("expressions") or [])
1431        # We define this because __getitem__ converts Expr into an iterable, which is
1432        # problematic because one can hit infinite loops if they do "for x in some_expr: ..."
1433        # See: https://peps.python.org/pep-0234/
1434        raise TypeError(f"'{self.__class__.__name__}' object is not iterable")
1435
1436    def isin(
1437        self,
1438        *expressions: t.Any,
1439        query: ExpOrStr | None = None,
1440        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
1441        dialect: DialectType = None,
1442        copy: bool = True,
1443        **opts: Unpack[ParserNoDialectArgs],
1444    ) -> In:
1445        from sqlglot.expressions.query import Query
1446
1447        subquery: Expr | None = None
1448        if query:
1449            subquery = maybe_parse(query, dialect=dialect, copy=copy, **opts)
1450            if isinstance(subquery, Query):
1451                subquery = subquery.subquery(copy=False)
1452        unnest_list: list[ExpOrStr] = ensure_list(unnest)
1453        return In(
1454            this=maybe_copy(self, copy),
1455            expressions=[convert(e, copy=copy) for e in expressions],
1456            query=subquery,
1457            unnest=(
1458                _lazy_unnest(
1459                    expressions=[
1460                        maybe_parse(e, dialect=dialect, copy=copy, **opts) for e in unnest_list
1461                    ]
1462                )
1463                if unnest
1464                else None
1465            ),
1466        )
1467
1468    def between(
1469        self, low: t.Any, high: t.Any, copy: bool = True, symmetric: bool | None = None
1470    ) -> Between:
1471        between = Between(
1472            this=maybe_copy(self, copy),
1473            low=convert(low, copy=copy),
1474            high=convert(high, copy=copy),
1475        )
1476        if symmetric is not None:
1477            between.set("symmetric", symmetric)
1478
1479        return between
1480
1481    def is_(self, other: ExpOrStr) -> Is:
1482        if isinstance(other, Not) and isinstance(other.this, (Null, Boolean)):
1483            predicate = self._binop(Is, other.this)
1484            predicate.set("negate", True)
1485            return predicate
1486        return self._binop(Is, other)
1487
1488    def like(self, other: ExpOrStr) -> Like:
1489        return self._binop(Like, other)
1490
1491    def ilike(self, other: ExpOrStr) -> ILike:
1492        return self._binop(ILike, other)
1493
1494    def eq(self, other: t.Any) -> EQ:
1495        return self._binop(EQ, other)
1496
1497    def neq(self, other: t.Any) -> NEQ:
1498        return self._binop(NEQ, other)
1499
1500    def rlike(self, other: ExpOrStr) -> RegexpLike:
1501        return self._binop(RegexpLike, other)
1502
1503    def div(self, other: ExpOrStr, typed: bool = False, safe: bool = False) -> Div:
1504        div = self._binop(Div, other)
1505        div.set("typed", typed)
1506        div.set("safe", safe)
1507        return div
1508
1509    def asc(self, nulls_first: bool = True) -> Ordered:
1510        return Ordered(this=self.copy(), nulls_first=nulls_first)
1511
1512    def desc(self, nulls_first: bool = False) -> Ordered:
1513        return Ordered(this=self.copy(), desc=True, nulls_first=nulls_first)
1514
1515    def __lt__(self, other: t.Any) -> LT:
1516        return self._binop(LT, other)
1517
1518    def __le__(self, other: t.Any) -> LTE:
1519        return self._binop(LTE, other)
1520
1521    def __gt__(self, other: t.Any) -> GT:
1522        return self._binop(GT, other)
1523
1524    def __ge__(self, other: t.Any) -> GTE:
1525        return self._binop(GTE, other)
1526
1527    def __add__(self, other: t.Any) -> Add:
1528        return self._binop(Add, other)
1529
1530    def __radd__(self, other: t.Any) -> Add:
1531        return self._binop(Add, other, reverse=True)
1532
1533    def __sub__(self, other: t.Any) -> Sub:
1534        return self._binop(Sub, other)
1535
1536    def __rsub__(self, other: t.Any) -> Sub:
1537        return self._binop(Sub, other, reverse=True)
1538
1539    def __mul__(self, other: t.Any) -> Mul:
1540        return self._binop(Mul, other)
1541
1542    def __rmul__(self, other: t.Any) -> Mul:
1543        return self._binop(Mul, other, reverse=True)
1544
1545    def __truediv__(self, other: t.Any) -> Div:
1546        return self._binop(Div, other)
1547
1548    def __rtruediv__(self, other: t.Any) -> Div:
1549        return self._binop(Div, other, reverse=True)
1550
1551    def __floordiv__(self, other: t.Any) -> IntDiv:
1552        return self._binop(IntDiv, other)
1553
1554    def __rfloordiv__(self, other: t.Any) -> IntDiv:
1555        return self._binop(IntDiv, other, reverse=True)
1556
1557    def __mod__(self, other: t.Any) -> Mod:
1558        return self._binop(Mod, other)
1559
1560    def __rmod__(self, other: t.Any) -> Mod:
1561        return self._binop(Mod, other, reverse=True)
1562
1563    def __pow__(self, other: t.Any) -> Pow:
1564        return self._binop(Pow, other)
1565
1566    def __rpow__(self, other: t.Any) -> Pow:
1567        return self._binop(Pow, other, reverse=True)
1568
1569    def __and__(self, other: t.Any) -> And:
1570        return self._binop(And, other)
1571
1572    def __rand__(self, other: t.Any) -> And:
1573        return self._binop(And, other, reverse=True)
1574
1575    def __or__(self, other: t.Any) -> Or:
1576        return self._binop(Or, other)
1577
1578    def __ror__(self, other: t.Any) -> Or:
1579        return self._binop(Or, other, reverse=True)
1580
1581    def __neg__(self) -> Neg:
1582        return Neg(this=_wrap(self.copy(), Binary))
1583
1584    def __invert__(self) -> Not:
1585        return not_(self.copy())
1586
1587
1588IntoType = t.Union[Type[Expr], Collection[Type[Expr]]]
1589ExpOrStr = t.Union[int, str, Expr]
1590
1591
1592@trait
1593class Condition(Expr):
1594    """Logical conditions like x AND y, or simply x"""
1595
1596
1597@trait
1598class Predicate(Condition):
1599    """Any condition that evaluates to a boolean, e.g. x = y, x LIKE 'a%', a @> b."""
1600
1601
1602class Cache(Expression):
1603    arg_types = {
1604        "this": True,
1605        "lazy": False,
1606        "options": False,
1607        "expression": False,
1608    }
1609
1610
1611class Uncache(Expression):
1612    arg_types = {"this": True, "exists": False}
1613
1614
1615class Refresh(Expression):
1616    arg_types = {
1617        "this": True,
1618        "kind": True,
1619        "partition_start": False,
1620        "partition_end": False,
1621        "force": False,
1622        "mode": False,
1623    }
1624
1625
1626class LockingStatement(Expression):
1627    arg_types = {"this": True, "expression": True}
1628
1629
1630@trait
1631class ColumnConstraintKind(Expr):
1632    pass
1633
1634
1635@trait
1636class SubqueryPredicate(Predicate):
1637    pass
1638
1639
1640class All(Expression, SubqueryPredicate):
1641    pass
1642
1643
1644class Any(Expression, SubqueryPredicate):
1645    pass
1646
1647
1648@trait
1649class Binary(Condition):
1650    arg_types: t.ClassVar[dict[str, bool]] = {"this": True, "expression": True}
1651
1652    @property
1653    def left(self) -> Expr:
1654        return self.args["this"]
1655
1656    @property
1657    def right(self) -> Expr:
1658        return self.args["expression"]
1659
1660
1661@trait
1662class Connector(Binary):
1663    pass
1664
1665
1666@trait
1667class Func(Condition):
1668    """
1669    The base class for all function expressions.
1670
1671    Attributes:
1672        is_var_len_args (bool): if set to True the argument identified by var_len_arg_key will be
1673            treated as a variable length argument and the argument's value will be stored as a list.
1674        var_len_arg_key (str): the arg_types key that collects the variable length arguments.
1675            Arguments preceding it in arg_types are filled positionally; those following it (e.g.
1676            dialect flags) are never populated by from_arg_list.
1677        _sql_names (list): the SQL name (1st item in the list) and aliases (subsequent items) for this
1678            function expression. These values are used to map this node to a name during parsing as
1679            well as to provide the function's name during SQL string generation. By default the SQL
1680            name is set to the expression's class name transformed to snake case.
1681    """
1682
1683    is_var_len_args: t.ClassVar[bool] = False
1684    var_len_arg_key: t.ClassVar[str] = "expressions"
1685    _sql_names: t.ClassVar[list[str]] = []
1686
1687    @classmethod
1688    def from_arg_list(cls, args: Sequence[object]) -> Self:
1689        if cls.is_var_len_args:
1690            all_arg_keys = tuple(cls.arg_types)
1691            var_len_index = all_arg_keys.index(cls.var_len_arg_key)
1692
1693            args_dict = {arg_key: arg for arg, arg_key in zip(args, all_arg_keys[:var_len_index])}
1694            args_dict[cls.var_len_arg_key] = args[var_len_index:]
1695        else:
1696            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
1697
1698        return cls(**args_dict)
1699
1700    @classmethod
1701    def sql_names(cls) -> list[str]:
1702        if cls is Func:
1703            raise NotImplementedError(
1704                "SQL name is only supported by concrete function implementations"
1705            )
1706        if not cls._sql_names:
1707            return [camel_to_snake_case(cls.__name__)]
1708        return cls._sql_names
1709
1710    @classmethod
1711    def sql_name(cls) -> str:
1712        sql_names = cls.sql_names()
1713        assert sql_names, f"Expected non-empty 'sql_names' for Func: {cls.__name__}."
1714        return sql_names[0]
1715
1716    @classmethod
1717    def default_parser_mappings(cls) -> dict[str, t.Callable[[Sequence[object]], Self]]:
1718        return {name: cls.from_arg_list for name in cls.sql_names()}
1719
1720
1721@trait
1722class AggFunc(Func):
1723    pass
1724
1725
1726class Column(Expression, Condition):
1727    # "shadow" marks a column whose qualifier is shadowed by a projection alias, so it must be
1728    # rendered unqualified in dialects where PROJECTION_ALIASES_SHADOW_SOURCE_NAMES is set
1729    arg_types = {
1730        "this": True,
1731        "table": False,
1732        "db": False,
1733        "catalog": False,
1734        "join_mark": False,
1735        "shadow": False,
1736    }
1737
1738    @property
1739    def table(self) -> str:
1740        return self.text("table")
1741
1742    @property
1743    def db(self) -> str:
1744        return self.text("db")
1745
1746    @property
1747    def catalog(self) -> str:
1748        return self.text("catalog")
1749
1750    @property
1751    def output_name(self) -> str:
1752        return self.name
1753
1754    @property
1755    def parts(self) -> list[Expr]:
1756        """Return the parts of a column in order catalog, db, table, name."""
1757        return [
1758            self.args[part] for part in ("catalog", "db", "table", "this") if self.args.get(part)
1759        ]
1760
1761    def to_dot(self, include_dots: bool = True) -> Expr:
1762        """Converts the column into a dot expression."""
1763        parts = self.parts
1764        parent = self.parent
1765
1766        if include_dots:
1767            while isinstance(parent, Dot):
1768                parts.append(parent.expression)
1769                parent = parent.parent
1770
1771        return Dot.build(deepcopy(parts)) if len(parts) > 1 else parts[0]
1772
1773
1774class Literal(Expression, Condition):
1775    arg_types = {"this": True, "is_string": True}
1776    _hash_raw_args = True
1777    is_primitive = True
1778
1779    @classmethod
1780    def number(cls, number: object) -> Literal | Neg:
1781        lit = cls(this=str(number), is_string=False)
1782        try:
1783            to_py = lit.to_py()
1784            if not isinstance(to_py, str) and to_py < 0:
1785                lit.set("this", str(to_py.copy_abs() if isinstance(to_py, Decimal) else abs(to_py)))
1786                return Neg(this=lit)
1787        except Exception:
1788            pass
1789        return lit
1790
1791    @classmethod
1792    def string(cls, string: object) -> Literal:
1793        return cls(this=str(string), is_string=True)
1794
1795    @property
1796    def output_name(self) -> str:
1797        return self.name
1798
1799    def to_py(self) -> int | str | Decimal:
1800        if self.is_number:
1801            try:
1802                return int(self.this)
1803            except ValueError:
1804                try:
1805                    return Decimal(self.this)
1806                except InvalidOperation as e:
1807                    raise ValueError(f"Invalid numeric literal: {self.this!r}") from e
1808        return self.this
1809
1810
1811class Var(Expression):
1812    is_primitive = True
1813
1814
1815class WithinGroup(Expression):
1816    arg_types = {"this": True, "expression": False}
1817
1818
1819class Pseudocolumn(Column):
1820    pass
1821
1822
1823class Hint(Expression):
1824    arg_types = {"expressions": True}
1825
1826
1827class JoinHint(Expression):
1828    arg_types = {"this": True, "expressions": True}
1829
1830
1831class Identifier(Expression):
1832    arg_types = {
1833        "this": True,
1834        "quoted": False,
1835        "global_": False,
1836        "temporary": False,
1837    }
1838    is_primitive = True
1839    _hash_raw_args = True
1840
1841    @property
1842    def quoted(self) -> bool:
1843        return bool(self.args.get("quoted"))
1844
1845    @property
1846    def output_name(self) -> str:
1847        return self.name
1848
1849
1850# https://docs.snowflake.com/en/sql-reference/identifier-literal
1851# "expressions" holds the arguments when the resolved identifier is invoked as a
1852# function, e.g. `IDENTIFIER('my_func')(1, 2)`
1853class DynamicIdentifier(Expression, Func):
1854    arg_types = {"this": True, "expressions": False}
1855
1856    @property
1857    def name(self) -> str:
1858        return self.this.name if self.this else ""
1859
1860
1861class Opclass(Expression):
1862    arg_types = {"this": True, "expression": True}
1863
1864
1865class Star(Expression):
1866    arg_types = {"except_": False, "replace": False, "rename": False, "ilike": False}
1867
1868    @property
1869    def name(self) -> str:
1870        return "*"
1871
1872    @property
1873    def output_name(self) -> str:
1874        return self.name
1875
1876
1877class Parameter(Expression, Condition):
1878    arg_types = {"this": True, "expression": False}
1879
1880
1881class SessionParameter(Expression, Condition):
1882    arg_types = {"this": True, "kind": False}
1883
1884
1885class Placeholder(Expression, Condition):
1886    arg_types = {"this": False, "kind": False, "widget": False, "jdbc": False}
1887    _hash_raw_args = True
1888
1889    @property
1890    def name(self) -> str:
1891        return self.text("this") or "?"
1892
1893
1894class Null(Expression, Condition):
1895    arg_types = {}
1896
1897    @property
1898    def name(self) -> str:
1899        return "NULL"
1900
1901    def to_py(self) -> t.Literal[None]:
1902        return None
1903
1904
1905class Boolean(Expression, Condition):
1906    is_primitive = True
1907
1908    def to_py(self) -> bool:
1909        return self.this
1910
1911
1912class Dot(Expression, Binary):
1913    arg_types = {"this": True, "expression": True, "subcolumn_depth": False}
1914
1915    @property
1916    def is_star(self) -> bool:
1917        return self.expression.is_star
1918
1919    @property
1920    def name(self) -> str:
1921        return self.expression.name
1922
1923    @property
1924    def output_name(self) -> str:
1925        return self.name
1926
1927    @classmethod
1928    def build(cls, expressions: Sequence[Expr]) -> Dot:
1929        """Build a Dot object with a sequence of expressions."""
1930        if len(expressions) < 2:
1931            raise ValueError("Dot requires >= 2 expressions.")
1932
1933        return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))
1934
1935    @property
1936    def parts(self) -> list[Expr]:
1937        """Return the parts of a table / column in order catalog, db, table."""
1938        this, *parts = self.flatten()
1939
1940        parts.reverse()
1941
1942        for arg in COLUMN_PARTS:
1943            part = this.args.get(arg)
1944
1945            if isinstance(part, Expr):
1946                parts.append(part)
1947
1948        parts.reverse()
1949        return parts
1950
1951
1952class Kwarg(Expression, Binary):
1953    """Kwarg in special functions like func(kwarg => y)."""
1954
1955
1956class Alias(Expression):
1957    arg_types = {"this": True, "alias": False}
1958
1959    @property
1960    def output_name(self) -> str:
1961        return self.alias
1962
1963
1964class PivotAlias(Alias):
1965    pass
1966
1967
1968class PivotAny(Expression):
1969    arg_types = {"this": False}
1970
1971
1972class Aliases(Expression):
1973    arg_types = {"this": True, "expressions": True}
1974
1975    @property
1976    def aliases(self) -> list[Expr]:
1977        return self.expressions
1978
1979
1980class Bracket(Expression, Condition):
1981    # https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#array_subscript_operator
1982    arg_types = {
1983        "this": True,
1984        "expressions": True,
1985        "offset": False,
1986        "safe": False,
1987        "returns_list_for_maps": False,
1988        "json_access": False,
1989    }
1990
1991    @property
1992    def output_name(self) -> str:
1993        if len(self.expressions) == 1:
1994            return self.expressions[0].output_name
1995
1996        return super().output_name
1997
1998
1999class ForIn(Expression):
2000    arg_types = {"this": True, "expression": True}
2001
2002
2003class IgnoreNulls(Expression):
2004    pass
2005
2006
2007class RespectNulls(Expression):
2008    pass
2009
2010
2011class HavingMax(Expression):
2012    arg_types = {"this": True, "expression": True, "max": True}
2013
2014
2015class SafeFunc(Expression, Func):
2016    pass
2017
2018
2019class Typeof(Expression, Func):
2020    pass
2021
2022
2023class ParameterizedAgg(Expression, AggFunc):
2024    arg_types = {"this": True, "expressions": True, "params": True}
2025    _hash_raw_args = True
2026
2027
2028class Anonymous(Expression, Func):
2029    arg_types = {"this": True, "expressions": False}
2030    is_var_len_args = True
2031
2032    @property
2033    def name(self) -> str:
2034        return self.this if isinstance(self.this, str) else self.this.name
2035
2036
2037class AnonymousAggFunc(Expression, AggFunc):
2038    arg_types = {"this": True, "expressions": False}
2039    is_var_len_args = True
2040    _hash_raw_args = True
2041
2042
2043class CombinedAggFunc(AnonymousAggFunc):
2044    arg_types = {"this": True, "expressions": False}
2045
2046
2047class CombinedParameterizedAgg(ParameterizedAgg):
2048    arg_types = {"this": True, "expressions": True, "params": True}
2049
2050
2051class HashAgg(Expression, AggFunc):
2052    arg_types = {"this": True, "expressions": False}
2053    is_var_len_args = True
2054
2055
2056class Hll(Expression, AggFunc):
2057    arg_types = {"this": True, "expressions": False}
2058    is_var_len_args = True
2059
2060
2061class ApproxDistinct(Expression, AggFunc):
2062    arg_types = {"this": True, "accuracy": False}
2063    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
2064
2065
2066class Slice(Expression):
2067    arg_types = {"this": False, "expression": False, "step": False}
2068
2069
2070@trait
2071class TimeUnit(Expr):
2072    """Automatically converts unit arg into a var."""
2073
2074    UNABBREVIATED_UNIT_NAME: t.ClassVar[dict[str, str]] = {
2075        "D": "DAY",
2076        "H": "HOUR",
2077        "M": "MINUTE",
2078        "MS": "MILLISECOND",
2079        "NS": "NANOSECOND",
2080        "Q": "QUARTER",
2081        "S": "SECOND",
2082        "US": "MICROSECOND",
2083        "W": "WEEK",
2084        "Y": "YEAR",
2085    }
2086
2087    VAR_LIKE: t.ClassVar[tuple[Type[Expr], ...]] = (Column, Literal, Var)
2088
2089    def __init__(self, **args: object) -> None:
2090        super().__init__(**args)
2091
2092        unit = self.args.get("unit")
2093        if (
2094            unit
2095            and type(unit) in TimeUnit.VAR_LIKE
2096            and not (isinstance(unit, Column) and len(unit.parts) != 1)
2097        ):
2098            unit = Var(this=(self.UNABBREVIATED_UNIT_NAME.get(unit.name) or unit.name).upper())
2099            self.args["unit"] = unit
2100            self._set_parent("unit", unit)
2101        elif type(unit).__name__ == "Week":
2102            unit.set("this", Var(this=unit.this.name.upper()))  # type: ignore[union-attr]
2103
2104    @property
2105    def unit(self) -> Expr | None:
2106        return self.args.get("unit")
2107
2108
2109class _TimeUnit(Expression, TimeUnit):
2110    """Automatically converts unit arg into a var."""
2111
2112    arg_types = {"unit": False}
2113
2114
2115@trait
2116class IntervalOp(TimeUnit):
2117    def interval(self) -> Interval:
2118        from sqlglot.expressions.datatypes import Interval
2119
2120        expr = self.expression
2121        return Interval(
2122            this=expr.copy() if expr is not None else None,
2123            unit=self.unit.copy() if self.unit else None,
2124        )
2125
2126
2127class Filter(Expression):
2128    arg_types = {"this": True, "expression": True}
2129
2130
2131class Per(Expression):
2132    arg_types = {"this": True, "expressions": True}
2133
2134
2135class Check(Expression):
2136    pass
2137
2138
2139class Ordered(Expression):
2140    arg_types = {"this": True, "desc": False, "nulls_first": True, "with_fill": False}
2141
2142    @property
2143    def name(self) -> str:
2144        return self.this.name
2145
2146
2147class Add(Expression, Binary):
2148    pass
2149
2150
2151class BitwiseAnd(Expression, Binary):
2152    arg_types = {"this": True, "expression": True, "padside": False}
2153
2154
2155class BitwiseLeftShift(Expression, Binary):
2156    arg_types = {"this": True, "expression": True, "requires_int128": False}
2157
2158
2159class BitwiseOr(Expression, Binary):
2160    arg_types = {"this": True, "expression": True, "padside": False}
2161
2162
2163class BitwiseRightShift(Expression, Binary):
2164    arg_types = {"this": True, "expression": True, "requires_int128": False}
2165
2166
2167class BitwiseXor(Expression, Binary):
2168    arg_types = {"this": True, "expression": True, "padside": False}
2169
2170
2171class Div(Expression, Binary):
2172    arg_types = {"this": True, "expression": True, "typed": False, "safe": False}
2173
2174
2175class Overlaps(Expression, Binary, Predicate):
2176    pass
2177
2178
2179class ExtendsLeft(Expression, Binary, Predicate):
2180    pass
2181
2182
2183class ExtendsRight(Expression, Binary, Predicate):
2184    pass
2185
2186
2187class DPipe(Expression, Binary):
2188    arg_types = {"this": True, "expression": True, "safe": False}
2189
2190
2191class EQ(Expression, Binary, Predicate):
2192    pass
2193
2194
2195class NullSafeEQ(Expression, Binary, Predicate):
2196    pass
2197
2198
2199class NullSafeNEQ(Expression, Binary, Predicate):
2200    pass
2201
2202
2203class PropertyEQ(Expression, Binary):
2204    pass
2205
2206
2207class Distance(Expression, Binary):
2208    pass
2209
2210
2211class DistanceNd(Expression, Binary):
2212    pass
2213
2214
2215class Escape(Expression, Binary):
2216    pass
2217
2218
2219class Glob(Expression, Binary, Predicate):
2220    pass
2221
2222
2223class GT(Expression, Binary, Predicate):
2224    pass
2225
2226
2227class GTE(Expression, Binary, Predicate):
2228    pass
2229
2230
2231class ILike(Expression, Binary, Predicate):
2232    arg_types = {"this": True, "expression": True, "negate": False}
2233
2234
2235class IntDiv(Expression, Binary):
2236    pass
2237
2238
2239class Is(Expression, Binary, Predicate):
2240    arg_types = {"this": True, "expression": True, "negate": False}
2241
2242
2243class Like(Expression, Binary, Predicate):
2244    arg_types = {"this": True, "expression": True, "negate": False}
2245
2246
2247class Match(Expression, Binary, Predicate):
2248    arg_types = {"this": True, "expression": True, "kind": False, "analyzer": False}
2249
2250
2251class LT(Expression, Binary, Predicate):
2252    pass
2253
2254
2255class LTE(Expression, Binary, Predicate):
2256    pass
2257
2258
2259class Mod(Expression, Binary):
2260    arg_types = {"this": True, "expression": True, "safe": False}
2261
2262
2263class Mul(Expression, Binary):
2264    pass
2265
2266
2267class NEQ(Expression, Binary, Predicate):
2268    pass
2269
2270
2271class NestedJSONSelect(Expression, Binary):
2272    pass
2273
2274
2275class Operator(Expression, Binary):
2276    arg_types = {"this": True, "operator": True, "expression": True}
2277
2278
2279class SimilarTo(Expression, Binary, Predicate):
2280    pass
2281
2282
2283class Sub(Expression, Binary):
2284    pass
2285
2286
2287class Adjacent(Expression, Binary, Predicate):
2288    pass
2289
2290
2291class Unary(Expression, Condition):
2292    pass
2293
2294
2295class BitwiseNot(Unary):
2296    pass
2297
2298
2299class Not(Unary):
2300    pass
2301
2302
2303class Paren(Unary):
2304    @property
2305    def output_name(self) -> str:
2306        return self.this.name
2307
2308
2309class Pos(Unary):
2310    pass
2311
2312
2313class Neg(Unary):
2314    def to_py(self) -> int | Decimal:
2315        if self.is_number:
2316            return self.this.to_py() * -1
2317        return super().to_py()
2318
2319
2320class AtIndex(Expression):
2321    arg_types = {"this": True, "expression": True}
2322
2323
2324class AtTimeZone(Expression):
2325    # session_zone: a zoneless operand is read in the session time zone (e.g. Presto, Trino)
2326    arg_types = {"this": True, "zone": True, "session_zone": False}
2327
2328
2329class FromTimeZone(Expression):
2330    arg_types = {"this": True, "zone": True}
2331
2332
2333class FormatPhrase(Expression):
2334    """Format override for a column in Teradata.
2335    Can be expanded to additional dialects as needed
2336
2337    https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Types-and-Literals/Data-Type-Formats-and-Format-Phrases/FORMAT
2338    """
2339
2340    arg_types = {"this": True, "format": True}
2341
2342    @property
2343    def name(self) -> str:
2344        return self.this.name
2345
2346    @property
2347    def output_name(self) -> str:
2348        return self.this.output_name
2349
2350
2351class TeradataConversion(Expression):
2352    """A postfix type conversion with Teradata-specific conversion or formatting semantics."""
2353
2354    arg_types = {"this": True, "to": True, "format": False}
2355
2356    @property
2357    def name(self) -> str:
2358        return self.this.name
2359
2360    @property
2361    def output_name(self) -> str:
2362        return self.this.output_name
2363
2364
2365class TeradataTitle(Expression):
2366    """A Teradata TITLE display heading, which does not rename the expression."""
2367
2368    arg_types = {"this": True, "title": True}
2369
2370    @property
2371    def name(self) -> str:
2372        return self.this.name
2373
2374    @property
2375    def output_name(self) -> str:
2376        return self.this.output_name
2377
2378
2379class TeradataNamed(Alias):
2380    """A Teradata NAMED alias on a subexpression; projections use ordinary Alias."""
2381
2382    arg_types = {"this": True, "alias": True}
2383
2384
2385class Between(Expression, Predicate):
2386    arg_types = {"this": True, "low": True, "high": True, "symmetric": False}
2387
2388
2389class Distinct(Expression):
2390    arg_types = {"expressions": False, "on": False}
2391
2392
2393class In(Expression, Predicate):
2394    arg_types = {
2395        "this": True,
2396        "expressions": False,
2397        "query": False,
2398        "unnest": False,
2399        "field": False,
2400        "is_global": False,
2401    }
2402
2403
2404class And(Expression, Connector, Func):
2405    pass
2406
2407
2408class Or(Expression, Connector, Func):
2409    pass
2410
2411
2412class Xor(Expression, Connector, Func):
2413    arg_types = {"this": True, "expression": True, "round_input": False}
2414
2415
2416class Pow(Expression, Binary, Func):
2417    _sql_names = ["POWER", "POW"]
2418
2419
2420class RegexpLike(Expression, Binary, Predicate, Func):
2421    arg_types = {"this": True, "expression": True, "flag": False, "full_match": False}
2422
2423
2424def not_(
2425    expression: ExpOrStr,
2426    dialect: DialectType = None,
2427    copy: bool = True,
2428    **opts: Unpack[ParserNoDialectArgs],
2429) -> Not:
2430    """
2431    Wrap a condition with a NOT operator.
2432
2433    Example:
2434        >>> not_("this_suit='black'").sql()
2435        "NOT this_suit = 'black'"
2436
2437    Args:
2438        expression: the SQL code string to parse.
2439            If an Expr instance is passed, this is used as-is.
2440        dialect: the dialect used to parse the input expression.
2441        copy: whether to copy the expression or not.
2442        **opts: other options to use to parse the input expressions.
2443
2444    Returns:
2445        The new condition.
2446    """
2447    this = condition(
2448        expression,
2449        dialect=dialect,
2450        copy=copy,
2451        **opts,
2452    )
2453    return Not(this=_wrap(this, Connector))
2454
2455
2456def _lazy_unnest(**kwargs: object) -> Expr:
2457    from sqlglot.expressions.array import Unnest
2458
2459    return Unnest(**kwargs)
2460
2461
2462def convert(value: t.Any, copy: bool = False) -> Expr:
2463    """Convert a python value into an expression object.
2464
2465    Raises an error if a conversion is not possible.
2466
2467    Args:
2468        value: A python object.
2469        copy: Whether to copy `value` (only applies to Exprs and collections).
2470
2471    Returns:
2472        The equivalent expression object.
2473    """
2474    if isinstance(value, Expr):
2475        return maybe_copy(value, copy)
2476    if isinstance(value, str):
2477        return Literal.string(value)
2478    if isinstance(value, bool):
2479        return Boolean(this=value)
2480    if value is None or (isinstance(value, float) and math.isnan(value)):
2481        return Null()
2482    if isinstance(value, numbers.Number):
2483        return Literal.number(value)
2484    if isinstance(value, bytes):
2485        from sqlglot.expressions.query import HexString as _HexString
2486
2487        return _HexString(this=value.hex())
2488    if isinstance(value, datetime.datetime):
2489        datetime_literal = Literal.string(value.isoformat(sep=" "))
2490
2491        tz = None
2492        if value.tzinfo:
2493            # this works for zoneinfo.ZoneInfo, pytz.timezone and datetime.datetime.utc to return IANA timezone names like "America/Los_Angeles"
2494            # instead of abbreviations like "PDT". This is for consistency with other timezone handling functions in SQLGlot
2495            tz = Literal.string(str(value.tzinfo))
2496
2497        from sqlglot.expressions.temporal import TimeStrToTime as _TimeStrToTime
2498
2499        return _TimeStrToTime(this=datetime_literal, zone=tz)
2500    if isinstance(value, datetime.date):
2501        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
2502        from sqlglot.expressions.temporal import DateStrToDate as _DateStrToDate
2503
2504        return _DateStrToDate(this=date_literal)
2505    if isinstance(value, datetime.time):
2506        time_literal = Literal.string(value.isoformat())
2507        from sqlglot.expressions.temporal import TsOrDsToTime as _TsOrDsToTime
2508
2509        return _TsOrDsToTime(this=time_literal)
2510    if isinstance(value, tuple):
2511        if hasattr(value, "_fields"):
2512            from sqlglot.expressions.array import Struct as _Struct
2513
2514            return _Struct(
2515                expressions=[
2516                    PropertyEQ(
2517                        this=to_identifier(k), expression=convert(getattr(value, k), copy=copy)
2518                    )
2519                    for k in value._fields
2520                ]
2521            )
2522        from sqlglot.expressions.query import Tuple as _Tuple
2523
2524        return _Tuple(expressions=[convert(v, copy=copy) for v in value])
2525    if isinstance(value, list):
2526        from sqlglot.expressions.array import Array as _Array
2527
2528        return _Array(expressions=[convert(v, copy=copy) for v in value])
2529    if isinstance(value, dict):
2530        from sqlglot.expressions.array import Array as _Array
2531        from sqlglot.expressions.array import Map as _Map
2532
2533        return _Map(
2534            keys=_Array(expressions=[convert(k, copy=copy) for k in value]),
2535            values=_Array(expressions=[convert(v, copy=copy) for v in value.values()]),
2536        )
2537    if hasattr(value, "__dict__"):
2538        from sqlglot.expressions.array import Struct as _Struct
2539
2540        return _Struct(
2541            expressions=[
2542                PropertyEQ(this=to_identifier(k), expression=convert(v, copy=copy))
2543                for k, v in value.__dict__.items()
2544            ]
2545        )
2546    raise ValueError(f"Cannot convert {value}")
2547
2548
2549QUERY_MODIFIERS = {
2550    "laterals": False,
2551    "joins": False,
2552    "connect": False,
2553    "pivots": False,
2554    "prewhere": False,
2555    "where": False,
2556    "group": False,
2557    "having": False,
2558    "qualify": False,
2559    "windows": False,
2560    "distribute": False,
2561    "sort": False,
2562    "cluster": False,
2563    "order": False,
2564    "limit": False,
2565    "offset": False,
2566    "locks": False,
2567    "sample": False,
2568    "settings": False,
2569    "format": False,
2570    "options": False,
2571    "for_": False,
2572}
2573
2574
2575TIMESTAMP_PARTS = {
2576    "year": False,
2577    "month": False,
2578    "day": False,
2579    "hour": False,
2580    "min": False,
2581    "sec": False,
2582    "nano": False,
2583}
2584
2585
2586@t.overload
2587def maybe_parse(
2588    sql_or_expression: int | str,
2589    *,
2590    into: Type[E],
2591    dialect: DialectType = None,
2592    prefix: str | None = None,
2593    copy: bool = False,
2594    **opts: Unpack[ParserNoDialectArgs],
2595) -> E: ...
2596
2597
2598@t.overload
2599def maybe_parse(
2600    sql_or_expression: int | str | E,
2601    *,
2602    into: IntoType | None = None,
2603    dialect: DialectType = None,
2604    prefix: str | None = None,
2605    copy: bool = False,
2606    **opts: Unpack[ParserNoDialectArgs],
2607) -> E: ...
2608
2609
2610def maybe_parse(
2611    sql_or_expression: ExpOrStr,
2612    *,
2613    into: IntoType | None = None,
2614    dialect: DialectType = None,
2615    prefix: str | None = None,
2616    copy: bool = False,
2617    **opts: Unpack[ParserNoDialectArgs],
2618) -> Expr:
2619    """Gracefully handle a possible string or expression.
2620
2621    Example:
2622        >>> maybe_parse("1")
2623        Literal(this=1, is_string=False)
2624        >>> maybe_parse(to_identifier("x"))
2625        Identifier(this=x, quoted=False)
2626
2627    Args:
2628        sql_or_expression: the SQL code string or an expression
2629        into: the SQLGlot Expr to parse into
2630        dialect: the dialect used to parse the input expressions (in the case that an
2631            input expression is a SQL string).
2632        prefix: a string to prefix the sql with before it gets parsed
2633            (automatically includes a space)
2634        copy: whether to copy the expression.
2635        **opts: other options to use to parse the input expressions (again, in the case
2636            that an input expression is a SQL string).
2637
2638    Returns:
2639        Expr: the parsed or given expression.
2640    """
2641    if isinstance(sql_or_expression, Expr):
2642        if copy:
2643            return sql_or_expression.copy()
2644        return sql_or_expression
2645
2646    if sql_or_expression is None:
2647        raise ParseError("SQL cannot be None")
2648
2649    import sqlglot
2650
2651    sql = str(sql_or_expression)
2652    if prefix:
2653        sql = f"{prefix} {sql}"
2654
2655    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
2656
2657
2658@t.overload
2659def maybe_copy(instance: None, copy: bool = True) -> None: ...
2660
2661
2662@t.overload
2663def maybe_copy(instance: E, copy: bool = True) -> E: ...
2664
2665
2666def maybe_copy(instance, copy=True):
2667    return instance.copy() if copy and instance else instance
2668
2669
2670def _to_s(node: t.Any, verbose: bool = False, level: int = 0, repr_str: bool = False) -> str:
2671    """Generate a textual representation of an Expr tree"""
2672    indent = "\n" + ("  " * (level + 1))
2673    delim = f",{indent}"
2674
2675    if isinstance(node, Expr):
2676        args = {k: v for k, v in node.args.items() if (v is not None and v != []) or verbose}
2677
2678        if (node.type or verbose) and not node.is_data_type:
2679            args["_type"] = node.type
2680        if node.comments or verbose:
2681            args["_comments"] = node.comments
2682
2683        if verbose:
2684            args["_id"] = id(node)
2685
2686        # Inline leaves for a more compact representation
2687        if node.is_leaf():
2688            indent = ""
2689            delim = ", "
2690
2691        repr_str = node.is_string or (isinstance(node, Identifier) and node.quoted)
2692        items = delim.join(
2693            [f"{k}={_to_s(v, verbose, level + 1, repr_str=repr_str)}" for k, v in args.items()]
2694        )
2695        return f"{node.__class__.__name__}({indent}{items})"
2696
2697    if isinstance(node, list):
2698        items = delim.join(_to_s(i, verbose, level + 1) for i in node)
2699        items = f"{indent}{items}" if items else ""
2700        return f"[{items}]"
2701
2702    # We use the representation of the string to avoid stripping out important whitespace
2703    if repr_str and isinstance(node, str):
2704        node = repr(node)
2705
2706    # Indent multiline strings to match the current level
2707    return indent.join(textwrap.dedent(str(node).strip("\n")).splitlines())
2708
2709
2710def _is_wrong_expression(expression, into):
2711    return isinstance(expression, Expr) and not isinstance(expression, into)
2712
2713
2714def _apply_builder(
2715    expression: ExpOrStr,
2716    instance: E,
2717    arg: str,
2718    copy: bool = True,
2719    prefix: str | None = None,
2720    into: Type[Expr] | None = None,
2721    dialect: DialectType = None,
2722    into_arg="this",
2723    **opts: Unpack[ParserNoDialectArgs],
2724) -> E:
2725    if _is_wrong_expression(expression, into) and into is not None:
2726        expression = into(**{into_arg: expression})
2727    instance = maybe_copy(instance, copy)
2728    expression = maybe_parse(
2729        sql_or_expression=expression,
2730        prefix=prefix,
2731        into=into,
2732        dialect=dialect,
2733        **opts,
2734    )
2735    instance.set(arg, expression)
2736    return instance
2737
2738
2739def _apply_child_list_builder(
2740    *expressions: ExpOrStr | None,
2741    instance: E,
2742    arg: str,
2743    append: bool = True,
2744    copy: bool = True,
2745    prefix: str | None = None,
2746    into: Type[Expr] | None = None,
2747    dialect: DialectType = None,
2748    properties: MutableMapping[str, object] | None = None,
2749    **opts: Unpack[ParserNoDialectArgs],
2750) -> E:
2751    instance = maybe_copy(instance, copy)
2752    parsed = []
2753    properties = {} if properties is None else properties
2754
2755    for expression in expressions:
2756        if expression is not None:
2757            if _is_wrong_expression(expression, into) and into is not None:
2758                expression = into(expressions=[expression])
2759
2760            expression = maybe_parse(
2761                expression,
2762                into=into,
2763                dialect=dialect,
2764                prefix=prefix,
2765                **opts,
2766            )
2767            for k, v in expression.args.items():
2768                if k == "expressions":
2769                    parsed.extend(v)
2770                else:
2771                    properties[k] = v
2772
2773    existing = instance.args.get(arg)
2774    if append and existing:
2775        parsed = existing.expressions + parsed
2776    if into is None:
2777        raise ValueError("`into` is required to use `_apply_child_list_builder`")
2778    child = into(expressions=parsed)
2779    for k, v in properties.items():
2780        child.set(k, v)
2781    instance.set(arg, child)
2782
2783    return instance
2784
2785
2786def _apply_list_builder(
2787    *expressions: ExpOrStr | None,
2788    instance: E,
2789    arg: str,
2790    append: bool = True,
2791    copy: bool = True,
2792    prefix: str | None = None,
2793    into: Type[Expr] | None = None,
2794    dialect: DialectType = None,
2795    **opts: Unpack[ParserNoDialectArgs],
2796) -> E:
2797    inst = maybe_copy(instance, copy)
2798
2799    parsed = [
2800        maybe_parse(
2801            sql_or_expression=expression,
2802            into=into,
2803            prefix=prefix,
2804            dialect=dialect,
2805            **opts,
2806        )
2807        for expression in expressions
2808        if expression is not None
2809    ]
2810
2811    existing_expressions = inst.args.get(arg)
2812    if append and existing_expressions:
2813        parsed = existing_expressions + parsed
2814
2815    inst.set(arg, parsed)
2816    return inst
2817
2818
2819def _apply_conjunction_builder(
2820    *expressions: ExpOrStr | None,
2821    instance: E,
2822    arg: str,
2823    into: Type[Expr] | None = None,
2824    append: bool = True,
2825    copy: bool = True,
2826    dialect: DialectType = None,
2827    **opts: Unpack[ParserNoDialectArgs],
2828) -> E:
2829    filtered = [exp for exp in expressions if exp is not None and exp != ""]
2830    if not filtered:
2831        return instance
2832
2833    inst = maybe_copy(instance, copy)
2834
2835    existing = inst.args.get(arg)
2836    if append and existing is not None:
2837        filtered = [existing.this if into else existing] + filtered
2838
2839    node = and_(*filtered, dialect=dialect, copy=copy, **opts)
2840
2841    inst.set(arg, into(this=node) if into else node)
2842    return inst
2843
2844
2845def _combine(
2846    expressions: Sequence[ExpOrStr | None],
2847    operator: Type[Expr],
2848    dialect: DialectType = None,
2849    copy: bool = True,
2850    wrap: bool = True,
2851    **opts: Unpack[ParserNoDialectArgs],
2852) -> Expr:
2853    conditions = [
2854        condition(expression, dialect=dialect, copy=copy, **opts)
2855        for expression in expressions
2856        if expression is not None
2857    ]
2858
2859    this, *rest = conditions
2860    if rest and wrap:
2861        this = _wrap(this, Connector)
2862    for expression in rest:
2863        this = operator(this=this, expression=_wrap(expression, Connector) if wrap else expression)
2864
2865    return this
2866
2867
2868@t.overload
2869def _wrap(expression: None, kind: Type[Expr]) -> None: ...
2870
2871
2872@t.overload
2873def _wrap(expression: E, kind: Type[Expr]) -> E | Paren: ...
2874
2875
2876def _wrap(expression: E | None, kind: Type[Expr]) -> E | None | Paren:
2877    return Paren(this=expression) if isinstance(expression, kind) else expression
2878
2879
2880def _apply_set_operation(
2881    *expressions: ExpOrStr,
2882    set_operation: Type,
2883    distinct: bool = True,
2884    dialect: DialectType = None,
2885    copy: bool = True,
2886    **opts: Unpack[ParserNoDialectArgs],
2887) -> t.Any:
2888    return reduce(
2889        lambda x, y: set_operation(this=x, expression=y, distinct=distinct, **opts),
2890        (maybe_parse(e, dialect=dialect, copy=copy, **opts) for e in expressions),
2891    )
2892
2893
2894SAFE_IDENTIFIER_RE: t.Pattern[str] = re.compile(r"^[_a-zA-Z][\w]*$")
2895
2896
2897@t.overload
2898def to_identifier(name: None, quoted: bool | None = None, copy: bool = True) -> None: ...
2899
2900
2901@t.overload
2902def to_identifier(
2903    name: int | str | Identifier, quoted: bool | None = None, copy: bool = True
2904) -> Identifier: ...
2905
2906
2907def to_identifier(name, quoted=None, copy=True):
2908    """Builds an identifier.
2909
2910    Args:
2911        name: The name to turn into an identifier.
2912        quoted: Whether to force quote the identifier.
2913        copy: Whether to copy name if it's an Identifier.
2914
2915    Returns:
2916        The identifier ast node.
2917    """
2918
2919    if name is None:
2920        return None
2921
2922    if isinstance(name, Identifier):
2923        identifier = maybe_copy(name, copy)
2924    elif isinstance(name, str):
2925        identifier = Identifier(
2926            this=name,
2927            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
2928        )
2929    else:
2930        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
2931    return identifier
2932
2933
2934def condition(
2935    expression: ExpOrStr,
2936    dialect: DialectType = None,
2937    copy: bool = True,
2938    **opts: Unpack[ParserNoDialectArgs],
2939) -> Expr:
2940    """
2941    Initialize a logical condition expression.
2942
2943    Example:
2944        >>> condition("x=1").sql()
2945        'x = 1'
2946
2947        This is helpful for composing larger logical syntax trees:
2948        >>> where = condition("x=1")
2949        >>> where = where.and_("y=1")
2950        >>> where.sql()
2951        'x = 1 AND y = 1'
2952
2953    Args:
2954        *expression: the SQL code string to parse.
2955            If an Expr instance is passed, this is used as-is.
2956        dialect: the dialect used to parse the input expression (in the case that the
2957            input expression is a SQL string).
2958        copy: Whether to copy `expression` (only applies to expressions).
2959        **opts: other options to use to parse the input expressions (again, in the case
2960            that the input expression is a SQL string).
2961
2962    Returns:
2963        The new Condition instance
2964    """
2965    return maybe_parse(
2966        expression,
2967        into=Condition,
2968        dialect=dialect,
2969        copy=copy,
2970        **opts,
2971    )
2972
2973
2974def and_(
2975    *expressions: ExpOrStr | None,
2976    dialect: DialectType = None,
2977    copy: bool = True,
2978    wrap: bool = True,
2979    **opts: Unpack[ParserNoDialectArgs],
2980) -> Condition:
2981    """
2982    Combine multiple conditions with an AND logical operator.
2983
2984    Example:
2985        >>> and_("x=1", and_("y=1", "z=1")).sql()
2986        'x = 1 AND (y = 1 AND z = 1)'
2987
2988    Args:
2989        *expressions: the SQL code strings to parse.
2990            If an Expr instance is passed, this is used as-is.
2991        dialect: the dialect used to parse the input expression.
2992        copy: whether to copy `expressions` (only applies to Exprs).
2993        wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
2994            precedence issues, but can be turned off when the produced AST is too deep and
2995            causes recursion-related issues.
2996        **opts: other options to use to parse the input expressions.
2997
2998    Returns:
2999        The new condition
3000    """
3001    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, wrap=wrap, **opts))
3002
3003
3004def or_(
3005    *expressions: ExpOrStr | None,
3006    dialect: DialectType = None,
3007    copy: bool = True,
3008    wrap: bool = True,
3009    **opts: Unpack[ParserNoDialectArgs],
3010) -> Condition:
3011    """
3012    Combine multiple conditions with an OR logical operator.
3013
3014    Example:
3015        >>> or_("x=1", or_("y=1", "z=1")).sql()
3016        'x = 1 OR (y = 1 OR z = 1)'
3017
3018    Args:
3019        *expressions: the SQL code strings to parse.
3020            If an Expr instance is passed, this is used as-is.
3021        dialect: the dialect used to parse the input expression.
3022        copy: whether to copy `expressions` (only applies to Exprs).
3023        wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
3024            precedence issues, but can be turned off when the produced AST is too deep and
3025            causes recursion-related issues.
3026        **opts: other options to use to parse the input expressions.
3027
3028    Returns:
3029        The new condition
3030    """
3031    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, wrap=wrap, **opts))
3032
3033
3034def xor(
3035    *expressions: ExpOrStr | None,
3036    dialect: DialectType = None,
3037    copy: bool = True,
3038    wrap: bool = True,
3039    **opts: Unpack[ParserNoDialectArgs],
3040) -> Condition:
3041    """
3042    Combine multiple conditions with an XOR logical operator.
3043
3044    Example:
3045        >>> xor("x=1", xor("y=1", "z=1")).sql()
3046        'x = 1 XOR (y = 1 XOR z = 1)'
3047
3048    Args:
3049        *expressions: the SQL code strings to parse.
3050            If an Expr instance is passed, this is used as-is.
3051        dialect: the dialect used to parse the input expression.
3052        copy: whether to copy `expressions` (only applies to Exprs).
3053        wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
3054            precedence issues, but can be turned off when the produced AST is too deep and
3055            causes recursion-related issues.
3056        **opts: other options to use to parse the input expressions.
3057
3058    Returns:
3059        The new condition
3060    """
3061    return t.cast(Condition, _combine(expressions, Xor, dialect, copy=copy, wrap=wrap, **opts))
3062
3063
3064def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
3065    """
3066    Wrap an expression in parentheses.
3067
3068    Example:
3069        >>> paren("5 + 3").sql()
3070        '(5 + 3)'
3071
3072    Args:
3073        expression: the SQL code string to parse.
3074            If an Expr instance is passed, this is used as-is.
3075        copy: whether to copy the expression or not.
3076
3077    Returns:
3078        The wrapped expression.
3079    """
3080    return Paren(this=maybe_parse(expression, copy=copy))
3081
3082
3083def alias_(
3084    expression: ExpOrStr,
3085    alias: str | Identifier | None,
3086    table: bool | Sequence[str | Identifier] = False,
3087    quoted: bool | None = None,
3088    dialect: DialectType = None,
3089    copy: bool = True,
3090    **opts: Unpack[ParserNoDialectArgs],
3091) -> Expr:
3092    """Create an Alias expression.
3093
3094    Example:
3095        >>> alias_('foo', 'bar').sql()
3096        'foo AS bar'
3097
3098        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
3099        '(SELECT 1, 2) AS bar(a, b)'
3100
3101    Args:
3102        expression: the SQL code strings to parse.
3103            If an Expr instance is passed, this is used as-is.
3104        alias: the alias name to use. If the name has
3105            special characters it is quoted.
3106        table: Whether to create a table alias, can also be a list of columns.
3107        quoted: whether to quote the alias
3108        dialect: the dialect used to parse the input expression.
3109        copy: Whether to copy the expression.
3110        **opts: other options to use to parse the input expressions.
3111
3112    Returns:
3113        Alias: the aliased expression
3114    """
3115    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
3116    alias = to_identifier(alias, quoted=quoted)
3117
3118    if table:
3119        from sqlglot.expressions.query import TableAlias as _TableAlias
3120
3121        table_alias = _TableAlias(this=alias)
3122        exp.set("alias", table_alias)
3123
3124        if not isinstance(table, bool):
3125            for column in table:
3126                table_alias.append("columns", to_identifier(column, quoted=quoted))
3127
3128        return exp
3129
3130    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
3131    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
3132    # for the complete Window expression.
3133    #
3134    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
3135
3136    if "alias" in exp.arg_types and type(exp).__name__ != "Window":
3137        exp.set("alias", alias)
3138        return exp
3139    return Alias(this=exp, alias=alias)
3140
3141
3142@t.overload
3143def column(
3144    col: str | Expr,
3145    table: str | Identifier | None = None,
3146    db: str | Identifier | None = None,
3147    catalog: str | Identifier | None = None,
3148    *,
3149    fields: Collection[str | Identifier],
3150    quoted: bool | None = None,
3151    copy: bool = True,
3152) -> Dot:
3153    pass
3154
3155
3156@t.overload
3157def column(
3158    col: str | Expr,
3159    table: str | Identifier | None = None,
3160    db: str | Identifier | None = None,
3161    catalog: str | Identifier | None = None,
3162    *,
3163    fields: t.Literal[None] = None,
3164    quoted: bool | None = None,
3165    copy: bool = True,
3166) -> Column:
3167    pass
3168
3169
3170def column(
3171    col,
3172    table=None,
3173    db=None,
3174    catalog=None,
3175    *,
3176    fields=None,
3177    quoted=None,
3178    copy: bool = True,
3179):
3180    """
3181    Build a Column.
3182
3183    Args:
3184        col: Column name or expression.
3185        table: Table name.
3186        db: Database name.
3187        catalog: Catalog name.
3188        fields: Additional fields using dots.
3189        quoted: Whether to force quotes on the column's identifiers.
3190        copy: Whether to copy expressions if passed in.
3191
3192    Returns:
3193        The new Column instance.
3194    """
3195    col = maybe_copy(col, copy) if isinstance(col, Expr) else to_identifier(col, quoted=quoted)
3196
3197    this: Column | Dot = Column(
3198        this=col,
3199        table=to_identifier(table, quoted=quoted, copy=copy),
3200        db=to_identifier(db, quoted=quoted, copy=copy),
3201        catalog=to_identifier(catalog, quoted=quoted, copy=copy),
3202    )
3203
3204    if fields:
3205        this = Dot.build(
3206            (this, *(to_identifier(field, quoted=quoted, copy=copy) for field in fields))
3207        )
3208    return this
logger = <Logger sqlglot (WARNING)>
SQLGLOT_META: str = 'sqlglot.meta'
SQLGLOT_ANONYMOUS = 'sqlglot.anonymous'
TABLE_PARTS = ('this', 'db', 'catalog')
COLUMN_PARTS = ('this', 'table', 'db', 'catalog')
POSITION_META_KEYS: tuple[str, ...] = ('line', 'col', 'start', 'end')
UNITTEST: bool = True
@trait
class Expr:
 53@trait
 54class Expr:
 55    """
 56    The base class for all expressions in a syntax tree. Each Expr encapsulates any necessary
 57    context, such as its child expressions, their names (arg keys), and whether a given child expression
 58    is optional or not.
 59
 60    Attributes:
 61        key: a unique key for each class in the Expr hierarchy. This is useful for hashing
 62            and representing expressions as strings.
 63        arg_types: determines the arguments (child nodes) supported by an expression. It maps
 64            arg keys to booleans that indicate whether the corresponding args are optional.
 65        parent: a reference to the parent expression (or None, in case of root expressions).
 66        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 67            uses to refer to it.
 68        index: the index of an expression if it is inside of a list argument in its parent.
 69        comments: a list of comments that are associated with a given expression. This is used in
 70            order to preserve comments when transpiling SQL code.
 71        type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 72            optimizer, in order to enable some transformations that require type information.
 73        meta: a dictionary that can be used to store useful metadata for a given expression.
 74
 75    Example:
 76        >>> class Foo(Expr):
 77        ...     arg_types = {"this": True, "expression": False}
 78
 79        The above definition informs us that Foo is an Expr that requires an argument called
 80        "this" and may also optionally receive an argument called "expression".
 81
 82    Args:
 83        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 84    """
 85
 86    key: t.ClassVar[str] = "expression"
 87    arg_types: t.ClassVar[dict[str, bool]] = {"this": True}
 88    required_args: t.ClassVar[set[str]] = {"this"}
 89    is_var_len_args: t.ClassVar[bool] = False
 90    var_len_arg_key: t.ClassVar[str] = "expressions"
 91    _hash_raw_args: t.ClassVar[bool] = False
 92    is_subquery: t.ClassVar[bool] = False
 93    is_cast: t.ClassVar[bool] = False
 94    is_data_type: t.ClassVar[bool] = False
 95
 96    args: dict[str, t.Any]
 97    parent: Expr | None
 98    arg_key: str | None
 99    index: int | None
100    comments: list[str] | None
101    _type: DataType | None
102    _meta: dict[str, t.Any] | None
103    _hash: int | None
104
105    @classmethod
106    def __init_subclass__(cls, **kwargs: t.Any) -> None:
107        super().__init_subclass__(**kwargs)
108        # When an Expr class is created, its key is automatically set
109        # to be the lowercase version of the class' name.
110        cls.key = cls.__name__.lower()
111        cls.required_args = {k for k, v in cls.arg_types.items() if v}
112        # This is so that docstrings are not inherited in pdoc
113        setattr(cls, "__doc__", getattr(cls, "__doc__", None) or "")
114
115    is_primitive: t.ClassVar[bool] = False
116
117    def __init__(self, **args: object) -> None:
118        self.args: dict[str, t.Any] = args
119        self.parent: Expr | None = None
120        self.arg_key: str | None = None
121        self.index: int | None = None
122        self.comments: list[str] | None = None
123        self._type: DataType | None = None
124        self._meta: dict[str, t.Any] | None = None
125        self._hash: int | None = None
126
127        if not self.is_primitive:
128            for arg_key, value in self.args.items():
129                self._set_parent(arg_key, value)
130
131    @property
132    def this(self) -> t.Any:
133        """
134        Retrieves the argument with key "this".
135        """
136        raise NotImplementedError
137
138    @property
139    def expression(self) -> t.Any:
140        """
141        Retrieves the argument with key "expression".
142        """
143        raise NotImplementedError
144
145    @property
146    def expressions(self) -> list[t.Any]:
147        """
148        Retrieves the argument with key "expressions".
149        """
150        raise NotImplementedError
151
152    def text(self, key: str) -> str:
153        """
154        Returns a textual representation of the argument corresponding to "key". This can only be used
155        for args that are strings or leaf Expr instances, such as identifiers and literals.
156        """
157        raise NotImplementedError
158
159    @property
160    def is_string(self) -> bool:
161        """
162        Checks whether a Literal expression is a string.
163        """
164        raise NotImplementedError
165
166    @property
167    def is_number(self) -> bool:
168        """
169        Checks whether a Literal expression is a number.
170        """
171        raise NotImplementedError
172
173    def to_py(self) -> t.Any:
174        """
175        Returns a Python object equivalent of the SQL node.
176        """
177        raise NotImplementedError
178
179    @property
180    def is_int(self) -> bool:
181        """
182        Checks whether an expression is an integer.
183        """
184        raise NotImplementedError
185
186    @property
187    def is_star(self) -> bool:
188        """Checks whether an expression is a star."""
189        raise NotImplementedError
190
191    @property
192    def alias(self) -> str:
193        """
194        Returns the alias of the expression, or an empty string if it's not aliased.
195        """
196        raise NotImplementedError
197
198    @property
199    def alias_column_names(self) -> list[str]:
200        raise NotImplementedError
201
202    @property
203    def name(self) -> str:
204        raise NotImplementedError
205
206    @property
207    def alias_or_name(self) -> str:
208        raise NotImplementedError
209
210    @property
211    def output_name(self) -> str:
212        """
213        Name of the output column if this expression is a selection.
214
215        If the Expr has no output name, an empty string is returned.
216
217        Example:
218            >>> from sqlglot import parse_one
219            >>> parse_one("SELECT a").expressions[0].output_name
220            'a'
221            >>> parse_one("SELECT b AS c").expressions[0].output_name
222            'c'
223            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
224            ''
225        """
226        raise NotImplementedError
227
228    @property
229    def type(self) -> DataType | None:
230        raise NotImplementedError
231
232    @type.setter
233    def type(self, dtype: DataType | DType | str | None) -> None:
234        raise NotImplementedError
235
236    def is_type(self, *dtypes: DATA_TYPE) -> bool:
237        raise NotImplementedError
238
239    def is_leaf(self) -> bool:
240        raise NotImplementedError
241
242    @property
243    def meta(self) -> dict[str, t.Any]:
244        raise NotImplementedError
245
246    def meta_get(self, key: str, default: t.Any = None) -> t.Any:
247        raise NotImplementedError
248
249    def __deepcopy__(self, memo: t.Any) -> Expr:
250        raise NotImplementedError
251
252    def copy(self: E) -> E:
253        """
254        Returns a deep copy of the expression.
255        """
256        raise NotImplementedError
257
258    def add_comments(self, comments: list[str] | None = None, prepend: bool = False) -> None:
259        raise NotImplementedError
260
261    def pop_comments(self) -> list[str]:
262        raise NotImplementedError
263
264    def append(self, arg_key: str, value: t.Any) -> None:
265        """
266        Appends value to arg_key if it's a list or sets it as a new list.
267
268        Args:
269            arg_key (str): name of the list expression arg
270            value (Any): value to append to the list
271        """
272        raise NotImplementedError
273
274    def set(
275        self,
276        arg_key: str,
277        value: object,
278        index: int | None = None,
279        overwrite: bool = True,
280    ) -> None:
281        """
282        Sets arg_key to value.
283
284        Args:
285            arg_key: name of the expression arg.
286            value: value to set the arg to.
287            index: if the arg is a list, this specifies what position to add the value in it.
288            overwrite: assuming an index is given, this determines whether to overwrite the
289                list entry instead of only inserting a new value (i.e., like list.insert).
290        """
291        raise NotImplementedError
292
293    def _set_parent(self, arg_key: str, value: object, index: int | None = None) -> None:
294        raise NotImplementedError
295
296    @property
297    def depth(self) -> int:
298        """
299        Returns the depth of this tree.
300        """
301        raise NotImplementedError
302
303    def iter_expressions(self: E, reverse: bool = False) -> Iterator[E]:
304        """Yields the key and expression for all arguments, exploding list args."""
305        raise NotImplementedError
306
307    def find(self, *expression_types: Type[E], bfs: bool = True) -> E | None:
308        """
309        Returns the first node in this tree which matches at least one of
310        the specified types.
311
312        Args:
313            expression_types: the expression type(s) to match.
314            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
315
316        Returns:
317            The node which matches the criteria or None if no such node was found.
318        """
319        raise NotImplementedError
320
321    def find_all(self, *expression_types: Type[E], bfs: bool = True) -> Iterator[E]:
322        """
323        Returns a generator object which visits all nodes in this tree and only
324        yields those that match at least one of the specified expression types.
325
326        Args:
327            expression_types: the expression type(s) to match.
328            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
329
330        Returns:
331            The generator object.
332        """
333        raise NotImplementedError
334
335    def find_ancestor(self, *expression_types: Type[E]) -> E | None:
336        """
337        Returns a nearest parent matching expression_types.
338
339        Args:
340            expression_types: the expression type(s) to match.
341
342        Returns:
343            The parent node.
344        """
345        raise NotImplementedError
346
347    @property
348    def parent_select(self) -> Select | None:
349        """
350        Returns the parent select statement.
351        """
352        raise NotImplementedError
353
354    @property
355    def same_parent(self) -> bool:
356        """Returns if the parent is the same class as itself."""
357        raise NotImplementedError
358
359    def root(self) -> Expr:
360        """
361        Returns the root expression of this tree.
362        """
363        raise NotImplementedError
364
365    def walk(
366        self, bfs: bool = True, prune: t.Callable[[Expr], bool] | None = None
367    ) -> Iterator[Expr]:
368        """
369        Returns a generator object which visits all nodes in this tree.
370
371        Args:
372            bfs: if set to True the BFS traversal order will be applied,
373                otherwise the DFS traversal will be used instead.
374            prune: callable that returns True if the generator should stop traversing
375                this branch of the tree.
376
377        Returns:
378            the generator object.
379        """
380        raise NotImplementedError
381
382    def dfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
383        """
384        Returns a generator object which visits all nodes in this tree in
385        the DFS (Depth-first) order.
386
387        Returns:
388            The generator object.
389        """
390        raise NotImplementedError
391
392    def bfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
393        """
394        Returns a generator object which visits all nodes in this tree in
395        the BFS (Breadth-first) order.
396
397        Returns:
398            The generator object.
399        """
400        raise NotImplementedError
401
402    def unnest(self) -> Expr:
403        """
404        Returns the first non parenthesis child or self.
405        """
406        raise NotImplementedError
407
408    def unalias(self) -> Expr:
409        """
410        Returns the inner expression if this is an Alias.
411        """
412        raise NotImplementedError
413
414    def unnest_operands(self) -> tuple[Expr, ...]:
415        """
416        Returns unnested operands as a tuple.
417        """
418        raise NotImplementedError
419
420    def flatten(self, unnest: bool = True) -> Iterator[Expr]:
421        """
422        Returns a generator which yields child nodes whose parents are the same class.
423
424        A AND B AND C -> [A, B, C]
425        """
426        raise NotImplementedError
427
428    def to_s(self) -> str:
429        """
430        Same as __repr__, but includes additional information which can be useful
431        for debugging, like empty or missing args and the AST nodes' object IDs.
432        """
433        raise NotImplementedError
434
435    def sql(
436        self, dialect: DialectType = None, copy: bool = True, **opts: Unpack[GeneratorNoDialectArgs]
437    ) -> str:
438        """
439        Returns SQL string representation of this tree.
440
441        Args:
442            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
443            opts: other `sqlglot.generator.Generator` options.
444
445        Returns:
446            The SQL string.
447        """
448        raise NotImplementedError
449
450    def transform(
451        self, fun: t.Callable[..., T], *args: object, copy: bool = True, **kwargs: object
452    ) -> T:
453        """
454        Visits all tree nodes (excluding already transformed ones)
455        and applies the given transformation function to each node.
456
457        Args:
458            fun: a function which takes a node as an argument and returns a
459                new transformed node or the same node without modifications. If the function
460                returns None, then the corresponding node will be removed from the syntax tree.
461            copy: if set to True a new tree instance is constructed, otherwise the tree is
462                modified in place.
463
464        Returns:
465            The transformed tree.
466        """
467        raise NotImplementedError
468
469    def replace(self, expression: T) -> T:
470        """
471        Swap out this expression with a new expression.
472
473        For example::
474
475            >>> import sqlglot
476            >>> tree = sqlglot.parse_one("SELECT x FROM tbl")
477            >>> tree.find(sqlglot.exp.Column).replace(sqlglot.exp.column("y"))
478            Column(
479              this=Identifier(this=y, quoted=False))
480            >>> tree.sql()
481            'SELECT y FROM tbl'
482
483        Args:
484            expression (T): new node
485
486        Returns:
487            T: The new expression or expressions.
488        """
489        raise NotImplementedError
490
491    def pop(self: E) -> E:
492        """
493        Remove this expression from its AST.
494
495        Returns:
496            The popped expression.
497        """
498        raise NotImplementedError
499
500    def assert_is(self, type_: Type[E]) -> E:
501        """
502        Assert that this `Expr` is an instance of `type_`.
503
504        If it is NOT an instance of `type_`, this raises an assertion error.
505        Otherwise, this returns this expression.
506
507        Examples:
508            This is useful for type security in chained expressions:
509
510            >>> import sqlglot
511            >>> sqlglot.parse_one("SELECT x from y").assert_is(sqlglot.exp.Select).select("z").sql()
512            'SELECT x, z FROM y'
513        """
514        raise NotImplementedError
515
516    def error_messages(self, args: Sequence[object] | None = None) -> list[str]:
517        """
518        Checks if this expression is valid (e.g. all mandatory args are set).
519
520        Args:
521            args: a sequence of values that were used to instantiate a Func expression. This is used
522                to check that the provided arguments don't exceed the function argument limit.
523
524        Returns:
525            A list of error messages for all possible errors that were found.
526        """
527        raise NotImplementedError
528
529    def dump(self) -> list[dict[str, t.Any]]:
530        """
531        Dump this Expr to a JSON-serializable dict.
532        """
533        from sqlglot.serde import dump
534
535        return dump(self)
536
537    @classmethod
538    def load(cls, obj: list[dict[str, Any]] | None) -> Expr:
539        """
540        Load a dict (as returned by `Expr.dump`) into an Expr instance.
541        """
542        from sqlglot.serde import load
543
544        result = load(obj)
545        assert isinstance(result, Expr)
546        return result
547
548    def and_(
549        self,
550        *expressions: ExpOrStr | None,
551        dialect: DialectType = None,
552        copy: bool = True,
553        wrap: bool = True,
554        **opts: Unpack[ParserNoDialectArgs],
555    ) -> Condition:
556        """
557        AND this condition with one or multiple expressions.
558
559        Example:
560            >>> condition("x=1").and_("y=1").sql()
561            'x = 1 AND y = 1'
562
563        Args:
564            *expressions: the SQL code strings to parse.
565                If an `Expr` instance is passed, it will be used as-is.
566            dialect: the dialect used to parse the input expression.
567            copy: whether to copy the involved expressions (only applies to Exprs).
568            wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
569                precedence issues, but can be turned off when the produced AST is too deep and
570                causes recursion-related issues.
571            opts: other options to use to parse the input expressions.
572
573        Returns:
574            The new And condition.
575        """
576        raise NotImplementedError
577
578    def or_(
579        self,
580        *expressions: ExpOrStr | None,
581        dialect: DialectType = None,
582        copy: bool = True,
583        wrap: bool = True,
584        **opts: Unpack[ParserNoDialectArgs],
585    ) -> Condition:
586        """
587        OR this condition with one or multiple expressions.
588
589        Example:
590            >>> condition("x=1").or_("y=1").sql()
591            'x = 1 OR y = 1'
592
593        Args:
594            *expressions: the SQL code strings to parse.
595                If an `Expr` instance is passed, it will be used as-is.
596            dialect: the dialect used to parse the input expression.
597            copy: whether to copy the involved expressions (only applies to Exprs).
598            wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
599                precedence issues, but can be turned off when the produced AST is too deep and
600                causes recursion-related issues.
601            opts: other options to use to parse the input expressions.
602
603        Returns:
604            The new Or condition.
605        """
606        raise NotImplementedError
607
608    def not_(self, copy: bool = True) -> Not:
609        """
610        Wrap this condition with NOT.
611
612        Example:
613            >>> condition("x=1").not_().sql()
614            'NOT x = 1'
615
616        Args:
617            copy: whether to copy this object.
618
619        Returns:
620            The new Not instance.
621        """
622        raise NotImplementedError
623
624    def update_positions(
625        self: E,
626        other: Token | Expr | None = None,
627        line: int | None = None,
628        col: int | None = None,
629        start: int | None = None,
630        end: int | None = None,
631    ) -> E:
632        """
633        Update this expression with positions from a token or other expression.
634
635        Args:
636            other: a token or expression to update this expression with.
637            line: the line number to use if other is None
638            col: column number
639            start: start char index
640            end:  end char index
641
642        Returns:
643            The updated expression.
644        """
645        raise NotImplementedError
646
647    def as_(
648        self,
649        alias: str | Identifier,
650        quoted: bool | None = None,
651        dialect: DialectType = None,
652        copy: bool = True,
653        table: bool | Sequence[str | Identifier] = False,
654        **opts: Unpack[ParserNoDialectArgs],
655    ) -> Expr:
656        raise NotImplementedError
657
658    def _binop(self, klass: Type[E], other: t.Any, reverse: bool = False) -> E:
659        raise NotImplementedError
660
661    def __getitem__(self, other: ExpOrStr | tuple[ExpOrStr, ...]) -> Bracket:
662        raise NotImplementedError
663
664    def __iter__(self) -> Iterator:
665        raise NotImplementedError
666
667    def isin(
668        self,
669        *expressions: t.Any,
670        query: ExpOrStr | None = None,
671        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
672        dialect: DialectType = None,
673        copy: bool = True,
674        **opts: Unpack[ParserNoDialectArgs],
675    ) -> In:
676        raise NotImplementedError
677
678    def between(
679        self, low: t.Any, high: t.Any, copy: bool = True, symmetric: bool | None = None
680    ) -> Between:
681        raise NotImplementedError
682
683    def is_(self, other: ExpOrStr) -> Is:
684        raise NotImplementedError
685
686    def like(self, other: ExpOrStr) -> Like:
687        raise NotImplementedError
688
689    def ilike(self, other: ExpOrStr) -> ILike:
690        raise NotImplementedError
691
692    def eq(self, other: t.Any) -> EQ:
693        raise NotImplementedError
694
695    def neq(self, other: t.Any) -> NEQ:
696        raise NotImplementedError
697
698    def rlike(self, other: ExpOrStr) -> RegexpLike:
699        raise NotImplementedError
700
701    def div(self, other: ExpOrStr, typed: bool = False, safe: bool = False) -> Div:
702        raise NotImplementedError
703
704    def asc(self, nulls_first: bool = True) -> Ordered:
705        raise NotImplementedError
706
707    def desc(self, nulls_first: bool = False) -> Ordered:
708        raise NotImplementedError
709
710    def __lt__(self, other: t.Any) -> LT:
711        raise NotImplementedError
712
713    def __le__(self, other: t.Any) -> LTE:
714        raise NotImplementedError
715
716    def __gt__(self, other: t.Any) -> GT:
717        raise NotImplementedError
718
719    def __ge__(self, other: t.Any) -> GTE:
720        raise NotImplementedError
721
722    def __add__(self, other: t.Any) -> Add:
723        raise NotImplementedError
724
725    def __radd__(self, other: t.Any) -> Add:
726        raise NotImplementedError
727
728    def __sub__(self, other: t.Any) -> Sub:
729        raise NotImplementedError
730
731    def __rsub__(self, other: t.Any) -> Sub:
732        raise NotImplementedError
733
734    def __mul__(self, other: t.Any) -> Mul:
735        raise NotImplementedError
736
737    def __rmul__(self, other: t.Any) -> Mul:
738        raise NotImplementedError
739
740    def __truediv__(self, other: t.Any) -> Div:
741        raise NotImplementedError
742
743    def __rtruediv__(self, other: t.Any) -> Div:
744        raise NotImplementedError
745
746    def __floordiv__(self, other: t.Any) -> IntDiv:
747        raise NotImplementedError
748
749    def __rfloordiv__(self, other: t.Any) -> IntDiv:
750        raise NotImplementedError
751
752    def __mod__(self, other: t.Any) -> Mod:
753        raise NotImplementedError
754
755    def __rmod__(self, other: t.Any) -> Mod:
756        raise NotImplementedError
757
758    def __pow__(self, other: t.Any) -> Pow:
759        raise NotImplementedError
760
761    def __rpow__(self, other: t.Any) -> Pow:
762        raise NotImplementedError
763
764    def __and__(self, other: t.Any) -> And:
765        raise NotImplementedError
766
767    def __rand__(self, other: t.Any) -> And:
768        raise NotImplementedError
769
770    def __or__(self, other: t.Any) -> Or:
771        raise NotImplementedError
772
773    def __ror__(self, other: t.Any) -> Or:
774        raise NotImplementedError
775
776    def __neg__(self) -> Neg:
777        raise NotImplementedError
778
779    def __invert__(self) -> Not:
780        raise NotImplementedError
781
782    def pipe(
783        self, func: t.Callable[Concatenate[Self, P], R], *args: P.args, **kwargs: P.kwargs
784    ) -> R:
785        """Apply a function to `Self` (the current instance) and return the result.
786
787        Doing `expr.pipe(func, *args, **kwargs)` is equivalent to `func(expr, *args, **kwargs)`.
788
789        It allows you to chain operations in a fluent way on any given function that takes `Self` as its first argument.
790
791        Tip:
792            If `func` doesn't take `Self` as it's first argument, you can use a lambda to work around it.
793
794        Args:
795            func: The function to apply. It should take `Self` as its first argument, followed by any additional arguments specified in `*args` and `**kwargs`.
796            *args: Additional positional arguments to pass to `func` after `Self`.
797            **kwargs: Additional keyword arguments to pass to `func`.
798
799        Returns:
800            The result of applying `func` to `Self` with the given arguments.
801        """
802        return func(self, *args, **kwargs)
803
804    def apply(
805        self, func: t.Callable[Concatenate[Self, P], t.Any], *args: P.args, **kwargs: P.kwargs
806    ) -> Self:
807        """Apply a function to `Self` (the current instance) for side effects, and return `Self`.
808
809        Useful for inspecting intermediate expressions in a method chain by simply adding/removing `apply` calls, especially when combined with `pipe`.
810
811        Tip:
812            If `func` doesn't take `Self` as it's first argument, you can use a lambda to work around it.
813
814        Args:
815            func: The function to apply. It should take `Self` as its first argument, followed by any additional arguments specified in `*args` and `**kwargs`.
816            *args: Additional positional arguments to pass to `func` after `Self`.
817            **kwargs: Additional keyword arguments to pass to `func`.
818
819        Returns:
820            The same instance.
821        """
822        func(self, *args, **kwargs)
823        return self

The base class for all expressions in a syntax tree. Each Expr encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expr hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines the arguments (child nodes) supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • index: the index of an expression if it is inside of a list argument in its parent.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
  • meta: a dictionary that can be used to store useful metadata for a given expression.
Example:
>>> class Foo(Expr):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expr that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
Expr(**args: object)
117    def __init__(self, **args: object) -> None:
118        self.args: dict[str, t.Any] = args
119        self.parent: Expr | None = None
120        self.arg_key: str | None = None
121        self.index: int | None = None
122        self.comments: list[str] | None = None
123        self._type: DataType | None = None
124        self._meta: dict[str, t.Any] | None = None
125        self._hash: int | None = None
126
127        if not self.is_primitive:
128            for arg_key, value in self.args.items():
129                self._set_parent(arg_key, value)
key: ClassVar[str] = 'expression'
arg_types: ClassVar[dict[str, bool]] = {'this': True}
required_args: 't.ClassVar[set[str]]' = {'this'}
is_var_len_args: ClassVar[bool] = False
var_len_arg_key: ClassVar[str] = 'expressions'
is_subquery: ClassVar[bool] = False
is_cast: ClassVar[bool] = False
is_data_type: ClassVar[bool] = False
args: dict[str, typing.Any]
parent: Expr | None
arg_key: str | None
index: int | None
comments: list[str] | None
is_primitive: ClassVar[bool] = False
this: Any
131    @property
132    def this(self) -> t.Any:
133        """
134        Retrieves the argument with key "this".
135        """
136        raise NotImplementedError

Retrieves the argument with key "this".

expression: Any
138    @property
139    def expression(self) -> t.Any:
140        """
141        Retrieves the argument with key "expression".
142        """
143        raise NotImplementedError

Retrieves the argument with key "expression".

expressions: list[typing.Any]
145    @property
146    def expressions(self) -> list[t.Any]:
147        """
148        Retrieves the argument with key "expressions".
149        """
150        raise NotImplementedError

Retrieves the argument with key "expressions".

def text(self, key: str) -> str:
152    def text(self, key: str) -> str:
153        """
154        Returns a textual representation of the argument corresponding to "key". This can only be used
155        for args that are strings or leaf Expr instances, such as identifiers and literals.
156        """
157        raise NotImplementedError

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expr instances, such as identifiers and literals.

is_string: bool
159    @property
160    def is_string(self) -> bool:
161        """
162        Checks whether a Literal expression is a string.
163        """
164        raise NotImplementedError

Checks whether a Literal expression is a string.

is_number: bool
166    @property
167    def is_number(self) -> bool:
168        """
169        Checks whether a Literal expression is a number.
170        """
171        raise NotImplementedError

Checks whether a Literal expression is a number.

def to_py(self) -> Any:
173    def to_py(self) -> t.Any:
174        """
175        Returns a Python object equivalent of the SQL node.
176        """
177        raise NotImplementedError

Returns a Python object equivalent of the SQL node.

is_int: bool
179    @property
180    def is_int(self) -> bool:
181        """
182        Checks whether an expression is an integer.
183        """
184        raise NotImplementedError

Checks whether an expression is an integer.

is_star: bool
186    @property
187    def is_star(self) -> bool:
188        """Checks whether an expression is a star."""
189        raise NotImplementedError

Checks whether an expression is a star.

alias: str
191    @property
192    def alias(self) -> str:
193        """
194        Returns the alias of the expression, or an empty string if it's not aliased.
195        """
196        raise NotImplementedError

Returns the alias of the expression, or an empty string if it's not aliased.

alias_column_names: list[str]
198    @property
199    def alias_column_names(self) -> list[str]:
200        raise NotImplementedError
name: str
202    @property
203    def name(self) -> str:
204        raise NotImplementedError
alias_or_name: str
206    @property
207    def alias_or_name(self) -> str:
208        raise NotImplementedError
output_name: str
210    @property
211    def output_name(self) -> str:
212        """
213        Name of the output column if this expression is a selection.
214
215        If the Expr has no output name, an empty string is returned.
216
217        Example:
218            >>> from sqlglot import parse_one
219            >>> parse_one("SELECT a").expressions[0].output_name
220            'a'
221            >>> parse_one("SELECT b AS c").expressions[0].output_name
222            'c'
223            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
224            ''
225        """
226        raise NotImplementedError

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
type: sqlglot.expressions.datatypes.DataType | None
228    @property
229    def type(self) -> DataType | None:
230        raise NotImplementedError
def is_type( self, *dtypes: Union[str, Identifier, Dot, sqlglot.expressions.datatypes.DataType, sqlglot.expressions.datatypes.DType]) -> bool:
236    def is_type(self, *dtypes: DATA_TYPE) -> bool:
237        raise NotImplementedError
def is_leaf(self) -> bool:
239    def is_leaf(self) -> bool:
240        raise NotImplementedError
meta: dict[str, typing.Any]
242    @property
243    def meta(self) -> dict[str, t.Any]:
244        raise NotImplementedError
def meta_get(self, key: str, default: Any = None) -> Any:
246    def meta_get(self, key: str, default: t.Any = None) -> t.Any:
247        raise NotImplementedError
def copy(self: ~E) -> ~E:
252    def copy(self: E) -> E:
253        """
254        Returns a deep copy of the expression.
255        """
256        raise NotImplementedError

Returns a deep copy of the expression.

def add_comments(self, comments: list[str] | None = None, prepend: bool = False) -> None:
258    def add_comments(self, comments: list[str] | None = None, prepend: bool = False) -> None:
259        raise NotImplementedError
def pop_comments(self) -> list[str]:
261    def pop_comments(self) -> list[str]:
262        raise NotImplementedError
def append(self, arg_key: str, value: Any) -> None:
264    def append(self, arg_key: str, value: t.Any) -> None:
265        """
266        Appends value to arg_key if it's a list or sets it as a new list.
267
268        Args:
269            arg_key (str): name of the list expression arg
270            value (Any): value to append to the list
271        """
272        raise NotImplementedError

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set( self, arg_key: str, value: object, index: int | None = None, overwrite: bool = True) -> None:
274    def set(
275        self,
276        arg_key: str,
277        value: object,
278        index: int | None = None,
279        overwrite: bool = True,
280    ) -> None:
281        """
282        Sets arg_key to value.
283
284        Args:
285            arg_key: name of the expression arg.
286            value: value to set the arg to.
287            index: if the arg is a list, this specifies what position to add the value in it.
288            overwrite: assuming an index is given, this determines whether to overwrite the
289                list entry instead of only inserting a new value (i.e., like list.insert).
290        """
291        raise NotImplementedError

Sets arg_key to value.

Arguments:
  • arg_key: name of the expression arg.
  • value: value to set the arg to.
  • index: if the arg is a list, this specifies what position to add the value in it.
  • overwrite: assuming an index is given, this determines whether to overwrite the list entry instead of only inserting a new value (i.e., like list.insert).
depth: int
296    @property
297    def depth(self) -> int:
298        """
299        Returns the depth of this tree.
300        """
301        raise NotImplementedError

Returns the depth of this tree.

def iter_expressions(self: ~E, reverse: bool = False) -> Iterator[~E]:
303    def iter_expressions(self: E, reverse: bool = False) -> Iterator[E]:
304        """Yields the key and expression for all arguments, exploding list args."""
305        raise NotImplementedError

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: type[~E], bfs: bool = True) -> Optional[~E]:
307    def find(self, *expression_types: Type[E], bfs: bool = True) -> E | None:
308        """
309        Returns the first node in this tree which matches at least one of
310        the specified types.
311
312        Args:
313            expression_types: the expression type(s) to match.
314            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
315
316        Returns:
317            The node which matches the criteria or None if no such node was found.
318        """
319        raise NotImplementedError

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: type[~E], bfs: bool = True) -> Iterator[~E]:
321    def find_all(self, *expression_types: Type[E], bfs: bool = True) -> Iterator[E]:
322        """
323        Returns a generator object which visits all nodes in this tree and only
324        yields those that match at least one of the specified expression types.
325
326        Args:
327            expression_types: the expression type(s) to match.
328            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
329
330        Returns:
331            The generator object.
332        """
333        raise NotImplementedError

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The generator object.

def find_ancestor(self, *expression_types: type[~E]) -> Optional[~E]:
335    def find_ancestor(self, *expression_types: Type[E]) -> E | None:
336        """
337        Returns a nearest parent matching expression_types.
338
339        Args:
340            expression_types: the expression type(s) to match.
341
342        Returns:
343            The parent node.
344        """
345        raise NotImplementedError

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select: sqlglot.expressions.query.Select | None
347    @property
348    def parent_select(self) -> Select | None:
349        """
350        Returns the parent select statement.
351        """
352        raise NotImplementedError

Returns the parent select statement.

same_parent: bool
354    @property
355    def same_parent(self) -> bool:
356        """Returns if the parent is the same class as itself."""
357        raise NotImplementedError

Returns if the parent is the same class as itself.

def root(self) -> Expr:
359    def root(self) -> Expr:
360        """
361        Returns the root expression of this tree.
362        """
363        raise NotImplementedError

Returns the root expression of this tree.

def walk( self, bfs: bool = True, prune: Optional[Callable[[Expr], bool]] = None) -> Iterator[Expr]:
365    def walk(
366        self, bfs: bool = True, prune: t.Callable[[Expr], bool] | None = None
367    ) -> Iterator[Expr]:
368        """
369        Returns a generator object which visits all nodes in this tree.
370
371        Args:
372            bfs: if set to True the BFS traversal order will be applied,
373                otherwise the DFS traversal will be used instead.
374            prune: callable that returns True if the generator should stop traversing
375                this branch of the tree.
376
377        Returns:
378            the generator object.
379        """
380        raise NotImplementedError

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs: if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune: callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs( self, prune: Optional[Callable[[Expr], bool]] = None) -> Iterator[Expr]:
382    def dfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
383        """
384        Returns a generator object which visits all nodes in this tree in
385        the DFS (Depth-first) order.
386
387        Returns:
388            The generator object.
389        """
390        raise NotImplementedError

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs( self, prune: Optional[Callable[[Expr], bool]] = None) -> Iterator[Expr]:
392    def bfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
393        """
394        Returns a generator object which visits all nodes in this tree in
395        the BFS (Breadth-first) order.
396
397        Returns:
398            The generator object.
399        """
400        raise NotImplementedError

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self) -> Expr:
402    def unnest(self) -> Expr:
403        """
404        Returns the first non parenthesis child or self.
405        """
406        raise NotImplementedError

Returns the first non parenthesis child or self.

def unalias(self) -> Expr:
408    def unalias(self) -> Expr:
409        """
410        Returns the inner expression if this is an Alias.
411        """
412        raise NotImplementedError

Returns the inner expression if this is an Alias.

def unnest_operands(self) -> tuple[Expr, ...]:
414    def unnest_operands(self) -> tuple[Expr, ...]:
415        """
416        Returns unnested operands as a tuple.
417        """
418        raise NotImplementedError

Returns unnested operands as a tuple.

def flatten(self, unnest: bool = True) -> Iterator[Expr]:
420    def flatten(self, unnest: bool = True) -> Iterator[Expr]:
421        """
422        Returns a generator which yields child nodes whose parents are the same class.
423
424        A AND B AND C -> [A, B, C]
425        """
426        raise NotImplementedError

Returns a generator which yields child nodes whose parents are the same class.

A AND B AND C -> [A, B, C]

def to_s(self) -> str:
428    def to_s(self) -> str:
429        """
430        Same as __repr__, but includes additional information which can be useful
431        for debugging, like empty or missing args and the AST nodes' object IDs.
432        """
433        raise NotImplementedError

Same as __repr__, but includes additional information which can be useful for debugging, like empty or missing args and the AST nodes' object IDs.

def sql( self, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.GeneratorNoDialectArgs]) -> str:
435    def sql(
436        self, dialect: DialectType = None, copy: bool = True, **opts: Unpack[GeneratorNoDialectArgs]
437    ) -> str:
438        """
439        Returns SQL string representation of this tree.
440
441        Args:
442            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
443            opts: other `sqlglot.generator.Generator` options.
444
445        Returns:
446            The SQL string.
447        """
448        raise NotImplementedError

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform( self, fun: Callable[..., ~T], *args: object, copy: bool = True, **kwargs: object) -> ~T:
450    def transform(
451        self, fun: t.Callable[..., T], *args: object, copy: bool = True, **kwargs: object
452    ) -> T:
453        """
454        Visits all tree nodes (excluding already transformed ones)
455        and applies the given transformation function to each node.
456
457        Args:
458            fun: a function which takes a node as an argument and returns a
459                new transformed node or the same node without modifications. If the function
460                returns None, then the corresponding node will be removed from the syntax tree.
461            copy: if set to True a new tree instance is constructed, otherwise the tree is
462                modified in place.
463
464        Returns:
465            The transformed tree.
466        """
467        raise NotImplementedError

Visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun: a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy: if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression: ~T) -> ~T:
469    def replace(self, expression: T) -> T:
470        """
471        Swap out this expression with a new expression.
472
473        For example::
474
475            >>> import sqlglot
476            >>> tree = sqlglot.parse_one("SELECT x FROM tbl")
477            >>> tree.find(sqlglot.exp.Column).replace(sqlglot.exp.column("y"))
478            Column(
479              this=Identifier(this=y, quoted=False))
480            >>> tree.sql()
481            'SELECT y FROM tbl'
482
483        Args:
484            expression (T): new node
485
486        Returns:
487            T: The new expression or expressions.
488        """
489        raise NotImplementedError

Swap out this expression with a new expression.

For example::

>>> import sqlglot
>>> tree = sqlglot.parse_one("SELECT x FROM tbl")
>>> tree.find(sqlglot.exp.Column).replace(sqlglot.exp.column("y"))
Column(
  this=Identifier(this=y, quoted=False))
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression (T): new node
Returns:

T: The new expression or expressions.

def pop(self: ~E) -> ~E:
491    def pop(self: E) -> E:
492        """
493        Remove this expression from its AST.
494
495        Returns:
496            The popped expression.
497        """
498        raise NotImplementedError

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_: type[~E]) -> ~E:
500    def assert_is(self, type_: Type[E]) -> E:
501        """
502        Assert that this `Expr` is an instance of `type_`.
503
504        If it is NOT an instance of `type_`, this raises an assertion error.
505        Otherwise, this returns this expression.
506
507        Examples:
508            This is useful for type security in chained expressions:
509
510            >>> import sqlglot
511            >>> sqlglot.parse_one("SELECT x from y").assert_is(sqlglot.exp.Select).select("z").sql()
512            'SELECT x, z FROM y'
513        """
514        raise NotImplementedError

Assert that this Expr is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(sqlglot.exp.Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Sequence[object] | None = None) -> list[str]:
516    def error_messages(self, args: Sequence[object] | None = None) -> list[str]:
517        """
518        Checks if this expression is valid (e.g. all mandatory args are set).
519
520        Args:
521            args: a sequence of values that were used to instantiate a Func expression. This is used
522                to check that the provided arguments don't exceed the function argument limit.
523
524        Returns:
525            A list of error messages for all possible errors that were found.
526        """
527        raise NotImplementedError

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self) -> list[dict[str, typing.Any]]:
529    def dump(self) -> list[dict[str, t.Any]]:
530        """
531        Dump this Expr to a JSON-serializable dict.
532        """
533        from sqlglot.serde import dump
534
535        return dump(self)

Dump this Expr to a JSON-serializable dict.

@classmethod
def load( cls, obj: list[dict[str, Any]] | None) -> Expr:
537    @classmethod
538    def load(cls, obj: list[dict[str, Any]] | None) -> Expr:
539        """
540        Load a dict (as returned by `Expr.dump`) into an Expr instance.
541        """
542        from sqlglot.serde import load
543
544        result = load(obj)
545        assert isinstance(result, Expr)
546        return result

Load a dict (as returned by Expr.dump) into an Expr instance.

def and_( self, *expressions: Union[int, str, Expr, NoneType], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, wrap: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Condition:
548    def and_(
549        self,
550        *expressions: ExpOrStr | None,
551        dialect: DialectType = None,
552        copy: bool = True,
553        wrap: bool = True,
554        **opts: Unpack[ParserNoDialectArgs],
555    ) -> Condition:
556        """
557        AND this condition with one or multiple expressions.
558
559        Example:
560            >>> condition("x=1").and_("y=1").sql()
561            'x = 1 AND y = 1'
562
563        Args:
564            *expressions: the SQL code strings to parse.
565                If an `Expr` instance is passed, it will be used as-is.
566            dialect: the dialect used to parse the input expression.
567            copy: whether to copy the involved expressions (only applies to Exprs).
568            wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
569                precedence issues, but can be turned off when the produced AST is too deep and
570                causes recursion-related issues.
571            opts: other options to use to parse the input expressions.
572
573        Returns:
574            The new And condition.
575        """
576        raise NotImplementedError

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expr instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the involved expressions (only applies to Exprs).
  • wrap: whether to wrap the operands in Parens. This is true by default to avoid precedence issues, but can be turned off when the produced AST is too deep and causes recursion-related issues.
  • opts: other options to use to parse the input expressions.
Returns:

The new And condition.

def or_( self, *expressions: Union[int, str, Expr, NoneType], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, wrap: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Condition:
578    def or_(
579        self,
580        *expressions: ExpOrStr | None,
581        dialect: DialectType = None,
582        copy: bool = True,
583        wrap: bool = True,
584        **opts: Unpack[ParserNoDialectArgs],
585    ) -> Condition:
586        """
587        OR this condition with one or multiple expressions.
588
589        Example:
590            >>> condition("x=1").or_("y=1").sql()
591            'x = 1 OR y = 1'
592
593        Args:
594            *expressions: the SQL code strings to parse.
595                If an `Expr` instance is passed, it will be used as-is.
596            dialect: the dialect used to parse the input expression.
597            copy: whether to copy the involved expressions (only applies to Exprs).
598            wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
599                precedence issues, but can be turned off when the produced AST is too deep and
600                causes recursion-related issues.
601            opts: other options to use to parse the input expressions.
602
603        Returns:
604            The new Or condition.
605        """
606        raise NotImplementedError

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expr instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the involved expressions (only applies to Exprs).
  • wrap: whether to wrap the operands in Parens. This is true by default to avoid precedence issues, but can be turned off when the produced AST is too deep and causes recursion-related issues.
  • opts: other options to use to parse the input expressions.
Returns:

The new Or condition.

def not_(self, copy: bool = True) -> Not:
608    def not_(self, copy: bool = True) -> Not:
609        """
610        Wrap this condition with NOT.
611
612        Example:
613            >>> condition("x=1").not_().sql()
614            'NOT x = 1'
615
616        Args:
617            copy: whether to copy this object.
618
619        Returns:
620            The new Not instance.
621        """
622        raise NotImplementedError

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Arguments:
  • copy: whether to copy this object.
Returns:

The new Not instance.

def update_positions( self: ~E, other: sqlglot.tokenizer_core.Token | Expr | None = None, line: int | None = None, col: int | None = None, start: int | None = None, end: int | None = None) -> ~E:
624    def update_positions(
625        self: E,
626        other: Token | Expr | None = None,
627        line: int | None = None,
628        col: int | None = None,
629        start: int | None = None,
630        end: int | None = None,
631    ) -> E:
632        """
633        Update this expression with positions from a token or other expression.
634
635        Args:
636            other: a token or expression to update this expression with.
637            line: the line number to use if other is None
638            col: column number
639            start: start char index
640            end:  end char index
641
642        Returns:
643            The updated expression.
644        """
645        raise NotImplementedError

Update this expression with positions from a token or other expression.

Arguments:
  • other: a token or expression to update this expression with.
  • line: the line number to use if other is None
  • col: column number
  • start: start char index
  • end: end char index
Returns:

The updated expression.

def as_( self, alias: str | Identifier, quoted: bool | None = None, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, table: bool | Sequence[str | Identifier] = False, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Expr:
647    def as_(
648        self,
649        alias: str | Identifier,
650        quoted: bool | None = None,
651        dialect: DialectType = None,
652        copy: bool = True,
653        table: bool | Sequence[str | Identifier] = False,
654        **opts: Unpack[ParserNoDialectArgs],
655    ) -> Expr:
656        raise NotImplementedError
def isin( self, *expressions: Any, query: Union[int, str, Expr, NoneType] = None, unnest: Union[int, str, Expr, NoneType, list[Union[int, str, Expr]], tuple[Union[int, str, Expr], ...]] = None, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> In:
667    def isin(
668        self,
669        *expressions: t.Any,
670        query: ExpOrStr | None = None,
671        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
672        dialect: DialectType = None,
673        copy: bool = True,
674        **opts: Unpack[ParserNoDialectArgs],
675    ) -> In:
676        raise NotImplementedError
def between( self, low: Any, high: Any, copy: bool = True, symmetric: bool | None = None) -> Between:
678    def between(
679        self, low: t.Any, high: t.Any, copy: bool = True, symmetric: bool | None = None
680    ) -> Between:
681        raise NotImplementedError
def is_( self, other: Union[int, str, Expr]) -> Is:
683    def is_(self, other: ExpOrStr) -> Is:
684        raise NotImplementedError
def like( self, other: Union[int, str, Expr]) -> Like:
686    def like(self, other: ExpOrStr) -> Like:
687        raise NotImplementedError
def ilike( self, other: Union[int, str, Expr]) -> ILike:
689    def ilike(self, other: ExpOrStr) -> ILike:
690        raise NotImplementedError
def eq(self, other: Any) -> EQ:
692    def eq(self, other: t.Any) -> EQ:
693        raise NotImplementedError
def neq(self, other: Any) -> NEQ:
695    def neq(self, other: t.Any) -> NEQ:
696        raise NotImplementedError
def rlike( self, other: Union[int, str, Expr]) -> RegexpLike:
698    def rlike(self, other: ExpOrStr) -> RegexpLike:
699        raise NotImplementedError
def div( self, other: Union[int, str, Expr], typed: bool = False, safe: bool = False) -> Div:
701    def div(self, other: ExpOrStr, typed: bool = False, safe: bool = False) -> Div:
702        raise NotImplementedError
def asc(self, nulls_first: bool = True) -> Ordered:
704    def asc(self, nulls_first: bool = True) -> Ordered:
705        raise NotImplementedError
def desc(self, nulls_first: bool = False) -> Ordered:
707    def desc(self, nulls_first: bool = False) -> Ordered:
708        raise NotImplementedError
def pipe( self, func: Callable[typing_extensions.Concatenate[typing_extensions.Self, ~P], ~R], *args: P.args, **kwargs: P.kwargs) -> ~R:
782    def pipe(
783        self, func: t.Callable[Concatenate[Self, P], R], *args: P.args, **kwargs: P.kwargs
784    ) -> R:
785        """Apply a function to `Self` (the current instance) and return the result.
786
787        Doing `expr.pipe(func, *args, **kwargs)` is equivalent to `func(expr, *args, **kwargs)`.
788
789        It allows you to chain operations in a fluent way on any given function that takes `Self` as its first argument.
790
791        Tip:
792            If `func` doesn't take `Self` as it's first argument, you can use a lambda to work around it.
793
794        Args:
795            func: The function to apply. It should take `Self` as its first argument, followed by any additional arguments specified in `*args` and `**kwargs`.
796            *args: Additional positional arguments to pass to `func` after `Self`.
797            **kwargs: Additional keyword arguments to pass to `func`.
798
799        Returns:
800            The result of applying `func` to `Self` with the given arguments.
801        """
802        return func(self, *args, **kwargs)

Apply a function to Self (the current instance) and return the result.

Doing expr.pipe(func, *args, **kwargs) is equivalent to func(expr, *args, **kwargs).

It allows you to chain operations in a fluent way on any given function that takes Self as its first argument.

Tip:

If func doesn't take Self as it's first argument, you can use a lambda to work around it.

Arguments:
  • func: The function to apply. It should take Self as its first argument, followed by any additional arguments specified in *args and **kwargs.
  • *args: Additional positional arguments to pass to func after Self.
  • **kwargs: Additional keyword arguments to pass to func.
Returns:

The result of applying func to Self with the given arguments.

def apply( self, func: Callable[typing_extensions.Concatenate[typing_extensions.Self, ~P], Any], *args: P.args, **kwargs: P.kwargs) -> typing_extensions.Self:
804    def apply(
805        self, func: t.Callable[Concatenate[Self, P], t.Any], *args: P.args, **kwargs: P.kwargs
806    ) -> Self:
807        """Apply a function to `Self` (the current instance) for side effects, and return `Self`.
808
809        Useful for inspecting intermediate expressions in a method chain by simply adding/removing `apply` calls, especially when combined with `pipe`.
810
811        Tip:
812            If `func` doesn't take `Self` as it's first argument, you can use a lambda to work around it.
813
814        Args:
815            func: The function to apply. It should take `Self` as its first argument, followed by any additional arguments specified in `*args` and `**kwargs`.
816            *args: Additional positional arguments to pass to `func` after `Self`.
817            **kwargs: Additional keyword arguments to pass to `func`.
818
819        Returns:
820            The same instance.
821        """
822        func(self, *args, **kwargs)
823        return self

Apply a function to Self (the current instance) for side effects, and return Self.

Useful for inspecting intermediate expressions in a method chain by simply adding/removing apply calls, especially when combined with pipe.

Tip:

If func doesn't take Self as it's first argument, you can use a lambda to work around it.

Arguments:
  • func: The function to apply. It should take Self as its first argument, followed by any additional arguments specified in *args and **kwargs.
  • *args: Additional positional arguments to pass to func after Self.
  • **kwargs: Additional keyword arguments to pass to func.
Returns:

The same instance.

class Expression(Expr):
 826class Expression(Expr):
 827    __slots__ = (
 828        "args",
 829        "parent",
 830        "arg_key",
 831        "index",
 832        "comments",
 833        "_type",
 834        "_meta",
 835        "_hash",
 836    )
 837
 838    def __eq__(self, other: object) -> bool:
 839        return self is other or (type(self) is type(other) and hash(self) == hash(other))
 840
 841    def __ne__(self, other: object) -> bool:
 842        return not self.__eq__(other)
 843
 844    def __hash__(self) -> int:
 845        if self._hash is None:
 846            nodes: list[Expr] = []
 847            stack: list[Expr] = [self]
 848
 849            # Collect nodes, finding child expressions inline instead of via the
 850            # iter_expressions generator (whose per-node generator object dominates the
 851            # hash's cost). reversed(nodes) is a valid post-order regardless of DFS/BFS.
 852            while stack:
 853                node = stack.pop()
 854                nodes.append(node)
 855
 856                for v in node.args.values():
 857                    if isinstance(v, Expr):
 858                        if v._hash is None:
 859                            stack.append(v)
 860                    elif type(v) is list:
 861                        for x in v:
 862                            if isinstance(x, Expr) and x._hash is None:
 863                                stack.append(x)
 864
 865            for node in reversed(nodes):
 866                hash_ = hash(node.key)
 867
 868                if node._hash_raw_args:
 869                    for k in sorted(node.args):
 870                        v = node.args[k]
 871                        if v:
 872                            hash_ = hash((hash_, k, tuple(v) if type(v) is list else v))
 873                else:
 874                    for k in sorted(node.args):
 875                        v = node.args[k]
 876                        vt = type(v)
 877
 878                        if vt is list:
 879                            for x in v:
 880                                if x is not None and x is not False:
 881                                    hash_ = hash((hash_, k, x.lower() if type(x) is str else x))
 882                                else:
 883                                    hash_ = hash((hash_, k))
 884                        elif v is not None and v is not False:
 885                            hash_ = hash((hash_, k, v.lower() if vt is str else v))
 886
 887                node._hash = hash_
 888        assert self._hash
 889        return self._hash
 890
 891    def __reduce__(
 892        self,
 893    ) -> tuple[
 894        t.Callable[[list[dict[str, t.Any]] | None], Expr | DType | None],
 895        tuple[list[dict[str, t.Any]]],
 896    ]:
 897        from sqlglot.serde import dump, load
 898
 899        return (load, (dump(self),))
 900
 901    @property
 902    def this(self) -> t.Any:
 903        return self.args.get("this")
 904
 905    @property
 906    def expression(self) -> t.Any:
 907        return self.args.get("expression")
 908
 909    @property
 910    def expressions(self) -> list[t.Any]:
 911        return self.args.get("expressions") or []
 912
 913    def text(self, key: str) -> str:
 914        field = self.args.get(key)
 915        if isinstance(field, str):
 916            return field
 917        if isinstance(field, (Identifier, Literal, Var)):
 918            return field.this
 919        if isinstance(field, (Star, Null)):
 920            return field.name
 921        return ""
 922
 923    @property
 924    def is_string(self) -> bool:
 925        return isinstance(self, Literal) and self.args["is_string"]
 926
 927    @property
 928    def is_number(self) -> bool:
 929        return (isinstance(self, Literal) and not self.args["is_string"]) or (
 930            isinstance(self, Neg) and self.this.is_number
 931        )
 932
 933    def to_py(self) -> t.Any:
 934        raise ValueError(f"{self} cannot be converted to a Python object.")
 935
 936    @property
 937    def is_int(self) -> bool:
 938        try:
 939            return self.is_number and isinstance(self.to_py(), int)
 940        except ValueError:
 941            return False
 942
 943    @property
 944    def is_star(self) -> bool:
 945        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 946
 947    @property
 948    def alias(self) -> str:
 949        alias = self.args.get("alias")
 950        if isinstance(alias, Expression):
 951            return alias.name
 952        return self.text("alias")
 953
 954    @property
 955    def alias_column_names(self) -> list[str]:
 956        table_alias = self.args.get("alias")
 957        if not table_alias:
 958            return []
 959        return [c.name for c in table_alias.args.get("columns") or []]
 960
 961    @property
 962    def name(self) -> str:
 963        return self.text("this")
 964
 965    @property
 966    def alias_or_name(self) -> str:
 967        return self.alias or self.name
 968
 969    @property
 970    def output_name(self) -> str:
 971        return ""
 972
 973    @property
 974    def type(self) -> DataType | None:
 975        if self.is_data_type:
 976            return self  # type: ignore[return-value]
 977        if self.is_cast:
 978            return self._type or self.to  # type: ignore[attr-defined]
 979        return self._type
 980
 981    @type.setter
 982    def type(self, dtype: DataType | DType | str | None) -> None:
 983        if dtype and type(dtype).__name__ != "DataType":
 984            from sqlglot.expressions.datatypes import DataType as _DataType
 985
 986            dtype = _DataType.build(dtype)
 987        self._type = dtype  # type: ignore[assignment]
 988
 989    def is_type(self, *dtypes: DATA_TYPE) -> bool:
 990        t = self._type
 991        return t is not None and t.is_type(*dtypes)
 992
 993    def is_leaf(self) -> bool:
 994        return not any((isinstance(v, Expr) or type(v) is list) and v for v in self.args.values())
 995
 996    @property
 997    def meta(self) -> dict[str, t.Any]:
 998        if self._meta is None:
 999            self._meta = {}
1000        return self._meta
1001
1002    def meta_get(self, key: str, default: t.Any = None) -> t.Any:
1003        """Reads a meta value without allocating the meta dict (unlike the `meta` property)."""
1004        meta = self._meta
1005        return meta.get(key, default) if meta is not None else default
1006
1007    def __deepcopy__(self, memo: t.Any) -> Expr:
1008        root = self.__class__()
1009        stack: list[tuple[Expr, Expr]] = [(self, root)]
1010
1011        while stack:
1012            node, copy = stack.pop()
1013
1014            if node.comments is not None:
1015                copy.comments = deepcopy(node.comments)
1016            if node._type is not None:
1017                copy._type = deepcopy(node._type)
1018            if node._meta is not None:
1019                # Positions and flags are immutable, so only other values need a deep copy
1020                meta = copy._meta = dict(node._meta)
1021                for k, v in meta.items():
1022                    if type(v) not in _IMMUTABLE_META_TYPES:
1023                        meta[k] = deepcopy(v)
1024            if node._hash is not None:
1025                copy._hash = node._hash
1026
1027            for k, vs in node.args.items():
1028                if isinstance(vs, Expr):
1029                    stack.append((vs, vs.__class__()))
1030                    copy.set(k, stack[-1][-1])
1031                elif type(vs) is list:
1032                    copy.args[k] = []
1033
1034                    for v in vs:
1035                        if isinstance(v, Expr):
1036                            stack.append((v, v.__class__()))
1037                            copy.append(k, stack[-1][-1])
1038                        else:
1039                            copy.append(k, v)
1040                else:
1041                    copy.args[k] = vs
1042
1043        return root
1044
1045    def copy(self: E) -> E:
1046        return deepcopy(self)
1047
1048    def add_comments(self, comments: list[str] | None = None, prepend: bool = False) -> None:
1049        if self.comments is None:
1050            self.comments = []
1051
1052        if comments:
1053            for comment in comments:
1054                _, *meta = comment.split(SQLGLOT_META)
1055                if meta:
1056                    for kv in "".join(meta).split(","):
1057                        k, *v = kv.split("=")
1058                        self.meta[k.strip()] = to_bool(v[0].strip() if v else True)
1059
1060                if not prepend:
1061                    self.comments.append(comment)
1062
1063            if prepend:
1064                self.comments = comments + self.comments
1065
1066    def pop_comments(self) -> list[str]:
1067        comments = self.comments or []
1068        self.comments = None
1069        return comments
1070
1071    def append(self, arg_key: str, value: t.Any) -> None:
1072        node: Expr | None = self
1073        while node and node._hash is not None:
1074            node._hash = None
1075            node = node.parent
1076
1077        if type(self.args.get(arg_key)) is not list:
1078            self.args[arg_key] = []
1079        self._set_parent(arg_key, value)
1080        values = self.args[arg_key]
1081        if isinstance(value, Expr):
1082            value.index = len(values)
1083        values.append(value)
1084
1085    def set(
1086        self,
1087        arg_key: str,
1088        value: object,
1089        index: int | None = None,
1090        overwrite: bool = True,
1091    ) -> None:
1092        node: Expr | None = self
1093
1094        while node and node._hash is not None:
1095            node._hash = None
1096            node = node.parent
1097
1098        if index is not None:
1099            expressions = self.args.get(arg_key) or []
1100
1101            if seq_get(expressions, index) is None:
1102                return
1103
1104            if value is None:
1105                expressions.pop(index)
1106                for v in expressions[index:]:
1107                    v.index = v.index - 1
1108                return
1109
1110            if isinstance(value, list):
1111                expressions.pop(index)
1112                expressions[index:index] = value
1113            elif overwrite:
1114                expressions[index] = value
1115            else:
1116                expressions.insert(index, value)
1117
1118            value = expressions
1119        elif value is None:
1120            self.args.pop(arg_key, None)
1121            return
1122
1123        self.args[arg_key] = value
1124        self._set_parent(arg_key, value, index)
1125
1126    def _set_parent(self, arg_key: str, value: object, index: int | None = None) -> None:
1127        if isinstance(value, Expr):
1128            value.parent = self
1129            value.arg_key = arg_key
1130            value.index = index
1131        elif isinstance(value, list):
1132            for i, v in enumerate(value):
1133                if isinstance(v, Expr):
1134                    v.parent = self
1135                    v.arg_key = arg_key
1136                    v.index = i
1137
1138    def set_kwargs(self, kwargs: Mapping[str, object]) -> Self:
1139        """Set multiples keyword arguments at once, using `.set()` method.
1140
1141        Args:
1142            kwargs (Mapping[str, object]): a `Mapping` of arg keys to values to set.
1143        Returns:
1144            Self: The same `Expression` with the updated arguments.
1145        """
1146        if kwargs:
1147            for k, v in kwargs.items():
1148                self.set(k, v)
1149        return self
1150
1151    @property
1152    def depth(self) -> int:
1153        if self.parent:
1154            return self.parent.depth + 1
1155        return 0
1156
1157    def iter_expressions(self: E, reverse: bool = False) -> Iterator[E]:
1158        for vs in reversed(self.args.values()) if reverse else self.args.values():
1159            if isinstance(vs, list):
1160                for v in reversed(vs) if reverse else vs:
1161                    if isinstance(v, Expr):
1162                        yield t.cast(E, v)
1163            elif isinstance(vs, Expr):
1164                yield t.cast(E, vs)
1165
1166    def find(self, *expression_types: Type[E], bfs: bool = True) -> E | None:
1167        return next(self.find_all(*expression_types, bfs=bfs), None)
1168
1169    def find_all(self, *expression_types: Type[E], bfs: bool = True) -> Iterator[E]:
1170        for expression in self.walk(bfs=bfs):
1171            if isinstance(expression, expression_types):
1172                yield expression
1173
1174    def find_ancestor(self, *expression_types: Type[E]) -> E | None:
1175        ancestor = self.parent
1176        while ancestor and not isinstance(ancestor, expression_types):
1177            ancestor = ancestor.parent
1178        return ancestor  # type: ignore[return-value]
1179
1180    @property
1181    def parent_select(self) -> Select | None:
1182        from sqlglot.expressions.query import Select as _Select
1183
1184        return self.find_ancestor(_Select)
1185
1186    @property
1187    def same_parent(self) -> bool:
1188        return type(self.parent) is self.__class__
1189
1190    def root(self) -> Expr:
1191        expression: Expr = self
1192        while expression.parent:
1193            expression = expression.parent
1194        return expression
1195
1196    def walk(
1197        self, bfs: bool = True, prune: t.Callable[[Expr], bool] | None = None
1198    ) -> Iterator[Expr]:
1199        if bfs:
1200            yield from self.bfs(prune=prune)
1201        else:
1202            yield from self.dfs(prune=prune)
1203
1204    def dfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
1205        stack = [self]
1206
1207        while stack:
1208            node = stack.pop()
1209            yield node
1210            if prune and prune(node):
1211                continue
1212            for v in node.iter_expressions(reverse=True):
1213                stack.append(v)
1214
1215    def bfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
1216        queue: deque[Expr] = deque()
1217        queue.append(self)
1218
1219        while queue:
1220            node = queue.popleft()
1221            yield node
1222            if prune and prune(node):
1223                continue
1224            for v in node.iter_expressions():
1225                queue.append(v)
1226
1227    def unnest(self) -> Expr:
1228        expression = self
1229        while type(expression) is Paren:
1230            expression = expression.this
1231        return expression
1232
1233    def unalias(self) -> Expr:
1234        if isinstance(self, Alias):
1235            return self.this
1236        return self
1237
1238    def unnest_operands(self) -> tuple[Expr, ...]:
1239        return tuple(arg.unnest() for arg in self.iter_expressions())
1240
1241    def flatten(self, unnest: bool = True) -> Iterator[Expr]:
1242        for node in self.dfs(prune=lambda n: bool(n.parent and type(n) is not self.__class__)):
1243            if type(node) is not self.__class__:
1244                yield node.unnest() if unnest and not node.is_subquery else node
1245
1246    def __str__(self) -> str:
1247        return self.sql()
1248
1249    def __repr__(self) -> str:
1250        return _to_s(self)
1251
1252    def to_s(self) -> str:
1253        return _to_s(self, verbose=True)
1254
1255    def sql(
1256        self, dialect: DialectType = None, copy: bool = True, **opts: Unpack[GeneratorNoDialectArgs]
1257    ) -> str:
1258        from sqlglot.dialects.dialect import Dialect
1259
1260        return Dialect.get_or_raise(dialect).generate(self, copy=copy, **opts)
1261
1262    def transform(
1263        self, fun: t.Callable[..., T], *args: object, copy: bool = True, **kwargs: object
1264    ) -> T:
1265        root: t.Any = None
1266        new_node: t.Any = None
1267
1268        for node in (self.copy() if copy else self).dfs(prune=lambda n: n is not new_node):
1269            parent, arg_key, index = node.parent, node.arg_key, node.index
1270            new_node = fun(node, *args, **kwargs)
1271
1272            if not root:
1273                root = new_node
1274            elif parent and arg_key and new_node is not node:
1275                parent.set(arg_key, new_node, index)
1276
1277        assert root
1278        return root
1279
1280    def replace(self, expression: T) -> T:
1281        parent = self.parent
1282
1283        if not parent or parent is expression:
1284            return expression
1285
1286        key = self.arg_key
1287
1288        if key:
1289            value = parent.args.get(key)
1290
1291            if type(expression) is list and isinstance(value, Expr):
1292                # We are trying to replace an Expr with a list, so it's assumed that
1293                # the intention was to really replace the parent of this expression.
1294                if value.parent:
1295                    value.parent.replace(expression)
1296            else:
1297                parent.set(key, expression, self.index)
1298
1299        if expression is not self:
1300            self.parent = None
1301            self.arg_key = None
1302            self.index = None
1303
1304        return expression
1305
1306    def pop(self: E) -> E:
1307        self.replace(None)
1308        return self
1309
1310    def assert_is(self, type_: Type[E]) -> E:
1311        if not isinstance(self, type_):
1312            raise AssertionError(f"{self} is not {type_}.")
1313        return self
1314
1315    def error_messages(self, args: Sequence[object] | None = None) -> list[str]:
1316        if UNITTEST:
1317            for k in self.args:
1318                if k not in self.arg_types:
1319                    raise TypeError(f"Unexpected keyword: '{k}' for {self.__class__}")
1320
1321        errors: list[str] | None = None
1322
1323        for k in self.required_args:
1324            v = self.args.get(k)
1325            if v is None or (isinstance(v, list) and not v):
1326                if errors is None:
1327                    errors = []
1328                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
1329
1330        if (
1331            args
1332            and isinstance(self, Func)
1333            and len(args) > len(self.arg_types)
1334            and not self.is_var_len_args
1335        ):
1336            if errors is None:
1337                errors = []
1338            errors.append(
1339                f"The number of provided arguments ({len(args)}) is greater than "
1340                f"the maximum number of supported arguments ({len(self.arg_types)})"
1341            )
1342
1343        return errors or []
1344
1345    def and_(
1346        self,
1347        *expressions: ExpOrStr | None,
1348        dialect: DialectType = None,
1349        copy: bool = True,
1350        wrap: bool = True,
1351        **opts: Unpack[ParserNoDialectArgs],
1352    ) -> Condition:
1353        return and_(self, *expressions, dialect=dialect, copy=copy, wrap=wrap, **opts)
1354
1355    def or_(
1356        self,
1357        *expressions: ExpOrStr | None,
1358        dialect: DialectType = None,
1359        copy: bool = True,
1360        wrap: bool = True,
1361        **opts: Unpack[ParserNoDialectArgs],
1362    ) -> Condition:
1363        return or_(self, *expressions, dialect=dialect, copy=copy, wrap=wrap, **opts)
1364
1365    def not_(self, copy: bool = True) -> Not:
1366        return not_(self, copy=copy)
1367
1368    def update_positions(
1369        self: E,
1370        other: Token | Expr | None = None,
1371        line: int | None = None,
1372        col: int | None = None,
1373        start: int | None = None,
1374        end: int | None = None,
1375    ) -> E:
1376        if isinstance(other, Token):
1377            meta = self.meta
1378            meta["line"] = other.line
1379            meta["col"] = other.col
1380            meta["start"] = other.start
1381            meta["end"] = other.end
1382        elif other is not None:
1383            other_meta = other._meta
1384            if other_meta:
1385                meta = self.meta
1386                for k in POSITION_META_KEYS:
1387                    if k in other_meta:
1388                        meta[k] = other_meta[k]
1389        else:
1390            meta = self.meta
1391            meta["line"] = line
1392            meta["col"] = col
1393            meta["start"] = start
1394            meta["end"] = end
1395        return self
1396
1397    def as_(
1398        self,
1399        alias: str | Identifier,
1400        quoted: bool | None = None,
1401        dialect: DialectType = None,
1402        copy: bool = True,
1403        table: bool | Sequence[str | Identifier] = False,
1404        **opts: Unpack[ParserNoDialectArgs],
1405    ) -> Expr:
1406        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, table=table, **opts)
1407
1408    def _binop(self, klass: Type[E], other: t.Any, reverse: bool = False) -> E:
1409        left: Expr = self.copy()
1410        right = convert(other, copy=True)
1411        if reverse:
1412            left, right = right, left
1413
1414        # NOT binds more tightly than AND and OR, but more loosely than comparisons and arithmetic.
1415        if not issubclass(klass, Connector):
1416            left = _wrap(left, Not)
1417            right = _wrap(right, Not)
1418
1419        # A repeated operator can chain on the left, but SQL may reject chained predicates.
1420        if not isinstance(left, klass) or isinstance(left, Predicate):
1421            left = _wrap(left, Binary)
1422        return klass(this=left, expression=_wrap(right, Binary))
1423
1424    def __getitem__(self, other: ExpOrStr | tuple[ExpOrStr, ...]) -> Bracket:
1425        return Bracket(
1426            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
1427        )
1428
1429    def __iter__(self) -> Iterator:
1430        if "expressions" in self.arg_types:
1431            return iter(self.args.get("expressions") or [])
1432        # We define this because __getitem__ converts Expr into an iterable, which is
1433        # problematic because one can hit infinite loops if they do "for x in some_expr: ..."
1434        # See: https://peps.python.org/pep-0234/
1435        raise TypeError(f"'{self.__class__.__name__}' object is not iterable")
1436
1437    def isin(
1438        self,
1439        *expressions: t.Any,
1440        query: ExpOrStr | None = None,
1441        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
1442        dialect: DialectType = None,
1443        copy: bool = True,
1444        **opts: Unpack[ParserNoDialectArgs],
1445    ) -> In:
1446        from sqlglot.expressions.query import Query
1447
1448        subquery: Expr | None = None
1449        if query:
1450            subquery = maybe_parse(query, dialect=dialect, copy=copy, **opts)
1451            if isinstance(subquery, Query):
1452                subquery = subquery.subquery(copy=False)
1453        unnest_list: list[ExpOrStr] = ensure_list(unnest)
1454        return In(
1455            this=maybe_copy(self, copy),
1456            expressions=[convert(e, copy=copy) for e in expressions],
1457            query=subquery,
1458            unnest=(
1459                _lazy_unnest(
1460                    expressions=[
1461                        maybe_parse(e, dialect=dialect, copy=copy, **opts) for e in unnest_list
1462                    ]
1463                )
1464                if unnest
1465                else None
1466            ),
1467        )
1468
1469    def between(
1470        self, low: t.Any, high: t.Any, copy: bool = True, symmetric: bool | None = None
1471    ) -> Between:
1472        between = Between(
1473            this=maybe_copy(self, copy),
1474            low=convert(low, copy=copy),
1475            high=convert(high, copy=copy),
1476        )
1477        if symmetric is not None:
1478            between.set("symmetric", symmetric)
1479
1480        return between
1481
1482    def is_(self, other: ExpOrStr) -> Is:
1483        if isinstance(other, Not) and isinstance(other.this, (Null, Boolean)):
1484            predicate = self._binop(Is, other.this)
1485            predicate.set("negate", True)
1486            return predicate
1487        return self._binop(Is, other)
1488
1489    def like(self, other: ExpOrStr) -> Like:
1490        return self._binop(Like, other)
1491
1492    def ilike(self, other: ExpOrStr) -> ILike:
1493        return self._binop(ILike, other)
1494
1495    def eq(self, other: t.Any) -> EQ:
1496        return self._binop(EQ, other)
1497
1498    def neq(self, other: t.Any) -> NEQ:
1499        return self._binop(NEQ, other)
1500
1501    def rlike(self, other: ExpOrStr) -> RegexpLike:
1502        return self._binop(RegexpLike, other)
1503
1504    def div(self, other: ExpOrStr, typed: bool = False, safe: bool = False) -> Div:
1505        div = self._binop(Div, other)
1506        div.set("typed", typed)
1507        div.set("safe", safe)
1508        return div
1509
1510    def asc(self, nulls_first: bool = True) -> Ordered:
1511        return Ordered(this=self.copy(), nulls_first=nulls_first)
1512
1513    def desc(self, nulls_first: bool = False) -> Ordered:
1514        return Ordered(this=self.copy(), desc=True, nulls_first=nulls_first)
1515
1516    def __lt__(self, other: t.Any) -> LT:
1517        return self._binop(LT, other)
1518
1519    def __le__(self, other: t.Any) -> LTE:
1520        return self._binop(LTE, other)
1521
1522    def __gt__(self, other: t.Any) -> GT:
1523        return self._binop(GT, other)
1524
1525    def __ge__(self, other: t.Any) -> GTE:
1526        return self._binop(GTE, other)
1527
1528    def __add__(self, other: t.Any) -> Add:
1529        return self._binop(Add, other)
1530
1531    def __radd__(self, other: t.Any) -> Add:
1532        return self._binop(Add, other, reverse=True)
1533
1534    def __sub__(self, other: t.Any) -> Sub:
1535        return self._binop(Sub, other)
1536
1537    def __rsub__(self, other: t.Any) -> Sub:
1538        return self._binop(Sub, other, reverse=True)
1539
1540    def __mul__(self, other: t.Any) -> Mul:
1541        return self._binop(Mul, other)
1542
1543    def __rmul__(self, other: t.Any) -> Mul:
1544        return self._binop(Mul, other, reverse=True)
1545
1546    def __truediv__(self, other: t.Any) -> Div:
1547        return self._binop(Div, other)
1548
1549    def __rtruediv__(self, other: t.Any) -> Div:
1550        return self._binop(Div, other, reverse=True)
1551
1552    def __floordiv__(self, other: t.Any) -> IntDiv:
1553        return self._binop(IntDiv, other)
1554
1555    def __rfloordiv__(self, other: t.Any) -> IntDiv:
1556        return self._binop(IntDiv, other, reverse=True)
1557
1558    def __mod__(self, other: t.Any) -> Mod:
1559        return self._binop(Mod, other)
1560
1561    def __rmod__(self, other: t.Any) -> Mod:
1562        return self._binop(Mod, other, reverse=True)
1563
1564    def __pow__(self, other: t.Any) -> Pow:
1565        return self._binop(Pow, other)
1566
1567    def __rpow__(self, other: t.Any) -> Pow:
1568        return self._binop(Pow, other, reverse=True)
1569
1570    def __and__(self, other: t.Any) -> And:
1571        return self._binop(And, other)
1572
1573    def __rand__(self, other: t.Any) -> And:
1574        return self._binop(And, other, reverse=True)
1575
1576    def __or__(self, other: t.Any) -> Or:
1577        return self._binop(Or, other)
1578
1579    def __ror__(self, other: t.Any) -> Or:
1580        return self._binop(Or, other, reverse=True)
1581
1582    def __neg__(self) -> Neg:
1583        return Neg(this=_wrap(self.copy(), Binary))
1584
1585    def __invert__(self) -> Not:
1586        return not_(self.copy())
this: Any
901    @property
902    def this(self) -> t.Any:
903        return self.args.get("this")

Retrieves the argument with key "this".

expression: Any
905    @property
906    def expression(self) -> t.Any:
907        return self.args.get("expression")

Retrieves the argument with key "expression".

expressions: list[typing.Any]
909    @property
910    def expressions(self) -> list[t.Any]:
911        return self.args.get("expressions") or []

Retrieves the argument with key "expressions".

def text(self, key: str) -> str:
913    def text(self, key: str) -> str:
914        field = self.args.get(key)
915        if isinstance(field, str):
916            return field
917        if isinstance(field, (Identifier, Literal, Var)):
918            return field.this
919        if isinstance(field, (Star, Null)):
920            return field.name
921        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expr instances, such as identifiers and literals.

is_string: bool
923    @property
924    def is_string(self) -> bool:
925        return isinstance(self, Literal) and self.args["is_string"]

Checks whether a Literal expression is a string.

is_number: bool
927    @property
928    def is_number(self) -> bool:
929        return (isinstance(self, Literal) and not self.args["is_string"]) or (
930            isinstance(self, Neg) and self.this.is_number
931        )

Checks whether a Literal expression is a number.

def to_py(self) -> Any:
933    def to_py(self) -> t.Any:
934        raise ValueError(f"{self} cannot be converted to a Python object.")

Returns a Python object equivalent of the SQL node.

is_int: bool
936    @property
937    def is_int(self) -> bool:
938        try:
939            return self.is_number and isinstance(self.to_py(), int)
940        except ValueError:
941            return False

Checks whether an expression is an integer.

is_star: bool
943    @property
944    def is_star(self) -> bool:
945        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))

Checks whether an expression is a star.

alias: str
947    @property
948    def alias(self) -> str:
949        alias = self.args.get("alias")
950        if isinstance(alias, Expression):
951            return alias.name
952        return self.text("alias")

Returns the alias of the expression, or an empty string if it's not aliased.

alias_column_names: list[str]
954    @property
955    def alias_column_names(self) -> list[str]:
956        table_alias = self.args.get("alias")
957        if not table_alias:
958            return []
959        return [c.name for c in table_alias.args.get("columns") or []]
name: str
961    @property
962    def name(self) -> str:
963        return self.text("this")
alias_or_name: str
965    @property
966    def alias_or_name(self) -> str:
967        return self.alias or self.name
output_name: str
969    @property
970    def output_name(self) -> str:
971        return ""

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
type: sqlglot.expressions.datatypes.DataType | None
973    @property
974    def type(self) -> DataType | None:
975        if self.is_data_type:
976            return self  # type: ignore[return-value]
977        if self.is_cast:
978            return self._type or self.to  # type: ignore[attr-defined]
979        return self._type
def is_type( self, *dtypes: Union[str, Identifier, Dot, sqlglot.expressions.datatypes.DataType, sqlglot.expressions.datatypes.DType]) -> bool:
989    def is_type(self, *dtypes: DATA_TYPE) -> bool:
990        t = self._type
991        return t is not None and t.is_type(*dtypes)
def is_leaf(self) -> bool:
993    def is_leaf(self) -> bool:
994        return not any((isinstance(v, Expr) or type(v) is list) and v for v in self.args.values())
meta: dict[str, typing.Any]
 996    @property
 997    def meta(self) -> dict[str, t.Any]:
 998        if self._meta is None:
 999            self._meta = {}
1000        return self._meta
def meta_get(self, key: str, default: Any = None) -> Any:
1002    def meta_get(self, key: str, default: t.Any = None) -> t.Any:
1003        """Reads a meta value without allocating the meta dict (unlike the `meta` property)."""
1004        meta = self._meta
1005        return meta.get(key, default) if meta is not None else default

Reads a meta value without allocating the meta dict (unlike the meta property).

def copy(self: ~E) -> ~E:
1045    def copy(self: E) -> E:
1046        return deepcopy(self)

Returns a deep copy of the expression.

def add_comments(self, comments: list[str] | None = None, prepend: bool = False) -> None:
1048    def add_comments(self, comments: list[str] | None = None, prepend: bool = False) -> None:
1049        if self.comments is None:
1050            self.comments = []
1051
1052        if comments:
1053            for comment in comments:
1054                _, *meta = comment.split(SQLGLOT_META)
1055                if meta:
1056                    for kv in "".join(meta).split(","):
1057                        k, *v = kv.split("=")
1058                        self.meta[k.strip()] = to_bool(v[0].strip() if v else True)
1059
1060                if not prepend:
1061                    self.comments.append(comment)
1062
1063            if prepend:
1064                self.comments = comments + self.comments
def pop_comments(self) -> list[str]:
1066    def pop_comments(self) -> list[str]:
1067        comments = self.comments or []
1068        self.comments = None
1069        return comments
def append(self, arg_key: str, value: Any) -> None:
1071    def append(self, arg_key: str, value: t.Any) -> None:
1072        node: Expr | None = self
1073        while node and node._hash is not None:
1074            node._hash = None
1075            node = node.parent
1076
1077        if type(self.args.get(arg_key)) is not list:
1078            self.args[arg_key] = []
1079        self._set_parent(arg_key, value)
1080        values = self.args[arg_key]
1081        if isinstance(value, Expr):
1082            value.index = len(values)
1083        values.append(value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set( self, arg_key: str, value: object, index: int | None = None, overwrite: bool = True) -> None:
1085    def set(
1086        self,
1087        arg_key: str,
1088        value: object,
1089        index: int | None = None,
1090        overwrite: bool = True,
1091    ) -> None:
1092        node: Expr | None = self
1093
1094        while node and node._hash is not None:
1095            node._hash = None
1096            node = node.parent
1097
1098        if index is not None:
1099            expressions = self.args.get(arg_key) or []
1100
1101            if seq_get(expressions, index) is None:
1102                return
1103
1104            if value is None:
1105                expressions.pop(index)
1106                for v in expressions[index:]:
1107                    v.index = v.index - 1
1108                return
1109
1110            if isinstance(value, list):
1111                expressions.pop(index)
1112                expressions[index:index] = value
1113            elif overwrite:
1114                expressions[index] = value
1115            else:
1116                expressions.insert(index, value)
1117
1118            value = expressions
1119        elif value is None:
1120            self.args.pop(arg_key, None)
1121            return
1122
1123        self.args[arg_key] = value
1124        self._set_parent(arg_key, value, index)

Sets arg_key to value.

Arguments:
  • arg_key: name of the expression arg.
  • value: value to set the arg to.
  • index: if the arg is a list, this specifies what position to add the value in it.
  • overwrite: assuming an index is given, this determines whether to overwrite the list entry instead of only inserting a new value (i.e., like list.insert).
def set_kwargs(self, kwargs: Mapping[str, object]) -> typing_extensions.Self:
1138    def set_kwargs(self, kwargs: Mapping[str, object]) -> Self:
1139        """Set multiples keyword arguments at once, using `.set()` method.
1140
1141        Args:
1142            kwargs (Mapping[str, object]): a `Mapping` of arg keys to values to set.
1143        Returns:
1144            Self: The same `Expression` with the updated arguments.
1145        """
1146        if kwargs:
1147            for k, v in kwargs.items():
1148                self.set(k, v)
1149        return self

Set multiples keyword arguments at once, using .set() method.

Arguments:
  • kwargs (Mapping[str, object]): a Mapping of arg keys to values to set.
Returns:

Self: The same Expression with the updated arguments.

depth: int
1151    @property
1152    def depth(self) -> int:
1153        if self.parent:
1154            return self.parent.depth + 1
1155        return 0

Returns the depth of this tree.

def iter_expressions(self: ~E, reverse: bool = False) -> Iterator[~E]:
1157    def iter_expressions(self: E, reverse: bool = False) -> Iterator[E]:
1158        for vs in reversed(self.args.values()) if reverse else self.args.values():
1159            if isinstance(vs, list):
1160                for v in reversed(vs) if reverse else vs:
1161                    if isinstance(v, Expr):
1162                        yield t.cast(E, v)
1163            elif isinstance(vs, Expr):
1164                yield t.cast(E, vs)

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: type[~E], bfs: bool = True) -> Optional[~E]:
1166    def find(self, *expression_types: Type[E], bfs: bool = True) -> E | None:
1167        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: type[~E], bfs: bool = True) -> Iterator[~E]:
1169    def find_all(self, *expression_types: Type[E], bfs: bool = True) -> Iterator[E]:
1170        for expression in self.walk(bfs=bfs):
1171            if isinstance(expression, expression_types):
1172                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The generator object.

def find_ancestor(self, *expression_types: type[~E]) -> Optional[~E]:
1174    def find_ancestor(self, *expression_types: Type[E]) -> E | None:
1175        ancestor = self.parent
1176        while ancestor and not isinstance(ancestor, expression_types):
1177            ancestor = ancestor.parent
1178        return ancestor  # type: ignore[return-value]

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select: sqlglot.expressions.query.Select | None
1180    @property
1181    def parent_select(self) -> Select | None:
1182        from sqlglot.expressions.query import Select as _Select
1183
1184        return self.find_ancestor(_Select)

Returns the parent select statement.

same_parent: bool
1186    @property
1187    def same_parent(self) -> bool:
1188        return type(self.parent) is self.__class__

Returns if the parent is the same class as itself.

def root(self) -> Expr:
1190    def root(self) -> Expr:
1191        expression: Expr = self
1192        while expression.parent:
1193            expression = expression.parent
1194        return expression

Returns the root expression of this tree.

def walk( self, bfs: bool = True, prune: Optional[Callable[[Expr], bool]] = None) -> Iterator[Expr]:
1196    def walk(
1197        self, bfs: bool = True, prune: t.Callable[[Expr], bool] | None = None
1198    ) -> Iterator[Expr]:
1199        if bfs:
1200            yield from self.bfs(prune=prune)
1201        else:
1202            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs: if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune: callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs( self, prune: Optional[Callable[[Expr], bool]] = None) -> Iterator[Expr]:
1204    def dfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
1205        stack = [self]
1206
1207        while stack:
1208            node = stack.pop()
1209            yield node
1210            if prune and prune(node):
1211                continue
1212            for v in node.iter_expressions(reverse=True):
1213                stack.append(v)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs( self, prune: Optional[Callable[[Expr], bool]] = None) -> Iterator[Expr]:
1215    def bfs(self, prune: t.Callable[[Expr], bool] | None = None) -> Iterator[Expr]:
1216        queue: deque[Expr] = deque()
1217        queue.append(self)
1218
1219        while queue:
1220            node = queue.popleft()
1221            yield node
1222            if prune and prune(node):
1223                continue
1224            for v in node.iter_expressions():
1225                queue.append(v)

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self) -> Expr:
1227    def unnest(self) -> Expr:
1228        expression = self
1229        while type(expression) is Paren:
1230            expression = expression.this
1231        return expression

Returns the first non parenthesis child or self.

def unalias(self) -> Expr:
1233    def unalias(self) -> Expr:
1234        if isinstance(self, Alias):
1235            return self.this
1236        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self) -> tuple[Expr, ...]:
1238    def unnest_operands(self) -> tuple[Expr, ...]:
1239        return tuple(arg.unnest() for arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest: bool = True) -> Iterator[Expr]:
1241    def flatten(self, unnest: bool = True) -> Iterator[Expr]:
1242        for node in self.dfs(prune=lambda n: bool(n.parent and type(n) is not self.__class__)):
1243            if type(node) is not self.__class__:
1244                yield node.unnest() if unnest and not node.is_subquery else node

Returns a generator which yields child nodes whose parents are the same class.

A AND B AND C -> [A, B, C]

def to_s(self) -> str:
1252    def to_s(self) -> str:
1253        return _to_s(self, verbose=True)

Same as __repr__, but includes additional information which can be useful for debugging, like empty or missing args and the AST nodes' object IDs.

def sql( self, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.GeneratorNoDialectArgs]) -> str:
1255    def sql(
1256        self, dialect: DialectType = None, copy: bool = True, **opts: Unpack[GeneratorNoDialectArgs]
1257    ) -> str:
1258        from sqlglot.dialects.dialect import Dialect
1259
1260        return Dialect.get_or_raise(dialect).generate(self, copy=copy, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform( self, fun: Callable[..., ~T], *args: object, copy: bool = True, **kwargs: object) -> ~T:
1262    def transform(
1263        self, fun: t.Callable[..., T], *args: object, copy: bool = True, **kwargs: object
1264    ) -> T:
1265        root: t.Any = None
1266        new_node: t.Any = None
1267
1268        for node in (self.copy() if copy else self).dfs(prune=lambda n: n is not new_node):
1269            parent, arg_key, index = node.parent, node.arg_key, node.index
1270            new_node = fun(node, *args, **kwargs)
1271
1272            if not root:
1273                root = new_node
1274            elif parent and arg_key and new_node is not node:
1275                parent.set(arg_key, new_node, index)
1276
1277        assert root
1278        return root

Visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun: a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy: if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression: ~T) -> ~T:
1280    def replace(self, expression: T) -> T:
1281        parent = self.parent
1282
1283        if not parent or parent is expression:
1284            return expression
1285
1286        key = self.arg_key
1287
1288        if key:
1289            value = parent.args.get(key)
1290
1291            if type(expression) is list and isinstance(value, Expr):
1292                # We are trying to replace an Expr with a list, so it's assumed that
1293                # the intention was to really replace the parent of this expression.
1294                if value.parent:
1295                    value.parent.replace(expression)
1296            else:
1297                parent.set(key, expression, self.index)
1298
1299        if expression is not self:
1300            self.parent = None
1301            self.arg_key = None
1302            self.index = None
1303
1304        return expression

Swap out this expression with a new expression.

For example::

>>> import sqlglot
>>> tree = sqlglot.parse_one("SELECT x FROM tbl")
>>> tree.find(sqlglot.exp.Column).replace(sqlglot.exp.column("y"))
Column(
  this=Identifier(this=y, quoted=False))
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression (T): new node
Returns:

T: The new expression or expressions.

def pop(self: ~E) -> ~E:
1306    def pop(self: E) -> E:
1307        self.replace(None)
1308        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_: type[~E]) -> ~E:
1310    def assert_is(self, type_: Type[E]) -> E:
1311        if not isinstance(self, type_):
1312            raise AssertionError(f"{self} is not {type_}.")
1313        return self

Assert that this Expr is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(sqlglot.exp.Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Sequence[object] | None = None) -> list[str]:
1315    def error_messages(self, args: Sequence[object] | None = None) -> list[str]:
1316        if UNITTEST:
1317            for k in self.args:
1318                if k not in self.arg_types:
1319                    raise TypeError(f"Unexpected keyword: '{k}' for {self.__class__}")
1320
1321        errors: list[str] | None = None
1322
1323        for k in self.required_args:
1324            v = self.args.get(k)
1325            if v is None or (isinstance(v, list) and not v):
1326                if errors is None:
1327                    errors = []
1328                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
1329
1330        if (
1331            args
1332            and isinstance(self, Func)
1333            and len(args) > len(self.arg_types)
1334            and not self.is_var_len_args
1335        ):
1336            if errors is None:
1337                errors = []
1338            errors.append(
1339                f"The number of provided arguments ({len(args)}) is greater than "
1340                f"the maximum number of supported arguments ({len(self.arg_types)})"
1341            )
1342
1343        return errors or []

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def and_( self, *expressions: Union[int, str, Expr, NoneType], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, wrap: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Condition:
1345    def and_(
1346        self,
1347        *expressions: ExpOrStr | None,
1348        dialect: DialectType = None,
1349        copy: bool = True,
1350        wrap: bool = True,
1351        **opts: Unpack[ParserNoDialectArgs],
1352    ) -> Condition:
1353        return and_(self, *expressions, dialect=dialect, copy=copy, wrap=wrap, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expr instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the involved expressions (only applies to Exprs).
  • wrap: whether to wrap the operands in Parens. This is true by default to avoid precedence issues, but can be turned off when the produced AST is too deep and causes recursion-related issues.
  • opts: other options to use to parse the input expressions.
Returns:

The new And condition.

def or_( self, *expressions: Union[int, str, Expr, NoneType], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, wrap: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Condition:
1355    def or_(
1356        self,
1357        *expressions: ExpOrStr | None,
1358        dialect: DialectType = None,
1359        copy: bool = True,
1360        wrap: bool = True,
1361        **opts: Unpack[ParserNoDialectArgs],
1362    ) -> Condition:
1363        return or_(self, *expressions, dialect=dialect, copy=copy, wrap=wrap, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expr instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the involved expressions (only applies to Exprs).
  • wrap: whether to wrap the operands in Parens. This is true by default to avoid precedence issues, but can be turned off when the produced AST is too deep and causes recursion-related issues.
  • opts: other options to use to parse the input expressions.
Returns:

The new Or condition.

def not_(self, copy: bool = True) -> Not:
1365    def not_(self, copy: bool = True) -> Not:
1366        return not_(self, copy=copy)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Arguments:
  • copy: whether to copy this object.
Returns:

The new Not instance.

def update_positions( self: ~E, other: sqlglot.tokenizer_core.Token | Expr | None = None, line: int | None = None, col: int | None = None, start: int | None = None, end: int | None = None) -> ~E:
1368    def update_positions(
1369        self: E,
1370        other: Token | Expr | None = None,
1371        line: int | None = None,
1372        col: int | None = None,
1373        start: int | None = None,
1374        end: int | None = None,
1375    ) -> E:
1376        if isinstance(other, Token):
1377            meta = self.meta
1378            meta["line"] = other.line
1379            meta["col"] = other.col
1380            meta["start"] = other.start
1381            meta["end"] = other.end
1382        elif other is not None:
1383            other_meta = other._meta
1384            if other_meta:
1385                meta = self.meta
1386                for k in POSITION_META_KEYS:
1387                    if k in other_meta:
1388                        meta[k] = other_meta[k]
1389        else:
1390            meta = self.meta
1391            meta["line"] = line
1392            meta["col"] = col
1393            meta["start"] = start
1394            meta["end"] = end
1395        return self

Update this expression with positions from a token or other expression.

Arguments:
  • other: a token or expression to update this expression with.
  • line: the line number to use if other is None
  • col: column number
  • start: start char index
  • end: end char index
Returns:

The updated expression.

def as_( self, alias: str | Identifier, quoted: bool | None = None, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, table: bool | Sequence[str | Identifier] = False, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Expr:
1397    def as_(
1398        self,
1399        alias: str | Identifier,
1400        quoted: bool | None = None,
1401        dialect: DialectType = None,
1402        copy: bool = True,
1403        table: bool | Sequence[str | Identifier] = False,
1404        **opts: Unpack[ParserNoDialectArgs],
1405    ) -> Expr:
1406        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, table=table, **opts)
def isin( self, *expressions: Any, query: Union[int, str, Expr, NoneType] = None, unnest: Union[int, str, Expr, NoneType, list[Union[int, str, Expr]], tuple[Union[int, str, Expr], ...]] = None, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> In:
1437    def isin(
1438        self,
1439        *expressions: t.Any,
1440        query: ExpOrStr | None = None,
1441        unnest: ExpOrStr | None | list[ExpOrStr] | tuple[ExpOrStr, ...] = None,
1442        dialect: DialectType = None,
1443        copy: bool = True,
1444        **opts: Unpack[ParserNoDialectArgs],
1445    ) -> In:
1446        from sqlglot.expressions.query import Query
1447
1448        subquery: Expr | None = None
1449        if query:
1450            subquery = maybe_parse(query, dialect=dialect, copy=copy, **opts)
1451            if isinstance(subquery, Query):
1452                subquery = subquery.subquery(copy=False)
1453        unnest_list: list[ExpOrStr] = ensure_list(unnest)
1454        return In(
1455            this=maybe_copy(self, copy),
1456            expressions=[convert(e, copy=copy) for e in expressions],
1457            query=subquery,
1458            unnest=(
1459                _lazy_unnest(
1460                    expressions=[
1461                        maybe_parse(e, dialect=dialect, copy=copy, **opts) for e in unnest_list
1462                    ]
1463                )
1464                if unnest
1465                else None
1466            ),
1467        )
def between( self, low: Any, high: Any, copy: bool = True, symmetric: bool | None = None) -> Between:
1469    def between(
1470        self, low: t.Any, high: t.Any, copy: bool = True, symmetric: bool | None = None
1471    ) -> Between:
1472        between = Between(
1473            this=maybe_copy(self, copy),
1474            low=convert(low, copy=copy),
1475            high=convert(high, copy=copy),
1476        )
1477        if symmetric is not None:
1478            between.set("symmetric", symmetric)
1479
1480        return between
def is_( self, other: Union[int, str, Expr]) -> Is:
1482    def is_(self, other: ExpOrStr) -> Is:
1483        if isinstance(other, Not) and isinstance(other.this, (Null, Boolean)):
1484            predicate = self._binop(Is, other.this)
1485            predicate.set("negate", True)
1486            return predicate
1487        return self._binop(Is, other)
def like( self, other: Union[int, str, Expr]) -> Like:
1489    def like(self, other: ExpOrStr) -> Like:
1490        return self._binop(Like, other)
def ilike( self, other: Union[int, str, Expr]) -> ILike:
1492    def ilike(self, other: ExpOrStr) -> ILike:
1493        return self._binop(ILike, other)
def eq(self, other: Any) -> EQ:
1495    def eq(self, other: t.Any) -> EQ:
1496        return self._binop(EQ, other)
def neq(self, other: Any) -> NEQ:
1498    def neq(self, other: t.Any) -> NEQ:
1499        return self._binop(NEQ, other)
def rlike( self, other: Union[int, str, Expr]) -> RegexpLike:
1501    def rlike(self, other: ExpOrStr) -> RegexpLike:
1502        return self._binop(RegexpLike, other)
def div( self, other: Union[int, str, Expr], typed: bool = False, safe: bool = False) -> Div:
1504    def div(self, other: ExpOrStr, typed: bool = False, safe: bool = False) -> Div:
1505        div = self._binop(Div, other)
1506        div.set("typed", typed)
1507        div.set("safe", safe)
1508        return div
def asc(self, nulls_first: bool = True) -> Ordered:
1510    def asc(self, nulls_first: bool = True) -> Ordered:
1511        return Ordered(this=self.copy(), nulls_first=nulls_first)
def desc(self, nulls_first: bool = False) -> Ordered:
1513    def desc(self, nulls_first: bool = False) -> Ordered:
1514        return Ordered(this=self.copy(), desc=True, nulls_first=nulls_first)
key: ClassVar[str] = 'expression'
required_args: 't.ClassVar[set[str]]' = {'this'}
args: dict[str, typing.Any]
parent: Expr | None
arg_key: str | None
index: int | None
comments: list[str] | None
IntoType = typing.Union[type[Expr], collections.abc.Collection[type[Expr]]]
ExpOrStr = typing.Union[int, str, Expr]
@trait
class Condition(Expr):
1593@trait
1594class Condition(Expr):
1595    """Logical conditions like x AND y, or simply x"""

Logical conditions like x AND y, or simply x

key: ClassVar[str] = 'condition'
required_args: 't.ClassVar[set[str]]' = {'this'}
@trait
class Predicate(Condition):
1598@trait
1599class Predicate(Condition):
1600    """Any condition that evaluates to a boolean, e.g. x = y, x LIKE 'a%', a @> b."""

Any condition that evaluates to a boolean, e.g. x = y, x LIKE 'a%', a @> b.

key: ClassVar[str] = 'predicate'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Cache(Expression):
1603class Cache(Expression):
1604    arg_types = {
1605        "this": True,
1606        "lazy": False,
1607        "options": False,
1608        "expression": False,
1609    }
arg_types = {'this': True, 'lazy': False, 'options': False, 'expression': False}
key: ClassVar[str] = 'cache'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Uncache(Expression):
1612class Uncache(Expression):
1613    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key: ClassVar[str] = 'uncache'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Refresh(Expression):
1616class Refresh(Expression):
1617    arg_types = {
1618        "this": True,
1619        "kind": True,
1620        "partition_start": False,
1621        "partition_end": False,
1622        "force": False,
1623        "mode": False,
1624    }
arg_types = {'this': True, 'kind': True, 'partition_start': False, 'partition_end': False, 'force': False, 'mode': False}
key: ClassVar[str] = 'refresh'
required_args: 't.ClassVar[set[str]]' = {'kind', 'this'}
class LockingStatement(Expression):
1627class LockingStatement(Expression):
1628    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key: ClassVar[str] = 'lockingstatement'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
@trait
class ColumnConstraintKind(Expr):
1631@trait
1632class ColumnConstraintKind(Expr):
1633    pass
key: ClassVar[str] = 'columnconstraintkind'
required_args: 't.ClassVar[set[str]]' = {'this'}
@trait
class SubqueryPredicate(Predicate):
1636@trait
1637class SubqueryPredicate(Predicate):
1638    pass
key: ClassVar[str] = 'subquerypredicate'
required_args: 't.ClassVar[set[str]]' = {'this'}
class All(Expression, SubqueryPredicate):
1641class All(Expression, SubqueryPredicate):
1642    pass
key: ClassVar[str] = 'all'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Any(Expression, SubqueryPredicate):
1645class Any(Expression, SubqueryPredicate):
1646    pass
key: ClassVar[str] = 'any'
required_args: 't.ClassVar[set[str]]' = {'this'}
@trait
class Binary(Condition):
1649@trait
1650class Binary(Condition):
1651    arg_types: t.ClassVar[dict[str, bool]] = {"this": True, "expression": True}
1652
1653    @property
1654    def left(self) -> Expr:
1655        return self.args["this"]
1656
1657    @property
1658    def right(self) -> Expr:
1659        return self.args["expression"]
arg_types: ClassVar[dict[str, bool]] = {'this': True, 'expression': True}
left: Expr
1653    @property
1654    def left(self) -> Expr:
1655        return self.args["this"]
right: Expr
1657    @property
1658    def right(self) -> Expr:
1659        return self.args["expression"]
key: ClassVar[str] = 'binary'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
@trait
class Connector(Binary):
1662@trait
1663class Connector(Binary):
1664    pass
key: ClassVar[str] = 'connector'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
@trait
class Func(Condition):
1667@trait
1668class Func(Condition):
1669    """
1670    The base class for all function expressions.
1671
1672    Attributes:
1673        is_var_len_args (bool): if set to True the argument identified by var_len_arg_key will be
1674            treated as a variable length argument and the argument's value will be stored as a list.
1675        var_len_arg_key (str): the arg_types key that collects the variable length arguments.
1676            Arguments preceding it in arg_types are filled positionally; those following it (e.g.
1677            dialect flags) are never populated by from_arg_list.
1678        _sql_names (list): the SQL name (1st item in the list) and aliases (subsequent items) for this
1679            function expression. These values are used to map this node to a name during parsing as
1680            well as to provide the function's name during SQL string generation. By default the SQL
1681            name is set to the expression's class name transformed to snake case.
1682    """
1683
1684    is_var_len_args: t.ClassVar[bool] = False
1685    var_len_arg_key: t.ClassVar[str] = "expressions"
1686    _sql_names: t.ClassVar[list[str]] = []
1687
1688    @classmethod
1689    def from_arg_list(cls, args: Sequence[object]) -> Self:
1690        if cls.is_var_len_args:
1691            all_arg_keys = tuple(cls.arg_types)
1692            var_len_index = all_arg_keys.index(cls.var_len_arg_key)
1693
1694            args_dict = {arg_key: arg for arg, arg_key in zip(args, all_arg_keys[:var_len_index])}
1695            args_dict[cls.var_len_arg_key] = args[var_len_index:]
1696        else:
1697            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
1698
1699        return cls(**args_dict)
1700
1701    @classmethod
1702    def sql_names(cls) -> list[str]:
1703        if cls is Func:
1704            raise NotImplementedError(
1705                "SQL name is only supported by concrete function implementations"
1706            )
1707        if not cls._sql_names:
1708            return [camel_to_snake_case(cls.__name__)]
1709        return cls._sql_names
1710
1711    @classmethod
1712    def sql_name(cls) -> str:
1713        sql_names = cls.sql_names()
1714        assert sql_names, f"Expected non-empty 'sql_names' for Func: {cls.__name__}."
1715        return sql_names[0]
1716
1717    @classmethod
1718    def default_parser_mappings(cls) -> dict[str, t.Callable[[Sequence[object]], Self]]:
1719        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the argument identified by var_len_arg_key will be treated as a variable length argument and the argument's value will be stored as a list.
  • var_len_arg_key (str): the arg_types key that collects the variable length arguments. Arguments preceding it in arg_types are filled positionally; those following it (e.g. dialect flags) are never populated by from_arg_list.
  • _sql_names (list): the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
is_var_len_args: ClassVar[bool] = False
var_len_arg_key: ClassVar[str] = 'expressions'
@classmethod
def from_arg_list(cls, args: Sequence[object]) -> typing_extensions.Self:
1688    @classmethod
1689    def from_arg_list(cls, args: Sequence[object]) -> Self:
1690        if cls.is_var_len_args:
1691            all_arg_keys = tuple(cls.arg_types)
1692            var_len_index = all_arg_keys.index(cls.var_len_arg_key)
1693
1694            args_dict = {arg_key: arg for arg, arg_key in zip(args, all_arg_keys[:var_len_index])}
1695            args_dict[cls.var_len_arg_key] = args[var_len_index:]
1696        else:
1697            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
1698
1699        return cls(**args_dict)
@classmethod
def sql_names(cls) -> list[str]:
1701    @classmethod
1702    def sql_names(cls) -> list[str]:
1703        if cls is Func:
1704            raise NotImplementedError(
1705                "SQL name is only supported by concrete function implementations"
1706            )
1707        if not cls._sql_names:
1708            return [camel_to_snake_case(cls.__name__)]
1709        return cls._sql_names
@classmethod
def sql_name(cls) -> str:
1711    @classmethod
1712    def sql_name(cls) -> str:
1713        sql_names = cls.sql_names()
1714        assert sql_names, f"Expected non-empty 'sql_names' for Func: {cls.__name__}."
1715        return sql_names[0]
@classmethod
def default_parser_mappings( cls) -> dict[str, typing.Callable[[Sequence[object]], typing_extensions.Self]]:
1717    @classmethod
1718    def default_parser_mappings(cls) -> dict[str, t.Callable[[Sequence[object]], Self]]:
1719        return {name: cls.from_arg_list for name in cls.sql_names()}
key: ClassVar[str] = 'func'
required_args: 't.ClassVar[set[str]]' = {'this'}
@trait
class AggFunc(Func):
1722@trait
1723class AggFunc(Func):
1724    pass
key: ClassVar[str] = 'aggfunc'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Column(Expression, Condition):
1727class Column(Expression, Condition):
1728    # "shadow" marks a column whose qualifier is shadowed by a projection alias, so it must be
1729    # rendered unqualified in dialects where PROJECTION_ALIASES_SHADOW_SOURCE_NAMES is set
1730    arg_types = {
1731        "this": True,
1732        "table": False,
1733        "db": False,
1734        "catalog": False,
1735        "join_mark": False,
1736        "shadow": False,
1737    }
1738
1739    @property
1740    def table(self) -> str:
1741        return self.text("table")
1742
1743    @property
1744    def db(self) -> str:
1745        return self.text("db")
1746
1747    @property
1748    def catalog(self) -> str:
1749        return self.text("catalog")
1750
1751    @property
1752    def output_name(self) -> str:
1753        return self.name
1754
1755    @property
1756    def parts(self) -> list[Expr]:
1757        """Return the parts of a column in order catalog, db, table, name."""
1758        return [
1759            self.args[part] for part in ("catalog", "db", "table", "this") if self.args.get(part)
1760        ]
1761
1762    def to_dot(self, include_dots: bool = True) -> Expr:
1763        """Converts the column into a dot expression."""
1764        parts = self.parts
1765        parent = self.parent
1766
1767        if include_dots:
1768            while isinstance(parent, Dot):
1769                parts.append(parent.expression)
1770                parent = parent.parent
1771
1772        return Dot.build(deepcopy(parts)) if len(parts) > 1 else parts[0]
arg_types = {'this': True, 'table': False, 'db': False, 'catalog': False, 'join_mark': False, 'shadow': False}
table: str
1739    @property
1740    def table(self) -> str:
1741        return self.text("table")
db: str
1743    @property
1744    def db(self) -> str:
1745        return self.text("db")
catalog: str
1747    @property
1748    def catalog(self) -> str:
1749        return self.text("catalog")
output_name: str
1751    @property
1752    def output_name(self) -> str:
1753        return self.name

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
parts: list[Expr]
1755    @property
1756    def parts(self) -> list[Expr]:
1757        """Return the parts of a column in order catalog, db, table, name."""
1758        return [
1759            self.args[part] for part in ("catalog", "db", "table", "this") if self.args.get(part)
1760        ]

Return the parts of a column in order catalog, db, table, name.

def to_dot(self, include_dots: bool = True) -> Expr:
1762    def to_dot(self, include_dots: bool = True) -> Expr:
1763        """Converts the column into a dot expression."""
1764        parts = self.parts
1765        parent = self.parent
1766
1767        if include_dots:
1768            while isinstance(parent, Dot):
1769                parts.append(parent.expression)
1770                parent = parent.parent
1771
1772        return Dot.build(deepcopy(parts)) if len(parts) > 1 else parts[0]

Converts the column into a dot expression.

key: ClassVar[str] = 'column'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Literal(Expression, Condition):
1775class Literal(Expression, Condition):
1776    arg_types = {"this": True, "is_string": True}
1777    _hash_raw_args = True
1778    is_primitive = True
1779
1780    @classmethod
1781    def number(cls, number: object) -> Literal | Neg:
1782        lit = cls(this=str(number), is_string=False)
1783        try:
1784            to_py = lit.to_py()
1785            if not isinstance(to_py, str) and to_py < 0:
1786                lit.set("this", str(to_py.copy_abs() if isinstance(to_py, Decimal) else abs(to_py)))
1787                return Neg(this=lit)
1788        except Exception:
1789            pass
1790        return lit
1791
1792    @classmethod
1793    def string(cls, string: object) -> Literal:
1794        return cls(this=str(string), is_string=True)
1795
1796    @property
1797    def output_name(self) -> str:
1798        return self.name
1799
1800    def to_py(self) -> int | str | Decimal:
1801        if self.is_number:
1802            try:
1803                return int(self.this)
1804            except ValueError:
1805                try:
1806                    return Decimal(self.this)
1807                except InvalidOperation as e:
1808                    raise ValueError(f"Invalid numeric literal: {self.this!r}") from e
1809        return self.this
arg_types = {'this': True, 'is_string': True}
is_primitive = True
@classmethod
def number( cls, number: object) -> Literal | Neg:
1780    @classmethod
1781    def number(cls, number: object) -> Literal | Neg:
1782        lit = cls(this=str(number), is_string=False)
1783        try:
1784            to_py = lit.to_py()
1785            if not isinstance(to_py, str) and to_py < 0:
1786                lit.set("this", str(to_py.copy_abs() if isinstance(to_py, Decimal) else abs(to_py)))
1787                return Neg(this=lit)
1788        except Exception:
1789            pass
1790        return lit
@classmethod
def string(cls, string: object) -> Literal:
1792    @classmethod
1793    def string(cls, string: object) -> Literal:
1794        return cls(this=str(string), is_string=True)
output_name: str
1796    @property
1797    def output_name(self) -> str:
1798        return self.name

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def to_py(self) -> int | str | decimal.Decimal:
1800    def to_py(self) -> int | str | Decimal:
1801        if self.is_number:
1802            try:
1803                return int(self.this)
1804            except ValueError:
1805                try:
1806                    return Decimal(self.this)
1807                except InvalidOperation as e:
1808                    raise ValueError(f"Invalid numeric literal: {self.this!r}") from e
1809        return self.this

Returns a Python object equivalent of the SQL node.

key: ClassVar[str] = 'literal'
required_args: 't.ClassVar[set[str]]' = {'is_string', 'this'}
class Var(Expression):
1812class Var(Expression):
1813    is_primitive = True
is_primitive = True
key: ClassVar[str] = 'var'
required_args: 't.ClassVar[set[str]]' = {'this'}
class WithinGroup(Expression):
1816class WithinGroup(Expression):
1817    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key: ClassVar[str] = 'withingroup'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Pseudocolumn(Column):
1820class Pseudocolumn(Column):
1821    pass
key: ClassVar[str] = 'pseudocolumn'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Hint(Expression):
1824class Hint(Expression):
1825    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key: ClassVar[str] = 'hint'
required_args: 't.ClassVar[set[str]]' = {'expressions'}
class JoinHint(Expression):
1828class JoinHint(Expression):
1829    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key: ClassVar[str] = 'joinhint'
required_args: 't.ClassVar[set[str]]' = {'expressions', 'this'}
class Identifier(Expression):
1832class Identifier(Expression):
1833    arg_types = {
1834        "this": True,
1835        "quoted": False,
1836        "global_": False,
1837        "temporary": False,
1838    }
1839    is_primitive = True
1840    _hash_raw_args = True
1841
1842    @property
1843    def quoted(self) -> bool:
1844        return bool(self.args.get("quoted"))
1845
1846    @property
1847    def output_name(self) -> str:
1848        return self.name
arg_types = {'this': True, 'quoted': False, 'global_': False, 'temporary': False}
is_primitive = True
quoted: bool
1842    @property
1843    def quoted(self) -> bool:
1844        return bool(self.args.get("quoted"))
output_name: str
1846    @property
1847    def output_name(self) -> str:
1848        return self.name

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key: ClassVar[str] = 'identifier'
required_args: 't.ClassVar[set[str]]' = {'this'}
class DynamicIdentifier(Expression, Func):
1854class DynamicIdentifier(Expression, Func):
1855    arg_types = {"this": True, "expressions": False}
1856
1857    @property
1858    def name(self) -> str:
1859        return self.this.name if self.this else ""
arg_types = {'this': True, 'expressions': False}
name: str
1857    @property
1858    def name(self) -> str:
1859        return self.this.name if self.this else ""
key: ClassVar[str] = 'dynamicidentifier'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Opclass(Expression):
1862class Opclass(Expression):
1863    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key: ClassVar[str] = 'opclass'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Star(Expression):
1866class Star(Expression):
1867    arg_types = {"except_": False, "replace": False, "rename": False, "ilike": False}
1868
1869    @property
1870    def name(self) -> str:
1871        return "*"
1872
1873    @property
1874    def output_name(self) -> str:
1875        return self.name
arg_types = {'except_': False, 'replace': False, 'rename': False, 'ilike': False}
name: str
1869    @property
1870    def name(self) -> str:
1871        return "*"
output_name: str
1873    @property
1874    def output_name(self) -> str:
1875        return self.name

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key: ClassVar[str] = 'star'
required_args: 't.ClassVar[set[str]]' = set()
class Parameter(Expression, Condition):
1878class Parameter(Expression, Condition):
1879    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key: ClassVar[str] = 'parameter'
required_args: 't.ClassVar[set[str]]' = {'this'}
class SessionParameter(Expression, Condition):
1882class SessionParameter(Expression, Condition):
1883    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key: ClassVar[str] = 'sessionparameter'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Placeholder(Expression, Condition):
1886class Placeholder(Expression, Condition):
1887    arg_types = {"this": False, "kind": False, "widget": False, "jdbc": False}
1888    _hash_raw_args = True
1889
1890    @property
1891    def name(self) -> str:
1892        return self.text("this") or "?"
arg_types = {'this': False, 'kind': False, 'widget': False, 'jdbc': False}
name: str
1890    @property
1891    def name(self) -> str:
1892        return self.text("this") or "?"
key: ClassVar[str] = 'placeholder'
required_args: 't.ClassVar[set[str]]' = set()
class Null(Expression, Condition):
1895class Null(Expression, Condition):
1896    arg_types = {}
1897
1898    @property
1899    def name(self) -> str:
1900        return "NULL"
1901
1902    def to_py(self) -> t.Literal[None]:
1903        return None
arg_types = {}
name: str
1898    @property
1899    def name(self) -> str:
1900        return "NULL"
def to_py(self) -> Literal[None]:
1902    def to_py(self) -> t.Literal[None]:
1903        return None

Returns a Python object equivalent of the SQL node.

key: ClassVar[str] = 'null'
required_args: 't.ClassVar[set[str]]' = set()
class Boolean(Expression, Condition):
1906class Boolean(Expression, Condition):
1907    is_primitive = True
1908
1909    def to_py(self) -> bool:
1910        return self.this
is_primitive = True
def to_py(self) -> bool:
1909    def to_py(self) -> bool:
1910        return self.this

Returns a Python object equivalent of the SQL node.

key: ClassVar[str] = 'boolean'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Dot(Expression, Binary):
1913class Dot(Expression, Binary):
1914    arg_types = {"this": True, "expression": True, "subcolumn_depth": False}
1915
1916    @property
1917    def is_star(self) -> bool:
1918        return self.expression.is_star
1919
1920    @property
1921    def name(self) -> str:
1922        return self.expression.name
1923
1924    @property
1925    def output_name(self) -> str:
1926        return self.name
1927
1928    @classmethod
1929    def build(cls, expressions: Sequence[Expr]) -> Dot:
1930        """Build a Dot object with a sequence of expressions."""
1931        if len(expressions) < 2:
1932            raise ValueError("Dot requires >= 2 expressions.")
1933
1934        return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))
1935
1936    @property
1937    def parts(self) -> list[Expr]:
1938        """Return the parts of a table / column in order catalog, db, table."""
1939        this, *parts = self.flatten()
1940
1941        parts.reverse()
1942
1943        for arg in COLUMN_PARTS:
1944            part = this.args.get(arg)
1945
1946            if isinstance(part, Expr):
1947                parts.append(part)
1948
1949        parts.reverse()
1950        return parts
arg_types = {'this': True, 'expression': True, 'subcolumn_depth': False}
is_star: bool
1916    @property
1917    def is_star(self) -> bool:
1918        return self.expression.is_star

Checks whether an expression is a star.

name: str
1920    @property
1921    def name(self) -> str:
1922        return self.expression.name
output_name: str
1924    @property
1925    def output_name(self) -> str:
1926        return self.name

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
@classmethod
def build( cls, expressions: Sequence[Expr]) -> Dot:
1928    @classmethod
1929    def build(cls, expressions: Sequence[Expr]) -> Dot:
1930        """Build a Dot object with a sequence of expressions."""
1931        if len(expressions) < 2:
1932            raise ValueError("Dot requires >= 2 expressions.")
1933
1934        return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))

Build a Dot object with a sequence of expressions.

parts: list[Expr]
1936    @property
1937    def parts(self) -> list[Expr]:
1938        """Return the parts of a table / column in order catalog, db, table."""
1939        this, *parts = self.flatten()
1940
1941        parts.reverse()
1942
1943        for arg in COLUMN_PARTS:
1944            part = this.args.get(arg)
1945
1946            if isinstance(part, Expr):
1947                parts.append(part)
1948
1949        parts.reverse()
1950        return parts

Return the parts of a table / column in order catalog, db, table.

key: ClassVar[str] = 'dot'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Kwarg(Expression, Binary):
1953class Kwarg(Expression, Binary):
1954    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

key: ClassVar[str] = 'kwarg'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Alias(Expression):
1957class Alias(Expression):
1958    arg_types = {"this": True, "alias": False}
1959
1960    @property
1961    def output_name(self) -> str:
1962        return self.alias
arg_types = {'this': True, 'alias': False}
output_name: str
1960    @property
1961    def output_name(self) -> str:
1962        return self.alias

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key: ClassVar[str] = 'alias'
required_args: 't.ClassVar[set[str]]' = {'this'}
class PivotAlias(Alias):
1965class PivotAlias(Alias):
1966    pass
key: ClassVar[str] = 'pivotalias'
required_args: 't.ClassVar[set[str]]' = {'this'}
class PivotAny(Expression):
1969class PivotAny(Expression):
1970    arg_types = {"this": False}
arg_types = {'this': False}
key: ClassVar[str] = 'pivotany'
required_args: 't.ClassVar[set[str]]' = set()
class Aliases(Expression):
1973class Aliases(Expression):
1974    arg_types = {"this": True, "expressions": True}
1975
1976    @property
1977    def aliases(self) -> list[Expr]:
1978        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases: list[Expr]
1976    @property
1977    def aliases(self) -> list[Expr]:
1978        return self.expressions
key: ClassVar[str] = 'aliases'
required_args: 't.ClassVar[set[str]]' = {'expressions', 'this'}
class Bracket(Expression, Condition):
1981class Bracket(Expression, Condition):
1982    # https://cloud.google.com/bigquery/docs/reference/standard-sql/operators#array_subscript_operator
1983    arg_types = {
1984        "this": True,
1985        "expressions": True,
1986        "offset": False,
1987        "safe": False,
1988        "returns_list_for_maps": False,
1989        "json_access": False,
1990    }
1991
1992    @property
1993    def output_name(self) -> str:
1994        if len(self.expressions) == 1:
1995            return self.expressions[0].output_name
1996
1997        return super().output_name
arg_types = {'this': True, 'expressions': True, 'offset': False, 'safe': False, 'returns_list_for_maps': False, 'json_access': False}
output_name: str
1992    @property
1993    def output_name(self) -> str:
1994        if len(self.expressions) == 1:
1995            return self.expressions[0].output_name
1996
1997        return super().output_name

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key: ClassVar[str] = 'bracket'
required_args: 't.ClassVar[set[str]]' = {'expressions', 'this'}
class ForIn(Expression):
2000class ForIn(Expression):
2001    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key: ClassVar[str] = 'forin'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class IgnoreNulls(Expression):
2004class IgnoreNulls(Expression):
2005    pass
key: ClassVar[str] = 'ignorenulls'
required_args: 't.ClassVar[set[str]]' = {'this'}
class RespectNulls(Expression):
2008class RespectNulls(Expression):
2009    pass
key: ClassVar[str] = 'respectnulls'
required_args: 't.ClassVar[set[str]]' = {'this'}
class HavingMax(Expression):
2012class HavingMax(Expression):
2013    arg_types = {"this": True, "expression": True, "max": True}
arg_types = {'this': True, 'expression': True, 'max': True}
key: ClassVar[str] = 'havingmax'
required_args: 't.ClassVar[set[str]]' = {'max', 'expression', 'this'}
class SafeFunc(Expression, Func):
2016class SafeFunc(Expression, Func):
2017    pass
key: ClassVar[str] = 'safefunc'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Typeof(Expression, Func):
2020class Typeof(Expression, Func):
2021    pass
key: ClassVar[str] = 'typeof'
required_args: 't.ClassVar[set[str]]' = {'this'}
class ParameterizedAgg(Expression, AggFunc):
2024class ParameterizedAgg(Expression, AggFunc):
2025    arg_types = {"this": True, "expressions": True, "params": True}
2026    _hash_raw_args = True
arg_types = {'this': True, 'expressions': True, 'params': True}
key: ClassVar[str] = 'parameterizedagg'
required_args: 't.ClassVar[set[str]]' = {'params', 'expressions', 'this'}
class Anonymous(Expression, Func):
2029class Anonymous(Expression, Func):
2030    arg_types = {"this": True, "expressions": False}
2031    is_var_len_args = True
2032
2033    @property
2034    def name(self) -> str:
2035        return self.this if isinstance(self.this, str) else self.this.name
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
name: str
2033    @property
2034    def name(self) -> str:
2035        return self.this if isinstance(self.this, str) else self.this.name
key: ClassVar[str] = 'anonymous'
required_args: 't.ClassVar[set[str]]' = {'this'}
class AnonymousAggFunc(Expression, AggFunc):
2038class AnonymousAggFunc(Expression, AggFunc):
2039    arg_types = {"this": True, "expressions": False}
2040    is_var_len_args = True
2041    _hash_raw_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key: ClassVar[str] = 'anonymousaggfunc'
required_args: 't.ClassVar[set[str]]' = {'this'}
class CombinedAggFunc(AnonymousAggFunc):
2044class CombinedAggFunc(AnonymousAggFunc):
2045    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key: ClassVar[str] = 'combinedaggfunc'
required_args: 't.ClassVar[set[str]]' = {'this'}
class CombinedParameterizedAgg(ParameterizedAgg):
2048class CombinedParameterizedAgg(ParameterizedAgg):
2049    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key: ClassVar[str] = 'combinedparameterizedagg'
required_args: 't.ClassVar[set[str]]' = {'params', 'expressions', 'this'}
class HashAgg(Expression, AggFunc):
2052class HashAgg(Expression, AggFunc):
2053    arg_types = {"this": True, "expressions": False}
2054    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key: ClassVar[str] = 'hashagg'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Hll(Expression, AggFunc):
2057class Hll(Expression, AggFunc):
2058    arg_types = {"this": True, "expressions": False}
2059    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key: ClassVar[str] = 'hll'
required_args: 't.ClassVar[set[str]]' = {'this'}
class ApproxDistinct(Expression, AggFunc):
2062class ApproxDistinct(Expression, AggFunc):
2063    arg_types = {"this": True, "accuracy": False}
2064    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key: ClassVar[str] = 'approxdistinct'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Slice(Expression):
2067class Slice(Expression):
2068    arg_types = {"this": False, "expression": False, "step": False}
arg_types = {'this': False, 'expression': False, 'step': False}
key: ClassVar[str] = 'slice'
required_args: 't.ClassVar[set[str]]' = set()
@trait
class TimeUnit(Expr):
2071@trait
2072class TimeUnit(Expr):
2073    """Automatically converts unit arg into a var."""
2074
2075    UNABBREVIATED_UNIT_NAME: t.ClassVar[dict[str, str]] = {
2076        "D": "DAY",
2077        "H": "HOUR",
2078        "M": "MINUTE",
2079        "MS": "MILLISECOND",
2080        "NS": "NANOSECOND",
2081        "Q": "QUARTER",
2082        "S": "SECOND",
2083        "US": "MICROSECOND",
2084        "W": "WEEK",
2085        "Y": "YEAR",
2086    }
2087
2088    VAR_LIKE: t.ClassVar[tuple[Type[Expr], ...]] = (Column, Literal, Var)
2089
2090    def __init__(self, **args: object) -> None:
2091        super().__init__(**args)
2092
2093        unit = self.args.get("unit")
2094        if (
2095            unit
2096            and type(unit) in TimeUnit.VAR_LIKE
2097            and not (isinstance(unit, Column) and len(unit.parts) != 1)
2098        ):
2099            unit = Var(this=(self.UNABBREVIATED_UNIT_NAME.get(unit.name) or unit.name).upper())
2100            self.args["unit"] = unit
2101            self._set_parent("unit", unit)
2102        elif type(unit).__name__ == "Week":
2103            unit.set("this", Var(this=unit.this.name.upper()))  # type: ignore[union-attr]
2104
2105    @property
2106    def unit(self) -> Expr | None:
2107        return self.args.get("unit")

Automatically converts unit arg into a var.

TimeUnit(**args: object)
2090    def __init__(self, **args: object) -> None:
2091        super().__init__(**args)
2092
2093        unit = self.args.get("unit")
2094        if (
2095            unit
2096            and type(unit) in TimeUnit.VAR_LIKE
2097            and not (isinstance(unit, Column) and len(unit.parts) != 1)
2098        ):
2099            unit = Var(this=(self.UNABBREVIATED_UNIT_NAME.get(unit.name) or unit.name).upper())
2100            self.args["unit"] = unit
2101            self._set_parent("unit", unit)
2102        elif type(unit).__name__ == "Week":
2103            unit.set("this", Var(this=unit.this.name.upper()))  # type: ignore[union-attr]
UNABBREVIATED_UNIT_NAME: ClassVar[dict[str, str]] = {'D': 'DAY', 'H': 'HOUR', 'M': 'MINUTE', 'MS': 'MILLISECOND', 'NS': 'NANOSECOND', 'Q': 'QUARTER', 'S': 'SECOND', 'US': 'MICROSECOND', 'W': 'WEEK', 'Y': 'YEAR'}
VAR_LIKE: ClassVar[tuple[type[Expr], ...]] = (<class 'Column'>, <class 'Literal'>, <class 'Var'>)
unit: Expr | None
2105    @property
2106    def unit(self) -> Expr | None:
2107        return self.args.get("unit")
key: ClassVar[str] = 'timeunit'
required_args: 't.ClassVar[set[str]]' = {'this'}
@trait
class IntervalOp(TimeUnit):
2116@trait
2117class IntervalOp(TimeUnit):
2118    def interval(self) -> Interval:
2119        from sqlglot.expressions.datatypes import Interval
2120
2121        expr = self.expression
2122        return Interval(
2123            this=expr.copy() if expr is not None else None,
2124            unit=self.unit.copy() if self.unit else None,
2125        )
def interval(self) -> sqlglot.expressions.datatypes.Interval:
2118    def interval(self) -> Interval:
2119        from sqlglot.expressions.datatypes import Interval
2120
2121        expr = self.expression
2122        return Interval(
2123            this=expr.copy() if expr is not None else None,
2124            unit=self.unit.copy() if self.unit else None,
2125        )
key: ClassVar[str] = 'intervalop'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Filter(Expression):
2128class Filter(Expression):
2129    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key: ClassVar[str] = 'filter'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Per(Expression):
2132class Per(Expression):
2133    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key: ClassVar[str] = 'per'
required_args: 't.ClassVar[set[str]]' = {'expressions', 'this'}
class Check(Expression):
2136class Check(Expression):
2137    pass
key: ClassVar[str] = 'check'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Ordered(Expression):
2140class Ordered(Expression):
2141    arg_types = {"this": True, "desc": False, "nulls_first": True, "with_fill": False}
2142
2143    @property
2144    def name(self) -> str:
2145        return self.this.name
arg_types = {'this': True, 'desc': False, 'nulls_first': True, 'with_fill': False}
name: str
2143    @property
2144    def name(self) -> str:
2145        return self.this.name
key: ClassVar[str] = 'ordered'
required_args: 't.ClassVar[set[str]]' = {'nulls_first', 'this'}
class Add(Expression, Binary):
2148class Add(Expression, Binary):
2149    pass
key: ClassVar[str] = 'add'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class BitwiseAnd(Expression, Binary):
2152class BitwiseAnd(Expression, Binary):
2153    arg_types = {"this": True, "expression": True, "padside": False}
arg_types = {'this': True, 'expression': True, 'padside': False}
key: ClassVar[str] = 'bitwiseand'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class BitwiseLeftShift(Expression, Binary):
2156class BitwiseLeftShift(Expression, Binary):
2157    arg_types = {"this": True, "expression": True, "requires_int128": False}
arg_types = {'this': True, 'expression': True, 'requires_int128': False}
key: ClassVar[str] = 'bitwiseleftshift'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class BitwiseOr(Expression, Binary):
2160class BitwiseOr(Expression, Binary):
2161    arg_types = {"this": True, "expression": True, "padside": False}
arg_types = {'this': True, 'expression': True, 'padside': False}
key: ClassVar[str] = 'bitwiseor'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class BitwiseRightShift(Expression, Binary):
2164class BitwiseRightShift(Expression, Binary):
2165    arg_types = {"this": True, "expression": True, "requires_int128": False}
arg_types = {'this': True, 'expression': True, 'requires_int128': False}
key: ClassVar[str] = 'bitwiserightshift'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class BitwiseXor(Expression, Binary):
2168class BitwiseXor(Expression, Binary):
2169    arg_types = {"this": True, "expression": True, "padside": False}
arg_types = {'this': True, 'expression': True, 'padside': False}
key: ClassVar[str] = 'bitwisexor'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Div(Expression, Binary):
2172class Div(Expression, Binary):
2173    arg_types = {"this": True, "expression": True, "typed": False, "safe": False}
arg_types = {'this': True, 'expression': True, 'typed': False, 'safe': False}
key: ClassVar[str] = 'div'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Overlaps(Expression, Binary, Predicate):
2176class Overlaps(Expression, Binary, Predicate):
2177    pass
key: ClassVar[str] = 'overlaps'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class ExtendsLeft(Expression, Binary, Predicate):
2180class ExtendsLeft(Expression, Binary, Predicate):
2181    pass
key: ClassVar[str] = 'extendsleft'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class ExtendsRight(Expression, Binary, Predicate):
2184class ExtendsRight(Expression, Binary, Predicate):
2185    pass
key: ClassVar[str] = 'extendsright'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class DPipe(Expression, Binary):
2188class DPipe(Expression, Binary):
2189    arg_types = {"this": True, "expression": True, "safe": False}
arg_types = {'this': True, 'expression': True, 'safe': False}
key: ClassVar[str] = 'dpipe'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class EQ(Expression, Binary, Predicate):
2192class EQ(Expression, Binary, Predicate):
2193    pass
key: ClassVar[str] = 'eq'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class NullSafeEQ(Expression, Binary, Predicate):
2196class NullSafeEQ(Expression, Binary, Predicate):
2197    pass
key: ClassVar[str] = 'nullsafeeq'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class NullSafeNEQ(Expression, Binary, Predicate):
2200class NullSafeNEQ(Expression, Binary, Predicate):
2201    pass
key: ClassVar[str] = 'nullsafeneq'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class PropertyEQ(Expression, Binary):
2204class PropertyEQ(Expression, Binary):
2205    pass
key: ClassVar[str] = 'propertyeq'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Distance(Expression, Binary):
2208class Distance(Expression, Binary):
2209    pass
key: ClassVar[str] = 'distance'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class DistanceNd(Expression, Binary):
2212class DistanceNd(Expression, Binary):
2213    pass
key: ClassVar[str] = 'distancend'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Escape(Expression, Binary):
2216class Escape(Expression, Binary):
2217    pass
key: ClassVar[str] = 'escape'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Glob(Expression, Binary, Predicate):
2220class Glob(Expression, Binary, Predicate):
2221    pass
key: ClassVar[str] = 'glob'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class GT(Expression, Binary, Predicate):
2224class GT(Expression, Binary, Predicate):
2225    pass
key: ClassVar[str] = 'gt'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class GTE(Expression, Binary, Predicate):
2228class GTE(Expression, Binary, Predicate):
2229    pass
key: ClassVar[str] = 'gte'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class ILike(Expression, Binary, Predicate):
2232class ILike(Expression, Binary, Predicate):
2233    arg_types = {"this": True, "expression": True, "negate": False}
arg_types = {'this': True, 'expression': True, 'negate': False}
key: ClassVar[str] = 'ilike'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class IntDiv(Expression, Binary):
2236class IntDiv(Expression, Binary):
2237    pass
key: ClassVar[str] = 'intdiv'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Is(Expression, Binary, Predicate):
2240class Is(Expression, Binary, Predicate):
2241    arg_types = {"this": True, "expression": True, "negate": False}
arg_types = {'this': True, 'expression': True, 'negate': False}
key: ClassVar[str] = 'is'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Like(Expression, Binary, Predicate):
2244class Like(Expression, Binary, Predicate):
2245    arg_types = {"this": True, "expression": True, "negate": False}
arg_types = {'this': True, 'expression': True, 'negate': False}
key: ClassVar[str] = 'like'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Match(Expression, Binary, Predicate):
2248class Match(Expression, Binary, Predicate):
2249    arg_types = {"this": True, "expression": True, "kind": False, "analyzer": False}
arg_types = {'this': True, 'expression': True, 'kind': False, 'analyzer': False}
key: ClassVar[str] = 'match'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class LT(Expression, Binary, Predicate):
2252class LT(Expression, Binary, Predicate):
2253    pass
key: ClassVar[str] = 'lt'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class LTE(Expression, Binary, Predicate):
2256class LTE(Expression, Binary, Predicate):
2257    pass
key: ClassVar[str] = 'lte'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Mod(Expression, Binary):
2260class Mod(Expression, Binary):
2261    arg_types = {"this": True, "expression": True, "safe": False}
arg_types = {'this': True, 'expression': True, 'safe': False}
key: ClassVar[str] = 'mod'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Mul(Expression, Binary):
2264class Mul(Expression, Binary):
2265    pass
key: ClassVar[str] = 'mul'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class NEQ(Expression, Binary, Predicate):
2268class NEQ(Expression, Binary, Predicate):
2269    pass
key: ClassVar[str] = 'neq'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class NestedJSONSelect(Expression, Binary):
2272class NestedJSONSelect(Expression, Binary):
2273    pass
key: ClassVar[str] = 'nestedjsonselect'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Operator(Expression, Binary):
2276class Operator(Expression, Binary):
2277    arg_types = {"this": True, "operator": True, "expression": True}
arg_types = {'this': True, 'operator': True, 'expression': True}
key: ClassVar[str] = 'operator'
required_args: 't.ClassVar[set[str]]' = {'operator', 'expression', 'this'}
class SimilarTo(Expression, Binary, Predicate):
2280class SimilarTo(Expression, Binary, Predicate):
2281    pass
key: ClassVar[str] = 'similarto'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Sub(Expression, Binary):
2284class Sub(Expression, Binary):
2285    pass
key: ClassVar[str] = 'sub'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Adjacent(Expression, Binary, Predicate):
2288class Adjacent(Expression, Binary, Predicate):
2289    pass
key: ClassVar[str] = 'adjacent'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Unary(Expression, Condition):
2292class Unary(Expression, Condition):
2293    pass
key: ClassVar[str] = 'unary'
required_args: 't.ClassVar[set[str]]' = {'this'}
class BitwiseNot(Unary):
2296class BitwiseNot(Unary):
2297    pass
key: ClassVar[str] = 'bitwisenot'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Not(Unary):
2300class Not(Unary):
2301    pass
key: ClassVar[str] = 'not'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Paren(Unary):
2304class Paren(Unary):
2305    @property
2306    def output_name(self) -> str:
2307        return self.this.name
output_name: str
2305    @property
2306    def output_name(self) -> str:
2307        return self.this.name

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key: ClassVar[str] = 'paren'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Pos(Unary):
2310class Pos(Unary):
2311    pass
key: ClassVar[str] = 'pos'
required_args: 't.ClassVar[set[str]]' = {'this'}
class Neg(Unary):
2314class Neg(Unary):
2315    def to_py(self) -> int | Decimal:
2316        if self.is_number:
2317            return self.this.to_py() * -1
2318        return super().to_py()
def to_py(self) -> int | decimal.Decimal:
2315    def to_py(self) -> int | Decimal:
2316        if self.is_number:
2317            return self.this.to_py() * -1
2318        return super().to_py()

Returns a Python object equivalent of the SQL node.

key: ClassVar[str] = 'neg'
required_args: 't.ClassVar[set[str]]' = {'this'}
class AtIndex(Expression):
2321class AtIndex(Expression):
2322    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key: ClassVar[str] = 'atindex'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class AtTimeZone(Expression):
2325class AtTimeZone(Expression):
2326    # session_zone: a zoneless operand is read in the session time zone (e.g. Presto, Trino)
2327    arg_types = {"this": True, "zone": True, "session_zone": False}
arg_types = {'this': True, 'zone': True, 'session_zone': False}
key: ClassVar[str] = 'attimezone'
required_args: 't.ClassVar[set[str]]' = {'zone', 'this'}
class FromTimeZone(Expression):
2330class FromTimeZone(Expression):
2331    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key: ClassVar[str] = 'fromtimezone'
required_args: 't.ClassVar[set[str]]' = {'zone', 'this'}
class FormatPhrase(Expression):
2334class FormatPhrase(Expression):
2335    """Format override for a column in Teradata.
2336    Can be expanded to additional dialects as needed
2337
2338    https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Types-and-Literals/Data-Type-Formats-and-Format-Phrases/FORMAT
2339    """
2340
2341    arg_types = {"this": True, "format": True}
2342
2343    @property
2344    def name(self) -> str:
2345        return self.this.name
2346
2347    @property
2348    def output_name(self) -> str:
2349        return self.this.output_name

Format override for a column in Teradata. Can be expanded to additional dialects as needed

https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Types-and-Literals/Data-Type-Formats-and-Format-Phrases/FORMAT

arg_types = {'this': True, 'format': True}
name: str
2343    @property
2344    def name(self) -> str:
2345        return self.this.name
output_name: str
2347    @property
2348    def output_name(self) -> str:
2349        return self.this.output_name

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key: ClassVar[str] = 'formatphrase'
required_args: 't.ClassVar[set[str]]' = {'format', 'this'}
class TeradataConversion(Expression):
2352class TeradataConversion(Expression):
2353    """A postfix type conversion with Teradata-specific conversion or formatting semantics."""
2354
2355    arg_types = {"this": True, "to": True, "format": False}
2356
2357    @property
2358    def name(self) -> str:
2359        return self.this.name
2360
2361    @property
2362    def output_name(self) -> str:
2363        return self.this.output_name

A postfix type conversion with Teradata-specific conversion or formatting semantics.

arg_types = {'this': True, 'to': True, 'format': False}
name: str
2357    @property
2358    def name(self) -> str:
2359        return self.this.name
output_name: str
2361    @property
2362    def output_name(self) -> str:
2363        return self.this.output_name

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key: ClassVar[str] = 'teradataconversion'
required_args: 't.ClassVar[set[str]]' = {'to', 'this'}
class TeradataTitle(Expression):
2366class TeradataTitle(Expression):
2367    """A Teradata TITLE display heading, which does not rename the expression."""
2368
2369    arg_types = {"this": True, "title": True}
2370
2371    @property
2372    def name(self) -> str:
2373        return self.this.name
2374
2375    @property
2376    def output_name(self) -> str:
2377        return self.this.output_name

A Teradata TITLE display heading, which does not rename the expression.

arg_types = {'this': True, 'title': True}
name: str
2371    @property
2372    def name(self) -> str:
2373        return self.this.name
output_name: str
2375    @property
2376    def output_name(self) -> str:
2377        return self.this.output_name

Name of the output column if this expression is a selection.

If the Expr has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key: ClassVar[str] = 'teradatatitle'
required_args: 't.ClassVar[set[str]]' = {'title', 'this'}
class TeradataNamed(Alias):
2380class TeradataNamed(Alias):
2381    """A Teradata NAMED alias on a subexpression; projections use ordinary Alias."""
2382
2383    arg_types = {"this": True, "alias": True}

A Teradata NAMED alias on a subexpression; projections use ordinary Alias.

arg_types = {'this': True, 'alias': True}
key: ClassVar[str] = 'teradatanamed'
required_args: 't.ClassVar[set[str]]' = {'alias', 'this'}
class Between(Expression, Predicate):
2386class Between(Expression, Predicate):
2387    arg_types = {"this": True, "low": True, "high": True, "symmetric": False}
arg_types = {'this': True, 'low': True, 'high': True, 'symmetric': False}
key: ClassVar[str] = 'between'
required_args: 't.ClassVar[set[str]]' = {'low', 'high', 'this'}
class Distinct(Expression):
2390class Distinct(Expression):
2391    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key: ClassVar[str] = 'distinct'
required_args: 't.ClassVar[set[str]]' = set()
class In(Expression, Predicate):
2394class In(Expression, Predicate):
2395    arg_types = {
2396        "this": True,
2397        "expressions": False,
2398        "query": False,
2399        "unnest": False,
2400        "field": False,
2401        "is_global": False,
2402    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key: ClassVar[str] = 'in'
required_args: 't.ClassVar[set[str]]' = {'this'}
class And(Expression, Connector, Func):
2405class And(Expression, Connector, Func):
2406    pass
key: ClassVar[str] = 'and'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Or(Expression, Connector, Func):
2409class Or(Expression, Connector, Func):
2410    pass
key: ClassVar[str] = 'or'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Xor(Expression, Connector, Func):
2413class Xor(Expression, Connector, Func):
2414    arg_types = {"this": True, "expression": True, "round_input": False}
arg_types = {'this': True, 'expression': True, 'round_input': False}
key: ClassVar[str] = 'xor'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class Pow(Expression, Binary, Func):
2417class Pow(Expression, Binary, Func):
2418    _sql_names = ["POWER", "POW"]
key: ClassVar[str] = 'pow'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
class RegexpLike(Expression, Binary, Predicate, Func):
2421class RegexpLike(Expression, Binary, Predicate, Func):
2422    arg_types = {"this": True, "expression": True, "flag": False, "full_match": False}
arg_types = {'this': True, 'expression': True, 'flag': False, 'full_match': False}
key: ClassVar[str] = 'regexplike'
required_args: 't.ClassVar[set[str]]' = {'expression', 'this'}
def not_( expression: Union[int, str, Expr], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Not:
2425def not_(
2426    expression: ExpOrStr,
2427    dialect: DialectType = None,
2428    copy: bool = True,
2429    **opts: Unpack[ParserNoDialectArgs],
2430) -> Not:
2431    """
2432    Wrap a condition with a NOT operator.
2433
2434    Example:
2435        >>> not_("this_suit='black'").sql()
2436        "NOT this_suit = 'black'"
2437
2438    Args:
2439        expression: the SQL code string to parse.
2440            If an Expr instance is passed, this is used as-is.
2441        dialect: the dialect used to parse the input expression.
2442        copy: whether to copy the expression or not.
2443        **opts: other options to use to parse the input expressions.
2444
2445    Returns:
2446        The new condition.
2447    """
2448    this = condition(
2449        expression,
2450        dialect=dialect,
2451        copy=copy,
2452        **opts,
2453    )
2454    return Not(this=_wrap(this, Connector))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression: the SQL code string to parse. If an Expr instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the expression or not.
  • **opts: other options to use to parse the input expressions.
Returns:

The new condition.

def convert(value: Any, copy: bool = False) -> Expr:
2463def convert(value: t.Any, copy: bool = False) -> Expr:
2464    """Convert a python value into an expression object.
2465
2466    Raises an error if a conversion is not possible.
2467
2468    Args:
2469        value: A python object.
2470        copy: Whether to copy `value` (only applies to Exprs and collections).
2471
2472    Returns:
2473        The equivalent expression object.
2474    """
2475    if isinstance(value, Expr):
2476        return maybe_copy(value, copy)
2477    if isinstance(value, str):
2478        return Literal.string(value)
2479    if isinstance(value, bool):
2480        return Boolean(this=value)
2481    if value is None or (isinstance(value, float) and math.isnan(value)):
2482        return Null()
2483    if isinstance(value, numbers.Number):
2484        return Literal.number(value)
2485    if isinstance(value, bytes):
2486        from sqlglot.expressions.query import HexString as _HexString
2487
2488        return _HexString(this=value.hex())
2489    if isinstance(value, datetime.datetime):
2490        datetime_literal = Literal.string(value.isoformat(sep=" "))
2491
2492        tz = None
2493        if value.tzinfo:
2494            # this works for zoneinfo.ZoneInfo, pytz.timezone and datetime.datetime.utc to return IANA timezone names like "America/Los_Angeles"
2495            # instead of abbreviations like "PDT". This is for consistency with other timezone handling functions in SQLGlot
2496            tz = Literal.string(str(value.tzinfo))
2497
2498        from sqlglot.expressions.temporal import TimeStrToTime as _TimeStrToTime
2499
2500        return _TimeStrToTime(this=datetime_literal, zone=tz)
2501    if isinstance(value, datetime.date):
2502        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
2503        from sqlglot.expressions.temporal import DateStrToDate as _DateStrToDate
2504
2505        return _DateStrToDate(this=date_literal)
2506    if isinstance(value, datetime.time):
2507        time_literal = Literal.string(value.isoformat())
2508        from sqlglot.expressions.temporal import TsOrDsToTime as _TsOrDsToTime
2509
2510        return _TsOrDsToTime(this=time_literal)
2511    if isinstance(value, tuple):
2512        if hasattr(value, "_fields"):
2513            from sqlglot.expressions.array import Struct as _Struct
2514
2515            return _Struct(
2516                expressions=[
2517                    PropertyEQ(
2518                        this=to_identifier(k), expression=convert(getattr(value, k), copy=copy)
2519                    )
2520                    for k in value._fields
2521                ]
2522            )
2523        from sqlglot.expressions.query import Tuple as _Tuple
2524
2525        return _Tuple(expressions=[convert(v, copy=copy) for v in value])
2526    if isinstance(value, list):
2527        from sqlglot.expressions.array import Array as _Array
2528
2529        return _Array(expressions=[convert(v, copy=copy) for v in value])
2530    if isinstance(value, dict):
2531        from sqlglot.expressions.array import Array as _Array
2532        from sqlglot.expressions.array import Map as _Map
2533
2534        return _Map(
2535            keys=_Array(expressions=[convert(k, copy=copy) for k in value]),
2536            values=_Array(expressions=[convert(v, copy=copy) for v in value.values()]),
2537        )
2538    if hasattr(value, "__dict__"):
2539        from sqlglot.expressions.array import Struct as _Struct
2540
2541        return _Struct(
2542            expressions=[
2543                PropertyEQ(this=to_identifier(k), expression=convert(v, copy=copy))
2544                for k, v in value.__dict__.items()
2545            ]
2546        )
2547    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value: A python object.
  • copy: Whether to copy value (only applies to Exprs and collections).
Returns:

The equivalent expression object.

QUERY_MODIFIERS = {'laterals': False, 'joins': False, 'connect': False, 'pivots': False, 'prewhere': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False, 'options': False, 'for_': False}
TIMESTAMP_PARTS = {'year': False, 'month': False, 'day': False, 'hour': False, 'min': False, 'sec': False, 'nano': False}
def maybe_parse( sql_or_expression: Union[int, str, Expr], *, into: Union[type[Expr], Collection[type[Expr]], NoneType] = None, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, prefix: str | None = None, copy: bool = False, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Expr:
2611def maybe_parse(
2612    sql_or_expression: ExpOrStr,
2613    *,
2614    into: IntoType | None = None,
2615    dialect: DialectType = None,
2616    prefix: str | None = None,
2617    copy: bool = False,
2618    **opts: Unpack[ParserNoDialectArgs],
2619) -> Expr:
2620    """Gracefully handle a possible string or expression.
2621
2622    Example:
2623        >>> maybe_parse("1")
2624        Literal(this=1, is_string=False)
2625        >>> maybe_parse(to_identifier("x"))
2626        Identifier(this=x, quoted=False)
2627
2628    Args:
2629        sql_or_expression: the SQL code string or an expression
2630        into: the SQLGlot Expr to parse into
2631        dialect: the dialect used to parse the input expressions (in the case that an
2632            input expression is a SQL string).
2633        prefix: a string to prefix the sql with before it gets parsed
2634            (automatically includes a space)
2635        copy: whether to copy the expression.
2636        **opts: other options to use to parse the input expressions (again, in the case
2637            that an input expression is a SQL string).
2638
2639    Returns:
2640        Expr: the parsed or given expression.
2641    """
2642    if isinstance(sql_or_expression, Expr):
2643        if copy:
2644            return sql_or_expression.copy()
2645        return sql_or_expression
2646
2647    if sql_or_expression is None:
2648        raise ParseError("SQL cannot be None")
2649
2650    import sqlglot
2651
2652    sql = str(sql_or_expression)
2653    if prefix:
2654        sql = f"{prefix} {sql}"
2655
2656    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
Literal(this=1, is_string=False)
>>> maybe_parse(to_identifier("x"))
Identifier(this=x, quoted=False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expr to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expr: the parsed or given expression.

def maybe_copy(instance, copy=True):
2667def maybe_copy(instance, copy=True):
2668    return instance.copy() if copy and instance else instance
SAFE_IDENTIFIER_RE: Pattern[str] = re.compile('^[_a-zA-Z][\\w]*$')
def to_identifier(name, quoted=None, copy=True):
2908def to_identifier(name, quoted=None, copy=True):
2909    """Builds an identifier.
2910
2911    Args:
2912        name: The name to turn into an identifier.
2913        quoted: Whether to force quote the identifier.
2914        copy: Whether to copy name if it's an Identifier.
2915
2916    Returns:
2917        The identifier ast node.
2918    """
2919
2920    if name is None:
2921        return None
2922
2923    if isinstance(name, Identifier):
2924        identifier = maybe_copy(name, copy)
2925    elif isinstance(name, str):
2926        identifier = Identifier(
2927            this=name,
2928            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
2929        )
2930    else:
2931        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
2932    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether to force quote the identifier.
  • copy: Whether to copy name if it's an Identifier.
Returns:

The identifier ast node.

def condition( expression: Union[int, str, Expr], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Expr:
2935def condition(
2936    expression: ExpOrStr,
2937    dialect: DialectType = None,
2938    copy: bool = True,
2939    **opts: Unpack[ParserNoDialectArgs],
2940) -> Expr:
2941    """
2942    Initialize a logical condition expression.
2943
2944    Example:
2945        >>> condition("x=1").sql()
2946        'x = 1'
2947
2948        This is helpful for composing larger logical syntax trees:
2949        >>> where = condition("x=1")
2950        >>> where = where.and_("y=1")
2951        >>> where.sql()
2952        'x = 1 AND y = 1'
2953
2954    Args:
2955        *expression: the SQL code string to parse.
2956            If an Expr instance is passed, this is used as-is.
2957        dialect: the dialect used to parse the input expression (in the case that the
2958            input expression is a SQL string).
2959        copy: Whether to copy `expression` (only applies to expressions).
2960        **opts: other options to use to parse the input expressions (again, in the case
2961            that the input expression is a SQL string).
2962
2963    Returns:
2964        The new Condition instance
2965    """
2966    return maybe_parse(
2967        expression,
2968        into=Condition,
2969        dialect=dialect,
2970        copy=copy,
2971        **opts,
2972    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> where.sql()
'x = 1 AND y = 1'
Arguments:
  • *expression: the SQL code string to parse. If an Expr instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • copy: Whether to copy expression (only applies to expressions).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

The new Condition instance

def and_( *expressions: Union[int, str, Expr, NoneType], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, wrap: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Condition:
2975def and_(
2976    *expressions: ExpOrStr | None,
2977    dialect: DialectType = None,
2978    copy: bool = True,
2979    wrap: bool = True,
2980    **opts: Unpack[ParserNoDialectArgs],
2981) -> Condition:
2982    """
2983    Combine multiple conditions with an AND logical operator.
2984
2985    Example:
2986        >>> and_("x=1", and_("y=1", "z=1")).sql()
2987        'x = 1 AND (y = 1 AND z = 1)'
2988
2989    Args:
2990        *expressions: the SQL code strings to parse.
2991            If an Expr instance is passed, this is used as-is.
2992        dialect: the dialect used to parse the input expression.
2993        copy: whether to copy `expressions` (only applies to Exprs).
2994        wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
2995            precedence issues, but can be turned off when the produced AST is too deep and
2996            causes recursion-related issues.
2997        **opts: other options to use to parse the input expressions.
2998
2999    Returns:
3000        The new condition
3001    """
3002    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, wrap=wrap, **opts))

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expr instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy expressions (only applies to Exprs).
  • wrap: whether to wrap the operands in Parens. This is true by default to avoid precedence issues, but can be turned off when the produced AST is too deep and causes recursion-related issues.
  • **opts: other options to use to parse the input expressions.
Returns:

The new condition

def or_( *expressions: Union[int, str, Expr, NoneType], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, wrap: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Condition:
3005def or_(
3006    *expressions: ExpOrStr | None,
3007    dialect: DialectType = None,
3008    copy: bool = True,
3009    wrap: bool = True,
3010    **opts: Unpack[ParserNoDialectArgs],
3011) -> Condition:
3012    """
3013    Combine multiple conditions with an OR logical operator.
3014
3015    Example:
3016        >>> or_("x=1", or_("y=1", "z=1")).sql()
3017        'x = 1 OR (y = 1 OR z = 1)'
3018
3019    Args:
3020        *expressions: the SQL code strings to parse.
3021            If an Expr instance is passed, this is used as-is.
3022        dialect: the dialect used to parse the input expression.
3023        copy: whether to copy `expressions` (only applies to Exprs).
3024        wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
3025            precedence issues, but can be turned off when the produced AST is too deep and
3026            causes recursion-related issues.
3027        **opts: other options to use to parse the input expressions.
3028
3029    Returns:
3030        The new condition
3031    """
3032    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, wrap=wrap, **opts))

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expr instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy expressions (only applies to Exprs).
  • wrap: whether to wrap the operands in Parens. This is true by default to avoid precedence issues, but can be turned off when the produced AST is too deep and causes recursion-related issues.
  • **opts: other options to use to parse the input expressions.
Returns:

The new condition

def xor( *expressions: Union[int, str, Expr, NoneType], dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, wrap: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Condition:
3035def xor(
3036    *expressions: ExpOrStr | None,
3037    dialect: DialectType = None,
3038    copy: bool = True,
3039    wrap: bool = True,
3040    **opts: Unpack[ParserNoDialectArgs],
3041) -> Condition:
3042    """
3043    Combine multiple conditions with an XOR logical operator.
3044
3045    Example:
3046        >>> xor("x=1", xor("y=1", "z=1")).sql()
3047        'x = 1 XOR (y = 1 XOR z = 1)'
3048
3049    Args:
3050        *expressions: the SQL code strings to parse.
3051            If an Expr instance is passed, this is used as-is.
3052        dialect: the dialect used to parse the input expression.
3053        copy: whether to copy `expressions` (only applies to Exprs).
3054        wrap: whether to wrap the operands in `Paren`s. This is true by default to avoid
3055            precedence issues, but can be turned off when the produced AST is too deep and
3056            causes recursion-related issues.
3057        **opts: other options to use to parse the input expressions.
3058
3059    Returns:
3060        The new condition
3061    """
3062    return t.cast(Condition, _combine(expressions, Xor, dialect, copy=copy, wrap=wrap, **opts))

Combine multiple conditions with an XOR logical operator.

Example:
>>> xor("x=1", xor("y=1", "z=1")).sql()
'x = 1 XOR (y = 1 XOR z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expr instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy expressions (only applies to Exprs).
  • wrap: whether to wrap the operands in Parens. This is true by default to avoid precedence issues, but can be turned off when the produced AST is too deep and causes recursion-related issues.
  • **opts: other options to use to parse the input expressions.
Returns:

The new condition

def paren( expression: Union[int, str, Expr], copy: bool = True) -> Paren:
3065def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
3066    """
3067    Wrap an expression in parentheses.
3068
3069    Example:
3070        >>> paren("5 + 3").sql()
3071        '(5 + 3)'
3072
3073    Args:
3074        expression: the SQL code string to parse.
3075            If an Expr instance is passed, this is used as-is.
3076        copy: whether to copy the expression or not.
3077
3078    Returns:
3079        The wrapped expression.
3080    """
3081    return Paren(this=maybe_parse(expression, copy=copy))

Wrap an expression in parentheses.

Example:
>>> paren("5 + 3").sql()
'(5 + 3)'
Arguments:
  • expression: the SQL code string to parse. If an Expr instance is passed, this is used as-is.
  • copy: whether to copy the expression or not.
Returns:

The wrapped expression.

def alias_( expression: Union[int, str, Expr], alias: str | Identifier | None, table: bool | Sequence[str | Identifier] = False, quoted: bool | None = None, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None, copy: bool = True, **opts: typing_extensions.Unpack[sqlglot._typing.ParserNoDialectArgs]) -> Expr:
3084def alias_(
3085    expression: ExpOrStr,
3086    alias: str | Identifier | None,
3087    table: bool | Sequence[str | Identifier] = False,
3088    quoted: bool | None = None,
3089    dialect: DialectType = None,
3090    copy: bool = True,
3091    **opts: Unpack[ParserNoDialectArgs],
3092) -> Expr:
3093    """Create an Alias expression.
3094
3095    Example:
3096        >>> alias_('foo', 'bar').sql()
3097        'foo AS bar'
3098
3099        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
3100        '(SELECT 1, 2) AS bar(a, b)'
3101
3102    Args:
3103        expression: the SQL code strings to parse.
3104            If an Expr instance is passed, this is used as-is.
3105        alias: the alias name to use. If the name has
3106            special characters it is quoted.
3107        table: Whether to create a table alias, can also be a list of columns.
3108        quoted: whether to quote the alias
3109        dialect: the dialect used to parse the input expression.
3110        copy: Whether to copy the expression.
3111        **opts: other options to use to parse the input expressions.
3112
3113    Returns:
3114        Alias: the aliased expression
3115    """
3116    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
3117    alias = to_identifier(alias, quoted=quoted)
3118
3119    if table:
3120        from sqlglot.expressions.query import TableAlias as _TableAlias
3121
3122        table_alias = _TableAlias(this=alias)
3123        exp.set("alias", table_alias)
3124
3125        if not isinstance(table, bool):
3126            for column in table:
3127                table_alias.append("columns", to_identifier(column, quoted=quoted))
3128
3129        return exp
3130
3131    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
3132    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
3133    # for the complete Window expression.
3134    #
3135    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
3136
3137    if "alias" in exp.arg_types and type(exp).__name__ != "Window":
3138        exp.set("alias", alias)
3139        return exp
3140    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expr instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether to create a table alias, can also be a list of columns.
  • quoted: whether to quote the alias
  • dialect: the dialect used to parse the input expression.
  • copy: Whether to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def column( col, table=None, db=None, catalog=None, *, fields=None, quoted=None, copy: bool = True):
3171def column(
3172    col,
3173    table=None,
3174    db=None,
3175    catalog=None,
3176    *,
3177    fields=None,
3178    quoted=None,
3179    copy: bool = True,
3180):
3181    """
3182    Build a Column.
3183
3184    Args:
3185        col: Column name or expression.
3186        table: Table name.
3187        db: Database name.
3188        catalog: Catalog name.
3189        fields: Additional fields using dots.
3190        quoted: Whether to force quotes on the column's identifiers.
3191        copy: Whether to copy expressions if passed in.
3192
3193    Returns:
3194        The new Column instance.
3195    """
3196    col = maybe_copy(col, copy) if isinstance(col, Expr) else to_identifier(col, quoted=quoted)
3197
3198    this: Column | Dot = Column(
3199        this=col,
3200        table=to_identifier(table, quoted=quoted, copy=copy),
3201        db=to_identifier(db, quoted=quoted, copy=copy),
3202        catalog=to_identifier(catalog, quoted=quoted, copy=copy),
3203    )
3204
3205    if fields:
3206        this = Dot.build(
3207            (this, *(to_identifier(field, quoted=quoted, copy=copy) for field in fields))
3208        )
3209    return this

Build a Column.

Arguments:
  • col: Column name or expression.
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • fields: Additional fields using dots.
  • quoted: Whether to force quotes on the column's identifiers.
  • copy: Whether to copy expressions if passed in.
Returns:

The new Column instance.