Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23from functools import reduce
  24
  25from sqlglot._typing import E
  26from sqlglot.errors import ParseError
  27from sqlglot.helper import (
  28    AutoName,
  29    camel_to_snake_case,
  30    ensure_collection,
  31    ensure_list,
  32    seq_get,
  33    subclasses,
  34)
  35from sqlglot.tokens import Token
  36
  37if t.TYPE_CHECKING:
  38    from sqlglot.dialects.dialect import DialectType
  39
  40
  41class _Expression(type):
  42    def __new__(cls, clsname, bases, attrs):
  43        klass = super().__new__(cls, clsname, bases, attrs)
  44
  45        # When an Expression class is created, its key is automatically set to be
  46        # the lowercase version of the class' name.
  47        klass.key = clsname.lower()
  48
  49        # This is so that docstrings are not inherited in pdoc
  50        klass.__doc__ = klass.__doc__ or ""
  51
  52        return klass
  53
  54
  55class Expression(metaclass=_Expression):
  56    """
  57    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  58    context, such as its child expressions, their names (arg keys), and whether a given child expression
  59    is optional or not.
  60
  61    Attributes:
  62        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  63            and representing expressions as strings.
  64        arg_types: determines what arguments (child nodes) are supported by an expression. It
  65            maps arg keys to booleans that indicate whether the corresponding args are optional.
  66        parent: a reference to the parent expression (or None, in case of root expressions).
  67        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  68            uses to refer to it.
  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(Expression):
  77        ...     arg_types = {"this": True, "expression": False}
  78
  79        The above definition informs us that Foo is an Expression 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 = "expression"
  87    arg_types = {"this": True}
  88    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  89
  90    def __init__(self, **args: t.Any):
  91        self.args: t.Dict[str, t.Any] = args
  92        self.parent: t.Optional[Expression] = None
  93        self.arg_key: t.Optional[str] = None
  94        self.comments: t.Optional[t.List[str]] = None
  95        self._type: t.Optional[DataType] = None
  96        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  97        self._hash: t.Optional[int] = None
  98
  99        for arg_key, value in self.args.items():
 100            self._set_parent(arg_key, value)
 101
 102    def __eq__(self, other) -> bool:
 103        return type(self) is type(other) and hash(self) == hash(other)
 104
 105    @property
 106    def hashable_args(self) -> t.Any:
 107        return frozenset(
 108            (k, tuple(_norm_arg(a) for a in v) if type(v) is list else _norm_arg(v))
 109            for k, v in self.args.items()
 110            if not (v is None or v is False or (type(v) is list and not v))
 111        )
 112
 113    def __hash__(self) -> int:
 114        if self._hash is not None:
 115            return self._hash
 116
 117        return hash((self.__class__, self.hashable_args))
 118
 119    @property
 120    def this(self):
 121        """
 122        Retrieves the argument with key "this".
 123        """
 124        return self.args.get("this")
 125
 126    @property
 127    def expression(self):
 128        """
 129        Retrieves the argument with key "expression".
 130        """
 131        return self.args.get("expression")
 132
 133    @property
 134    def expressions(self):
 135        """
 136        Retrieves the argument with key "expressions".
 137        """
 138        return self.args.get("expressions") or []
 139
 140    def text(self, key) -> str:
 141        """
 142        Returns a textual representation of the argument corresponding to "key". This can only be used
 143        for args that are strings or leaf Expression instances, such as identifiers and literals.
 144        """
 145        field = self.args.get(key)
 146        if isinstance(field, str):
 147            return field
 148        if isinstance(field, (Identifier, Literal, Var)):
 149            return field.this
 150        if isinstance(field, (Star, Null)):
 151            return field.name
 152        return ""
 153
 154    @property
 155    def is_string(self) -> bool:
 156        """
 157        Checks whether a Literal expression is a string.
 158        """
 159        return isinstance(self, Literal) and self.args["is_string"]
 160
 161    @property
 162    def is_number(self) -> bool:
 163        """
 164        Checks whether a Literal expression is a number.
 165        """
 166        return isinstance(self, Literal) and not self.args["is_string"]
 167
 168    @property
 169    def is_int(self) -> bool:
 170        """
 171        Checks whether a Literal expression is an integer.
 172        """
 173        if self.is_number:
 174            try:
 175                int(self.name)
 176                return True
 177            except ValueError:
 178                pass
 179        return False
 180
 181    @property
 182    def is_star(self) -> bool:
 183        """Checks whether an expression is a star."""
 184        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 185
 186    @property
 187    def alias(self) -> str:
 188        """
 189        Returns the alias of the expression, or an empty string if it's not aliased.
 190        """
 191        if isinstance(self.args.get("alias"), TableAlias):
 192            return self.args["alias"].name
 193        return self.text("alias")
 194
 195    @property
 196    def alias_column_names(self) -> t.List[str]:
 197        table_alias = self.args.get("alias")
 198        if not table_alias:
 199            return []
 200        return [c.name for c in table_alias.args.get("columns") or []]
 201
 202    @property
 203    def name(self) -> str:
 204        return self.text("this")
 205
 206    @property
 207    def alias_or_name(self) -> str:
 208        return self.alias or self.name
 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 Expression 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        return ""
 227
 228    @property
 229    def type(self) -> t.Optional[DataType]:
 230        return self._type
 231
 232    @type.setter
 233    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 234        if dtype and not isinstance(dtype, DataType):
 235            dtype = DataType.build(dtype)
 236        self._type = dtype  # type: ignore
 237
 238    @property
 239    def meta(self) -> t.Dict[str, t.Any]:
 240        if self._meta is None:
 241            self._meta = {}
 242        return self._meta
 243
 244    def __deepcopy__(self, memo):
 245        copy = self.__class__(**deepcopy(self.args))
 246        if self.comments is not None:
 247            copy.comments = deepcopy(self.comments)
 248
 249        if self._type is not None:
 250            copy._type = self._type.copy()
 251
 252        if self._meta is not None:
 253            copy._meta = deepcopy(self._meta)
 254
 255        return copy
 256
 257    def copy(self):
 258        """
 259        Returns a deep copy of the expression.
 260        """
 261        new = deepcopy(self)
 262        new.parent = self.parent
 263        return new
 264
 265    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
 266        if self.comments is None:
 267            self.comments = []
 268        if comments:
 269            self.comments.extend(comments)
 270
 271    def append(self, arg_key: str, value: t.Any) -> None:
 272        """
 273        Appends value to arg_key if it's a list or sets it as a new list.
 274
 275        Args:
 276            arg_key (str): name of the list expression arg
 277            value (Any): value to append to the list
 278        """
 279        if not isinstance(self.args.get(arg_key), list):
 280            self.args[arg_key] = []
 281        self.args[arg_key].append(value)
 282        self._set_parent(arg_key, value)
 283
 284    def set(self, arg_key: str, value: t.Any) -> None:
 285        """
 286        Sets arg_key to value.
 287
 288        Args:
 289            arg_key: name of the expression arg.
 290            value: value to set the arg to.
 291        """
 292        if value is None:
 293            self.args.pop(arg_key, None)
 294            return
 295
 296        self.args[arg_key] = value
 297        self._set_parent(arg_key, value)
 298
 299    def _set_parent(self, arg_key: str, value: t.Any) -> None:
 300        if hasattr(value, "parent"):
 301            value.parent = self
 302            value.arg_key = arg_key
 303        elif type(value) is list:
 304            for v in value:
 305                if hasattr(v, "parent"):
 306                    v.parent = self
 307                    v.arg_key = arg_key
 308
 309    @property
 310    def depth(self) -> int:
 311        """
 312        Returns the depth of this tree.
 313        """
 314        if self.parent:
 315            return self.parent.depth + 1
 316        return 0
 317
 318    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 319        """Yields the key and expression for all arguments, exploding list args."""
 320        for k, vs in self.args.items():
 321            if type(vs) is list:
 322                for v in vs:
 323                    if hasattr(v, "parent"):
 324                        yield k, v
 325            else:
 326                if hasattr(vs, "parent"):
 327                    yield k, vs
 328
 329    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
 330        """
 331        Returns the first node in this tree which matches at least one of
 332        the specified types.
 333
 334        Args:
 335            expression_types: the expression type(s) to match.
 336            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 337
 338        Returns:
 339            The node which matches the criteria or None if no such node was found.
 340        """
 341        return next(self.find_all(*expression_types, bfs=bfs), None)
 342
 343    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
 344        """
 345        Returns a generator object which visits all nodes in this tree and only
 346        yields those that match at least one of the specified expression types.
 347
 348        Args:
 349            expression_types: the expression type(s) to match.
 350            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 351
 352        Returns:
 353            The generator object.
 354        """
 355        for expression, *_ in self.walk(bfs=bfs):
 356            if isinstance(expression, expression_types):
 357                yield expression
 358
 359    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
 360        """
 361        Returns a nearest parent matching expression_types.
 362
 363        Args:
 364            expression_types: the expression type(s) to match.
 365
 366        Returns:
 367            The parent node.
 368        """
 369        ancestor = self.parent
 370        while ancestor and not isinstance(ancestor, expression_types):
 371            ancestor = ancestor.parent
 372        return t.cast(E, ancestor)
 373
 374    @property
 375    def parent_select(self) -> t.Optional[Select]:
 376        """
 377        Returns the parent select statement.
 378        """
 379        return self.find_ancestor(Select)
 380
 381    @property
 382    def same_parent(self) -> bool:
 383        """Returns if the parent is the same class as itself."""
 384        return type(self.parent) is self.__class__
 385
 386    def root(self) -> Expression:
 387        """
 388        Returns the root expression of this tree.
 389        """
 390        expression = self
 391        while expression.parent:
 392            expression = expression.parent
 393        return expression
 394
 395    def walk(self, bfs=True, prune=None):
 396        """
 397        Returns a generator object which visits all nodes in this tree.
 398
 399        Args:
 400            bfs (bool): if set to True the BFS traversal order will be applied,
 401                otherwise the DFS traversal will be used instead.
 402            prune ((node, parent, arg_key) -> bool): callable that returns True if
 403                the generator should stop traversing this branch of the tree.
 404
 405        Returns:
 406            the generator object.
 407        """
 408        if bfs:
 409            yield from self.bfs(prune=prune)
 410        else:
 411            yield from self.dfs(prune=prune)
 412
 413    def dfs(self, parent=None, key=None, prune=None):
 414        """
 415        Returns a generator object which visits all nodes in this tree in
 416        the DFS (Depth-first) order.
 417
 418        Returns:
 419            The generator object.
 420        """
 421        parent = parent or self.parent
 422        yield self, parent, key
 423        if prune and prune(self, parent, key):
 424            return
 425
 426        for k, v in self.iter_expressions():
 427            yield from v.dfs(self, k, prune)
 428
 429    def bfs(self, prune=None):
 430        """
 431        Returns a generator object which visits all nodes in this tree in
 432        the BFS (Breadth-first) order.
 433
 434        Returns:
 435            The generator object.
 436        """
 437        queue = deque([(self, self.parent, None)])
 438
 439        while queue:
 440            item, parent, key = queue.popleft()
 441
 442            yield item, parent, key
 443            if prune and prune(item, parent, key):
 444                continue
 445
 446            for k, v in item.iter_expressions():
 447                queue.append((v, item, k))
 448
 449    def unnest(self):
 450        """
 451        Returns the first non parenthesis child or self.
 452        """
 453        expression = self
 454        while type(expression) is Paren:
 455            expression = expression.this
 456        return expression
 457
 458    def unalias(self):
 459        """
 460        Returns the inner expression if this is an Alias.
 461        """
 462        if isinstance(self, Alias):
 463            return self.this
 464        return self
 465
 466    def unnest_operands(self):
 467        """
 468        Returns unnested operands as a tuple.
 469        """
 470        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 471
 472    def flatten(self, unnest=True):
 473        """
 474        Returns a generator which yields child nodes who's parents are the same class.
 475
 476        A AND B AND C -> [A, B, C]
 477        """
 478        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 479            if not type(node) is self.__class__:
 480                yield node.unnest() if unnest else node
 481
 482    def __str__(self) -> str:
 483        return self.sql()
 484
 485    def __repr__(self) -> str:
 486        return self._to_s()
 487
 488    def sql(self, dialect: DialectType = None, **opts) -> str:
 489        """
 490        Returns SQL string representation of this tree.
 491
 492        Args:
 493            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 494            opts: other `sqlglot.generator.Generator` options.
 495
 496        Returns:
 497            The SQL string.
 498        """
 499        from sqlglot.dialects import Dialect
 500
 501        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 502
 503    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 504        indent = "" if not level else "\n"
 505        indent += "".join(["  "] * level)
 506        left = f"({self.key.upper()} "
 507
 508        args: t.Dict[str, t.Any] = {
 509            k: ", ".join(
 510                v._to_s(hide_missing=hide_missing, level=level + 1)
 511                if hasattr(v, "_to_s")
 512                else str(v)
 513                for v in ensure_list(vs)
 514                if v is not None
 515            )
 516            for k, vs in self.args.items()
 517        }
 518        args["comments"] = self.comments
 519        args["type"] = self.type
 520        args = {k: v for k, v in args.items() if v or not hide_missing}
 521
 522        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 523        right += ")"
 524
 525        return indent + left + right
 526
 527    def transform(self, fun, *args, copy=True, **kwargs):
 528        """
 529        Recursively visits all tree nodes (excluding already transformed ones)
 530        and applies the given transformation function to each node.
 531
 532        Args:
 533            fun (function): a function which takes a node as an argument and returns a
 534                new transformed node or the same node without modifications. If the function
 535                returns None, then the corresponding node will be removed from the syntax tree.
 536            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 537                modified in place.
 538
 539        Returns:
 540            The transformed tree.
 541        """
 542        node = self.copy() if copy else self
 543        new_node = fun(node, *args, **kwargs)
 544
 545        if new_node is None or not isinstance(new_node, Expression):
 546            return new_node
 547        if new_node is not node:
 548            new_node.parent = node.parent
 549            return new_node
 550
 551        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 552        return new_node
 553
 554    @t.overload
 555    def replace(self, expression: E) -> E:
 556        ...
 557
 558    @t.overload
 559    def replace(self, expression: None) -> None:
 560        ...
 561
 562    def replace(self, expression):
 563        """
 564        Swap out this expression with a new expression.
 565
 566        For example::
 567
 568            >>> tree = Select().select("x").from_("tbl")
 569            >>> tree.find(Column).replace(Column(this="y"))
 570            (COLUMN this: y)
 571            >>> tree.sql()
 572            'SELECT y FROM tbl'
 573
 574        Args:
 575            expression: new node
 576
 577        Returns:
 578            The new expression or expressions.
 579        """
 580        if not self.parent:
 581            return expression
 582
 583        parent = self.parent
 584        self.parent = None
 585
 586        replace_children(parent, lambda child: expression if child is self else child)
 587        return expression
 588
 589    def pop(self: E) -> E:
 590        """
 591        Remove this expression from its AST.
 592
 593        Returns:
 594            The popped expression.
 595        """
 596        self.replace(None)
 597        return self
 598
 599    def assert_is(self, type_: t.Type[E]) -> E:
 600        """
 601        Assert that this `Expression` is an instance of `type_`.
 602
 603        If it is NOT an instance of `type_`, this raises an assertion error.
 604        Otherwise, this returns this expression.
 605
 606        Examples:
 607            This is useful for type security in chained expressions:
 608
 609            >>> import sqlglot
 610            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 611            'SELECT x, z FROM y'
 612        """
 613        assert isinstance(self, type_)
 614        return self
 615
 616    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 617        """
 618        Checks if this expression is valid (e.g. all mandatory args are set).
 619
 620        Args:
 621            args: a sequence of values that were used to instantiate a Func expression. This is used
 622                to check that the provided arguments don't exceed the function argument limit.
 623
 624        Returns:
 625            A list of error messages for all possible errors that were found.
 626        """
 627        errors: t.List[str] = []
 628
 629        for k in self.args:
 630            if k not in self.arg_types:
 631                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 632        for k, mandatory in self.arg_types.items():
 633            v = self.args.get(k)
 634            if mandatory and (v is None or (isinstance(v, list) and not v)):
 635                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 636
 637        if (
 638            args
 639            and isinstance(self, Func)
 640            and len(args) > len(self.arg_types)
 641            and not self.is_var_len_args
 642        ):
 643            errors.append(
 644                f"The number of provided arguments ({len(args)}) is greater than "
 645                f"the maximum number of supported arguments ({len(self.arg_types)})"
 646            )
 647
 648        return errors
 649
 650    def dump(self):
 651        """
 652        Dump this Expression to a JSON-serializable dict.
 653        """
 654        from sqlglot.serde import dump
 655
 656        return dump(self)
 657
 658    @classmethod
 659    def load(cls, obj):
 660        """
 661        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 662        """
 663        from sqlglot.serde import load
 664
 665        return load(obj)
 666
 667
 668IntoType = t.Union[
 669    str,
 670    t.Type[Expression],
 671    t.Collection[t.Union[str, t.Type[Expression]]],
 672]
 673ExpOrStr = t.Union[str, Expression]
 674
 675
 676class Condition(Expression):
 677    def and_(
 678        self,
 679        *expressions: t.Optional[ExpOrStr],
 680        dialect: DialectType = None,
 681        copy: bool = True,
 682        **opts,
 683    ) -> Condition:
 684        """
 685        AND this condition with one or multiple expressions.
 686
 687        Example:
 688            >>> condition("x=1").and_("y=1").sql()
 689            'x = 1 AND y = 1'
 690
 691        Args:
 692            *expressions: the SQL code strings to parse.
 693                If an `Expression` instance is passed, it will be used as-is.
 694            dialect: the dialect used to parse the input expression.
 695            copy: whether or not to copy the involved expressions (only applies to Expressions).
 696            opts: other options to use to parse the input expressions.
 697
 698        Returns:
 699            The new And condition.
 700        """
 701        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
 702
 703    def or_(
 704        self,
 705        *expressions: t.Optional[ExpOrStr],
 706        dialect: DialectType = None,
 707        copy: bool = True,
 708        **opts,
 709    ) -> Condition:
 710        """
 711        OR this condition with one or multiple expressions.
 712
 713        Example:
 714            >>> condition("x=1").or_("y=1").sql()
 715            'x = 1 OR y = 1'
 716
 717        Args:
 718            *expressions: the SQL code strings to parse.
 719                If an `Expression` instance is passed, it will be used as-is.
 720            dialect: the dialect used to parse the input expression.
 721            copy: whether or not to copy the involved expressions (only applies to Expressions).
 722            opts: other options to use to parse the input expressions.
 723
 724        Returns:
 725            The new Or condition.
 726        """
 727        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
 728
 729    def not_(self, copy: bool = True):
 730        """
 731        Wrap this condition with NOT.
 732
 733        Example:
 734            >>> condition("x=1").not_().sql()
 735            'NOT x = 1'
 736
 737        Args:
 738            copy: whether or not to copy this object.
 739
 740        Returns:
 741            The new Not instance.
 742        """
 743        return not_(self, copy=copy)
 744
 745    def as_(
 746        self,
 747        alias: str | Identifier,
 748        quoted: t.Optional[bool] = None,
 749        dialect: DialectType = None,
 750        copy: bool = True,
 751        **opts,
 752    ) -> Alias:
 753        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
 754
 755    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
 756        this = self.copy()
 757        other = convert(other, copy=True)
 758        if not isinstance(this, klass) and not isinstance(other, klass):
 759            this = _wrap(this, Binary)
 760            other = _wrap(other, Binary)
 761        if reverse:
 762            return klass(this=other, expression=this)
 763        return klass(this=this, expression=other)
 764
 765    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
 766        return Bracket(
 767            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
 768        )
 769
 770    def isin(
 771        self,
 772        *expressions: t.Any,
 773        query: t.Optional[ExpOrStr] = None,
 774        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
 775        copy: bool = True,
 776        **opts,
 777    ) -> In:
 778        return In(
 779            this=maybe_copy(self, copy),
 780            expressions=[convert(e, copy=copy) for e in expressions],
 781            query=maybe_parse(query, copy=copy, **opts) if query else None,
 782            unnest=Unnest(
 783                expressions=[
 784                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
 785                ]
 786            )
 787            if unnest
 788            else None,
 789        )
 790
 791    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
 792        return Between(
 793            this=maybe_copy(self, copy),
 794            low=convert(low, copy=copy, **opts),
 795            high=convert(high, copy=copy, **opts),
 796        )
 797
 798    def is_(self, other: ExpOrStr) -> Is:
 799        return self._binop(Is, other)
 800
 801    def like(self, other: ExpOrStr) -> Like:
 802        return self._binop(Like, other)
 803
 804    def ilike(self, other: ExpOrStr) -> ILike:
 805        return self._binop(ILike, other)
 806
 807    def eq(self, other: t.Any) -> EQ:
 808        return self._binop(EQ, other)
 809
 810    def neq(self, other: t.Any) -> NEQ:
 811        return self._binop(NEQ, other)
 812
 813    def rlike(self, other: ExpOrStr) -> RegexpLike:
 814        return self._binop(RegexpLike, other)
 815
 816    def __lt__(self, other: t.Any) -> LT:
 817        return self._binop(LT, other)
 818
 819    def __le__(self, other: t.Any) -> LTE:
 820        return self._binop(LTE, other)
 821
 822    def __gt__(self, other: t.Any) -> GT:
 823        return self._binop(GT, other)
 824
 825    def __ge__(self, other: t.Any) -> GTE:
 826        return self._binop(GTE, other)
 827
 828    def __add__(self, other: t.Any) -> Add:
 829        return self._binop(Add, other)
 830
 831    def __radd__(self, other: t.Any) -> Add:
 832        return self._binop(Add, other, reverse=True)
 833
 834    def __sub__(self, other: t.Any) -> Sub:
 835        return self._binop(Sub, other)
 836
 837    def __rsub__(self, other: t.Any) -> Sub:
 838        return self._binop(Sub, other, reverse=True)
 839
 840    def __mul__(self, other: t.Any) -> Mul:
 841        return self._binop(Mul, other)
 842
 843    def __rmul__(self, other: t.Any) -> Mul:
 844        return self._binop(Mul, other, reverse=True)
 845
 846    def __truediv__(self, other: t.Any) -> Div:
 847        return self._binop(Div, other)
 848
 849    def __rtruediv__(self, other: t.Any) -> Div:
 850        return self._binop(Div, other, reverse=True)
 851
 852    def __floordiv__(self, other: t.Any) -> IntDiv:
 853        return self._binop(IntDiv, other)
 854
 855    def __rfloordiv__(self, other: t.Any) -> IntDiv:
 856        return self._binop(IntDiv, other, reverse=True)
 857
 858    def __mod__(self, other: t.Any) -> Mod:
 859        return self._binop(Mod, other)
 860
 861    def __rmod__(self, other: t.Any) -> Mod:
 862        return self._binop(Mod, other, reverse=True)
 863
 864    def __pow__(self, other: t.Any) -> Pow:
 865        return self._binop(Pow, other)
 866
 867    def __rpow__(self, other: t.Any) -> Pow:
 868        return self._binop(Pow, other, reverse=True)
 869
 870    def __and__(self, other: t.Any) -> And:
 871        return self._binop(And, other)
 872
 873    def __rand__(self, other: t.Any) -> And:
 874        return self._binop(And, other, reverse=True)
 875
 876    def __or__(self, other: t.Any) -> Or:
 877        return self._binop(Or, other)
 878
 879    def __ror__(self, other: t.Any) -> Or:
 880        return self._binop(Or, other, reverse=True)
 881
 882    def __neg__(self) -> Neg:
 883        return Neg(this=_wrap(self.copy(), Binary))
 884
 885    def __invert__(self) -> Not:
 886        return not_(self.copy())
 887
 888
 889class Predicate(Condition):
 890    """Relationships like x = y, x > 1, x >= y."""
 891
 892
 893class DerivedTable(Expression):
 894    @property
 895    def selects(self) -> t.List[Expression]:
 896        return self.this.selects if isinstance(self.this, Subqueryable) else []
 897
 898    @property
 899    def named_selects(self) -> t.List[str]:
 900        return [select.output_name for select in self.selects]
 901
 902
 903class Unionable(Expression):
 904    def union(
 905        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 906    ) -> Unionable:
 907        """
 908        Builds a UNION expression.
 909
 910        Example:
 911            >>> import sqlglot
 912            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 913            'SELECT * FROM foo UNION SELECT * FROM bla'
 914
 915        Args:
 916            expression: the SQL code string.
 917                If an `Expression` instance is passed, it will be used as-is.
 918            distinct: set the DISTINCT flag if and only if this is true.
 919            dialect: the dialect used to parse the input expression.
 920            opts: other options to use to parse the input expressions.
 921
 922        Returns:
 923            The new Union expression.
 924        """
 925        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 926
 927    def intersect(
 928        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 929    ) -> Unionable:
 930        """
 931        Builds an INTERSECT expression.
 932
 933        Example:
 934            >>> import sqlglot
 935            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 936            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 937
 938        Args:
 939            expression: the SQL code string.
 940                If an `Expression` instance is passed, it will be used as-is.
 941            distinct: set the DISTINCT flag if and only if this is true.
 942            dialect: the dialect used to parse the input expression.
 943            opts: other options to use to parse the input expressions.
 944
 945        Returns:
 946            The new Intersect expression.
 947        """
 948        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 949
 950    def except_(
 951        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 952    ) -> Unionable:
 953        """
 954        Builds an EXCEPT expression.
 955
 956        Example:
 957            >>> import sqlglot
 958            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 959            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 960
 961        Args:
 962            expression: the SQL code string.
 963                If an `Expression` instance is passed, it will be used as-is.
 964            distinct: set the DISTINCT flag if and only if this is true.
 965            dialect: the dialect used to parse the input expression.
 966            opts: other options to use to parse the input expressions.
 967
 968        Returns:
 969            The new Except expression.
 970        """
 971        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 972
 973
 974class UDTF(DerivedTable, Unionable):
 975    @property
 976    def selects(self) -> t.List[Expression]:
 977        alias = self.args.get("alias")
 978        return alias.columns if alias else []
 979
 980
 981class Cache(Expression):
 982    arg_types = {
 983        "with": False,
 984        "this": True,
 985        "lazy": False,
 986        "options": False,
 987        "expression": False,
 988    }
 989
 990
 991class Uncache(Expression):
 992    arg_types = {"this": True, "exists": False}
 993
 994
 995class DDL(Expression):
 996    @property
 997    def ctes(self):
 998        with_ = self.args.get("with")
 999        if not with_:
1000            return []
1001        return with_.expressions
1002
1003    @property
1004    def named_selects(self) -> t.List[str]:
1005        if isinstance(self.expression, Subqueryable):
1006            return self.expression.named_selects
1007        return []
1008
1009    @property
1010    def selects(self) -> t.List[Expression]:
1011        if isinstance(self.expression, Subqueryable):
1012            return self.expression.selects
1013        return []
1014
1015
1016class Create(DDL):
1017    arg_types = {
1018        "with": False,
1019        "this": True,
1020        "kind": True,
1021        "expression": False,
1022        "exists": False,
1023        "properties": False,
1024        "replace": False,
1025        "unique": False,
1026        "indexes": False,
1027        "no_schema_binding": False,
1028        "begin": False,
1029        "clone": False,
1030    }
1031
1032
1033# https://docs.snowflake.com/en/sql-reference/sql/create-clone
1034class Clone(Expression):
1035    arg_types = {
1036        "this": True,
1037        "when": False,
1038        "kind": False,
1039        "shallow": False,
1040        "expression": False,
1041    }
1042
1043
1044class Describe(Expression):
1045    arg_types = {"this": True, "kind": False, "expressions": False}
1046
1047
1048class Pragma(Expression):
1049    pass
1050
1051
1052class Set(Expression):
1053    arg_types = {"expressions": False, "unset": False, "tag": False}
1054
1055
1056class SetItem(Expression):
1057    arg_types = {
1058        "this": False,
1059        "expressions": False,
1060        "kind": False,
1061        "collate": False,  # MySQL SET NAMES statement
1062        "global": False,
1063    }
1064
1065
1066class Show(Expression):
1067    arg_types = {
1068        "this": True,
1069        "target": False,
1070        "offset": False,
1071        "limit": False,
1072        "like": False,
1073        "where": False,
1074        "db": False,
1075        "scope": False,
1076        "scope_kind": False,
1077        "full": False,
1078        "mutex": False,
1079        "query": False,
1080        "channel": False,
1081        "global": False,
1082        "log": False,
1083        "position": False,
1084        "types": False,
1085    }
1086
1087
1088class UserDefinedFunction(Expression):
1089    arg_types = {"this": True, "expressions": False, "wrapped": False}
1090
1091
1092class CharacterSet(Expression):
1093    arg_types = {"this": True, "default": False}
1094
1095
1096class With(Expression):
1097    arg_types = {"expressions": True, "recursive": False}
1098
1099    @property
1100    def recursive(self) -> bool:
1101        return bool(self.args.get("recursive"))
1102
1103
1104class WithinGroup(Expression):
1105    arg_types = {"this": True, "expression": False}
1106
1107
1108class CTE(DerivedTable):
1109    arg_types = {"this": True, "alias": True}
1110
1111
1112class TableAlias(Expression):
1113    arg_types = {"this": False, "columns": False}
1114
1115    @property
1116    def columns(self):
1117        return self.args.get("columns") or []
1118
1119
1120class BitString(Condition):
1121    pass
1122
1123
1124class HexString(Condition):
1125    pass
1126
1127
1128class ByteString(Condition):
1129    pass
1130
1131
1132class RawString(Condition):
1133    pass
1134
1135
1136class Column(Condition):
1137    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1138
1139    @property
1140    def table(self) -> str:
1141        return self.text("table")
1142
1143    @property
1144    def db(self) -> str:
1145        return self.text("db")
1146
1147    @property
1148    def catalog(self) -> str:
1149        return self.text("catalog")
1150
1151    @property
1152    def output_name(self) -> str:
1153        return self.name
1154
1155    @property
1156    def parts(self) -> t.List[Identifier]:
1157        """Return the parts of a column in order catalog, db, table, name."""
1158        return [
1159            t.cast(Identifier, self.args[part])
1160            for part in ("catalog", "db", "table", "this")
1161            if self.args.get(part)
1162        ]
1163
1164    def to_dot(self) -> Dot:
1165        """Converts the column into a dot expression."""
1166        parts = self.parts
1167        parent = self.parent
1168
1169        while parent:
1170            if isinstance(parent, Dot):
1171                parts.append(parent.expression)
1172            parent = parent.parent
1173
1174        return Dot.build(deepcopy(parts))
1175
1176
1177class ColumnPosition(Expression):
1178    arg_types = {"this": False, "position": True}
1179
1180
1181class ColumnDef(Expression):
1182    arg_types = {
1183        "this": True,
1184        "kind": False,
1185        "constraints": False,
1186        "exists": False,
1187        "position": False,
1188    }
1189
1190    @property
1191    def constraints(self) -> t.List[ColumnConstraint]:
1192        return self.args.get("constraints") or []
1193
1194
1195class AlterColumn(Expression):
1196    arg_types = {
1197        "this": True,
1198        "dtype": False,
1199        "collate": False,
1200        "using": False,
1201        "default": False,
1202        "drop": False,
1203    }
1204
1205
1206class RenameTable(Expression):
1207    pass
1208
1209
1210class Comment(Expression):
1211    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
1212
1213
1214class Comprehension(Expression):
1215    arg_types = {"this": True, "expression": True, "iterator": True, "condition": False}
1216
1217
1218# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1219class MergeTreeTTLAction(Expression):
1220    arg_types = {
1221        "this": True,
1222        "delete": False,
1223        "recompress": False,
1224        "to_disk": False,
1225        "to_volume": False,
1226    }
1227
1228
1229# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1230class MergeTreeTTL(Expression):
1231    arg_types = {
1232        "expressions": True,
1233        "where": False,
1234        "group": False,
1235        "aggregates": False,
1236    }
1237
1238
1239# https://dev.mysql.com/doc/refman/8.0/en/create-table.html
1240class IndexConstraintOption(Expression):
1241    arg_types = {
1242        "key_block_size": False,
1243        "using": False,
1244        "parser": False,
1245        "comment": False,
1246        "visible": False,
1247        "engine_attr": False,
1248        "secondary_engine_attr": False,
1249    }
1250
1251
1252class ColumnConstraint(Expression):
1253    arg_types = {"this": False, "kind": True}
1254
1255    @property
1256    def kind(self) -> ColumnConstraintKind:
1257        return self.args["kind"]
1258
1259
1260class ColumnConstraintKind(Expression):
1261    pass
1262
1263
1264class AutoIncrementColumnConstraint(ColumnConstraintKind):
1265    pass
1266
1267
1268class CaseSpecificColumnConstraint(ColumnConstraintKind):
1269    arg_types = {"not_": True}
1270
1271
1272class CharacterSetColumnConstraint(ColumnConstraintKind):
1273    arg_types = {"this": True}
1274
1275
1276class CheckColumnConstraint(ColumnConstraintKind):
1277    pass
1278
1279
1280class ClusteredColumnConstraint(ColumnConstraintKind):
1281    pass
1282
1283
1284class CollateColumnConstraint(ColumnConstraintKind):
1285    pass
1286
1287
1288class CommentColumnConstraint(ColumnConstraintKind):
1289    pass
1290
1291
1292class CompressColumnConstraint(ColumnConstraintKind):
1293    pass
1294
1295
1296class DateFormatColumnConstraint(ColumnConstraintKind):
1297    arg_types = {"this": True}
1298
1299
1300class DefaultColumnConstraint(ColumnConstraintKind):
1301    pass
1302
1303
1304class EncodeColumnConstraint(ColumnConstraintKind):
1305    pass
1306
1307
1308class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1309    # this: True -> ALWAYS, this: False -> BY DEFAULT
1310    arg_types = {
1311        "this": False,
1312        "expression": False,
1313        "on_null": False,
1314        "start": False,
1315        "increment": False,
1316        "minvalue": False,
1317        "maxvalue": False,
1318        "cycle": False,
1319    }
1320
1321
1322# https://dev.mysql.com/doc/refman/8.0/en/create-table.html
1323class IndexColumnConstraint(ColumnConstraintKind):
1324    arg_types = {"this": False, "schema": True, "kind": False, "type": False, "options": False}
1325
1326
1327class InlineLengthColumnConstraint(ColumnConstraintKind):
1328    pass
1329
1330
1331class NonClusteredColumnConstraint(ColumnConstraintKind):
1332    pass
1333
1334
1335class NotForReplicationColumnConstraint(ColumnConstraintKind):
1336    arg_types = {}
1337
1338
1339class NotNullColumnConstraint(ColumnConstraintKind):
1340    arg_types = {"allow_null": False}
1341
1342
1343# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
1344class OnUpdateColumnConstraint(ColumnConstraintKind):
1345    pass
1346
1347
1348class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1349    arg_types = {"desc": False}
1350
1351
1352class TitleColumnConstraint(ColumnConstraintKind):
1353    pass
1354
1355
1356class UniqueColumnConstraint(ColumnConstraintKind):
1357    arg_types = {"this": False}
1358
1359
1360class UppercaseColumnConstraint(ColumnConstraintKind):
1361    arg_types: t.Dict[str, t.Any] = {}
1362
1363
1364class PathColumnConstraint(ColumnConstraintKind):
1365    pass
1366
1367
1368# computed column expression
1369# https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver16
1370class ComputedColumnConstraint(ColumnConstraintKind):
1371    arg_types = {"this": True, "persisted": False, "not_null": False}
1372
1373
1374class Constraint(Expression):
1375    arg_types = {"this": True, "expressions": True}
1376
1377
1378class Delete(Expression):
1379    arg_types = {
1380        "with": False,
1381        "this": False,
1382        "using": False,
1383        "where": False,
1384        "returning": False,
1385        "limit": False,
1386        "tables": False,  # Multiple-Table Syntax (MySQL)
1387    }
1388
1389    def delete(
1390        self,
1391        table: ExpOrStr,
1392        dialect: DialectType = None,
1393        copy: bool = True,
1394        **opts,
1395    ) -> Delete:
1396        """
1397        Create a DELETE expression or replace the table on an existing DELETE expression.
1398
1399        Example:
1400            >>> delete("tbl").sql()
1401            'DELETE FROM tbl'
1402
1403        Args:
1404            table: the table from which to delete.
1405            dialect: the dialect used to parse the input expression.
1406            copy: if `False`, modify this expression instance in-place.
1407            opts: other options to use to parse the input expressions.
1408
1409        Returns:
1410            Delete: the modified expression.
1411        """
1412        return _apply_builder(
1413            expression=table,
1414            instance=self,
1415            arg="this",
1416            dialect=dialect,
1417            into=Table,
1418            copy=copy,
1419            **opts,
1420        )
1421
1422    def where(
1423        self,
1424        *expressions: t.Optional[ExpOrStr],
1425        append: bool = True,
1426        dialect: DialectType = None,
1427        copy: bool = True,
1428        **opts,
1429    ) -> Delete:
1430        """
1431        Append to or set the WHERE expressions.
1432
1433        Example:
1434            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1435            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1436
1437        Args:
1438            *expressions: the SQL code strings to parse.
1439                If an `Expression` instance is passed, it will be used as-is.
1440                Multiple expressions are combined with an AND operator.
1441            append: if `True`, AND the new expressions to any existing expression.
1442                Otherwise, this resets the expression.
1443            dialect: the dialect used to parse the input expressions.
1444            copy: if `False`, modify this expression instance in-place.
1445            opts: other options to use to parse the input expressions.
1446
1447        Returns:
1448            Delete: the modified expression.
1449        """
1450        return _apply_conjunction_builder(
1451            *expressions,
1452            instance=self,
1453            arg="where",
1454            append=append,
1455            into=Where,
1456            dialect=dialect,
1457            copy=copy,
1458            **opts,
1459        )
1460
1461    def returning(
1462        self,
1463        expression: ExpOrStr,
1464        dialect: DialectType = None,
1465        copy: bool = True,
1466        **opts,
1467    ) -> Delete:
1468        """
1469        Set the RETURNING expression. Not supported by all dialects.
1470
1471        Example:
1472            >>> delete("tbl").returning("*", dialect="postgres").sql()
1473            'DELETE FROM tbl RETURNING *'
1474
1475        Args:
1476            expression: the SQL code strings to parse.
1477                If an `Expression` instance is passed, it will be used as-is.
1478            dialect: the dialect used to parse the input expressions.
1479            copy: if `False`, modify this expression instance in-place.
1480            opts: other options to use to parse the input expressions.
1481
1482        Returns:
1483            Delete: the modified expression.
1484        """
1485        return _apply_builder(
1486            expression=expression,
1487            instance=self,
1488            arg="returning",
1489            prefix="RETURNING",
1490            dialect=dialect,
1491            copy=copy,
1492            into=Returning,
1493            **opts,
1494        )
1495
1496
1497class Drop(Expression):
1498    arg_types = {
1499        "this": False,
1500        "kind": False,
1501        "exists": False,
1502        "temporary": False,
1503        "materialized": False,
1504        "cascade": False,
1505        "constraints": False,
1506        "purge": False,
1507    }
1508
1509
1510class Filter(Expression):
1511    arg_types = {"this": True, "expression": True}
1512
1513
1514class Check(Expression):
1515    pass
1516
1517
1518# https://docs.snowflake.com/en/sql-reference/constructs/connect-by
1519class Connect(Expression):
1520    arg_types = {"start": False, "connect": True}
1521
1522
1523class Prior(Expression):
1524    pass
1525
1526
1527class Directory(Expression):
1528    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1529    arg_types = {"this": True, "local": False, "row_format": False}
1530
1531
1532class ForeignKey(Expression):
1533    arg_types = {
1534        "expressions": True,
1535        "reference": False,
1536        "delete": False,
1537        "update": False,
1538    }
1539
1540
1541class ColumnPrefix(Expression):
1542    arg_types = {"this": True, "expression": True}
1543
1544
1545class PrimaryKey(Expression):
1546    arg_types = {"expressions": True, "options": False}
1547
1548
1549# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1550# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1551class Into(Expression):
1552    arg_types = {"this": True, "temporary": False, "unlogged": False}
1553
1554
1555class From(Expression):
1556    @property
1557    def name(self) -> str:
1558        return self.this.name
1559
1560    @property
1561    def alias_or_name(self) -> str:
1562        return self.this.alias_or_name
1563
1564
1565class Having(Expression):
1566    pass
1567
1568
1569class Hint(Expression):
1570    arg_types = {"expressions": True}
1571
1572
1573class JoinHint(Expression):
1574    arg_types = {"this": True, "expressions": True}
1575
1576
1577class Identifier(Expression):
1578    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1579
1580    @property
1581    def quoted(self) -> bool:
1582        return bool(self.args.get("quoted"))
1583
1584    @property
1585    def hashable_args(self) -> t.Any:
1586        return (self.this, self.quoted)
1587
1588    @property
1589    def output_name(self) -> str:
1590        return self.name
1591
1592
1593class Index(Expression):
1594    arg_types = {
1595        "this": False,
1596        "table": False,
1597        "using": False,
1598        "where": False,
1599        "columns": False,
1600        "unique": False,
1601        "primary": False,
1602        "amp": False,  # teradata
1603        "partition_by": False,  # teradata
1604    }
1605
1606
1607class Insert(DDL):
1608    arg_types = {
1609        "with": False,
1610        "this": True,
1611        "expression": False,
1612        "conflict": False,
1613        "returning": False,
1614        "overwrite": False,
1615        "exists": False,
1616        "partition": False,
1617        "alternative": False,
1618        "where": False,
1619        "ignore": False,
1620        "by_name": False,
1621    }
1622
1623    def with_(
1624        self,
1625        alias: ExpOrStr,
1626        as_: ExpOrStr,
1627        recursive: t.Optional[bool] = None,
1628        append: bool = True,
1629        dialect: DialectType = None,
1630        copy: bool = True,
1631        **opts,
1632    ) -> Insert:
1633        """
1634        Append to or set the common table expressions.
1635
1636        Example:
1637            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1638            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1639
1640        Args:
1641            alias: the SQL code string to parse as the table name.
1642                If an `Expression` instance is passed, this is used as-is.
1643            as_: the SQL code string to parse as the table expression.
1644                If an `Expression` instance is passed, it will be used as-is.
1645            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1646            append: if `True`, add to any existing expressions.
1647                Otherwise, this resets the expressions.
1648            dialect: the dialect used to parse the input expression.
1649            copy: if `False`, modify this expression instance in-place.
1650            opts: other options to use to parse the input expressions.
1651
1652        Returns:
1653            The modified expression.
1654        """
1655        return _apply_cte_builder(
1656            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1657        )
1658
1659
1660class OnConflict(Expression):
1661    arg_types = {
1662        "duplicate": False,
1663        "expressions": False,
1664        "nothing": False,
1665        "key": False,
1666        "constraint": False,
1667    }
1668
1669
1670class Returning(Expression):
1671    arg_types = {"expressions": True, "into": False}
1672
1673
1674# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1675class Introducer(Expression):
1676    arg_types = {"this": True, "expression": True}
1677
1678
1679# national char, like n'utf8'
1680class National(Expression):
1681    pass
1682
1683
1684class LoadData(Expression):
1685    arg_types = {
1686        "this": True,
1687        "local": False,
1688        "overwrite": False,
1689        "inpath": True,
1690        "partition": False,
1691        "input_format": False,
1692        "serde": False,
1693    }
1694
1695
1696class Partition(Expression):
1697    arg_types = {"expressions": True}
1698
1699
1700class Fetch(Expression):
1701    arg_types = {
1702        "direction": False,
1703        "count": False,
1704        "percent": False,
1705        "with_ties": False,
1706    }
1707
1708
1709class Group(Expression):
1710    arg_types = {
1711        "expressions": False,
1712        "grouping_sets": False,
1713        "cube": False,
1714        "rollup": False,
1715        "totals": False,
1716        "all": False,
1717    }
1718
1719
1720class Lambda(Expression):
1721    arg_types = {"this": True, "expressions": True}
1722
1723
1724class Limit(Expression):
1725    arg_types = {"this": False, "expression": True, "offset": False}
1726
1727
1728class Literal(Condition):
1729    arg_types = {"this": True, "is_string": True}
1730
1731    @property
1732    def hashable_args(self) -> t.Any:
1733        return (self.this, self.args.get("is_string"))
1734
1735    @classmethod
1736    def number(cls, number) -> Literal:
1737        return cls(this=str(number), is_string=False)
1738
1739    @classmethod
1740    def string(cls, string) -> Literal:
1741        return cls(this=str(string), is_string=True)
1742
1743    @property
1744    def output_name(self) -> str:
1745        return self.name
1746
1747
1748class Join(Expression):
1749    arg_types = {
1750        "this": True,
1751        "on": False,
1752        "side": False,
1753        "kind": False,
1754        "using": False,
1755        "method": False,
1756        "global": False,
1757        "hint": False,
1758    }
1759
1760    @property
1761    def method(self) -> str:
1762        return self.text("method").upper()
1763
1764    @property
1765    def kind(self) -> str:
1766        return self.text("kind").upper()
1767
1768    @property
1769    def side(self) -> str:
1770        return self.text("side").upper()
1771
1772    @property
1773    def hint(self) -> str:
1774        return self.text("hint").upper()
1775
1776    @property
1777    def alias_or_name(self) -> str:
1778        return self.this.alias_or_name
1779
1780    def on(
1781        self,
1782        *expressions: t.Optional[ExpOrStr],
1783        append: bool = True,
1784        dialect: DialectType = None,
1785        copy: bool = True,
1786        **opts,
1787    ) -> Join:
1788        """
1789        Append to or set the ON expressions.
1790
1791        Example:
1792            >>> import sqlglot
1793            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1794            'JOIN x ON y = 1'
1795
1796        Args:
1797            *expressions: the SQL code strings to parse.
1798                If an `Expression` instance is passed, it will be used as-is.
1799                Multiple expressions are combined with an AND operator.
1800            append: if `True`, AND the new expressions to any existing expression.
1801                Otherwise, this resets the expression.
1802            dialect: the dialect used to parse the input expressions.
1803            copy: if `False`, modify this expression instance in-place.
1804            opts: other options to use to parse the input expressions.
1805
1806        Returns:
1807            The modified Join expression.
1808        """
1809        join = _apply_conjunction_builder(
1810            *expressions,
1811            instance=self,
1812            arg="on",
1813            append=append,
1814            dialect=dialect,
1815            copy=copy,
1816            **opts,
1817        )
1818
1819        if join.kind == "CROSS":
1820            join.set("kind", None)
1821
1822        return join
1823
1824    def using(
1825        self,
1826        *expressions: t.Optional[ExpOrStr],
1827        append: bool = True,
1828        dialect: DialectType = None,
1829        copy: bool = True,
1830        **opts,
1831    ) -> Join:
1832        """
1833        Append to or set the USING expressions.
1834
1835        Example:
1836            >>> import sqlglot
1837            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1838            'JOIN x USING (foo, bla)'
1839
1840        Args:
1841            *expressions: the SQL code strings to parse.
1842                If an `Expression` instance is passed, it will be used as-is.
1843            append: if `True`, concatenate the new expressions to the existing "using" list.
1844                Otherwise, this resets the expression.
1845            dialect: the dialect used to parse the input expressions.
1846            copy: if `False`, modify this expression instance in-place.
1847            opts: other options to use to parse the input expressions.
1848
1849        Returns:
1850            The modified Join expression.
1851        """
1852        join = _apply_list_builder(
1853            *expressions,
1854            instance=self,
1855            arg="using",
1856            append=append,
1857            dialect=dialect,
1858            copy=copy,
1859            **opts,
1860        )
1861
1862        if join.kind == "CROSS":
1863            join.set("kind", None)
1864
1865        return join
1866
1867
1868class Lateral(UDTF):
1869    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1870
1871
1872class MatchRecognize(Expression):
1873    arg_types = {
1874        "partition_by": False,
1875        "order": False,
1876        "measures": False,
1877        "rows": False,
1878        "after": False,
1879        "pattern": False,
1880        "define": False,
1881        "alias": False,
1882    }
1883
1884
1885# Clickhouse FROM FINAL modifier
1886# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1887class Final(Expression):
1888    pass
1889
1890
1891class Offset(Expression):
1892    arg_types = {"this": False, "expression": True}
1893
1894
1895class Order(Expression):
1896    arg_types = {"this": False, "expressions": True}
1897
1898
1899# hive specific sorts
1900# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1901class Cluster(Order):
1902    pass
1903
1904
1905class Distribute(Order):
1906    pass
1907
1908
1909class Sort(Order):
1910    pass
1911
1912
1913class Ordered(Expression):
1914    arg_types = {"this": True, "desc": True, "nulls_first": True}
1915
1916
1917class Property(Expression):
1918    arg_types = {"this": True, "value": True}
1919
1920
1921class AlgorithmProperty(Property):
1922    arg_types = {"this": True}
1923
1924
1925class AutoIncrementProperty(Property):
1926    arg_types = {"this": True}
1927
1928
1929class BlockCompressionProperty(Property):
1930    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1931
1932
1933class CharacterSetProperty(Property):
1934    arg_types = {"this": True, "default": True}
1935
1936
1937class ChecksumProperty(Property):
1938    arg_types = {"on": False, "default": False}
1939
1940
1941class CollateProperty(Property):
1942    arg_types = {"this": True}
1943
1944
1945class CopyGrantsProperty(Property):
1946    arg_types = {}
1947
1948
1949class DataBlocksizeProperty(Property):
1950    arg_types = {
1951        "size": False,
1952        "units": False,
1953        "minimum": False,
1954        "maximum": False,
1955        "default": False,
1956    }
1957
1958
1959class DefinerProperty(Property):
1960    arg_types = {"this": True}
1961
1962
1963class DistKeyProperty(Property):
1964    arg_types = {"this": True}
1965
1966
1967class DistStyleProperty(Property):
1968    arg_types = {"this": True}
1969
1970
1971class EngineProperty(Property):
1972    arg_types = {"this": True}
1973
1974
1975class HeapProperty(Property):
1976    arg_types = {}
1977
1978
1979class ToTableProperty(Property):
1980    arg_types = {"this": True}
1981
1982
1983class ExecuteAsProperty(Property):
1984    arg_types = {"this": True}
1985
1986
1987class ExternalProperty(Property):
1988    arg_types = {"this": False}
1989
1990
1991class FallbackProperty(Property):
1992    arg_types = {"no": True, "protection": False}
1993
1994
1995class FileFormatProperty(Property):
1996    arg_types = {"this": True}
1997
1998
1999class FreespaceProperty(Property):
2000    arg_types = {"this": True, "percent": False}
2001
2002
2003class InputOutputFormat(Expression):
2004    arg_types = {"input_format": False, "output_format": False}
2005
2006
2007class IsolatedLoadingProperty(Property):
2008    arg_types = {
2009        "no": True,
2010        "concurrent": True,
2011        "for_all": True,
2012        "for_insert": True,
2013        "for_none": True,
2014    }
2015
2016
2017class JournalProperty(Property):
2018    arg_types = {
2019        "no": False,
2020        "dual": False,
2021        "before": False,
2022        "local": False,
2023        "after": False,
2024    }
2025
2026
2027class LanguageProperty(Property):
2028    arg_types = {"this": True}
2029
2030
2031# spark ddl
2032class ClusteredByProperty(Property):
2033    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
2034
2035
2036class DictProperty(Property):
2037    arg_types = {"this": True, "kind": True, "settings": False}
2038
2039
2040class DictSubProperty(Property):
2041    pass
2042
2043
2044class DictRange(Property):
2045    arg_types = {"this": True, "min": True, "max": True}
2046
2047
2048# Clickhouse CREATE ... ON CLUSTER modifier
2049# https://clickhouse.com/docs/en/sql-reference/distributed-ddl
2050class OnCluster(Property):
2051    arg_types = {"this": True}
2052
2053
2054class LikeProperty(Property):
2055    arg_types = {"this": True, "expressions": False}
2056
2057
2058class LocationProperty(Property):
2059    arg_types = {"this": True}
2060
2061
2062class LockingProperty(Property):
2063    arg_types = {
2064        "this": False,
2065        "kind": True,
2066        "for_or_in": True,
2067        "lock_type": True,
2068        "override": False,
2069    }
2070
2071
2072class LogProperty(Property):
2073    arg_types = {"no": True}
2074
2075
2076class MaterializedProperty(Property):
2077    arg_types = {"this": False}
2078
2079
2080class MergeBlockRatioProperty(Property):
2081    arg_types = {"this": False, "no": False, "default": False, "percent": False}
2082
2083
2084class NoPrimaryIndexProperty(Property):
2085    arg_types = {}
2086
2087
2088class OnProperty(Property):
2089    arg_types = {"this": True}
2090
2091
2092class OnCommitProperty(Property):
2093    arg_types = {"delete": False}
2094
2095
2096class PartitionedByProperty(Property):
2097    arg_types = {"this": True}
2098
2099
2100class ReturnsProperty(Property):
2101    arg_types = {"this": True, "is_table": False, "table": False}
2102
2103
2104class RowFormatProperty(Property):
2105    arg_types = {"this": True}
2106
2107
2108class RowFormatDelimitedProperty(Property):
2109    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2110    arg_types = {
2111        "fields": False,
2112        "escaped": False,
2113        "collection_items": False,
2114        "map_keys": False,
2115        "lines": False,
2116        "null": False,
2117        "serde": False,
2118    }
2119
2120
2121class RowFormatSerdeProperty(Property):
2122    arg_types = {"this": True, "serde_properties": False}
2123
2124
2125# https://spark.apache.org/docs/3.1.2/sql-ref-syntax-qry-select-transform.html
2126class QueryTransform(Expression):
2127    arg_types = {
2128        "expressions": True,
2129        "command_script": True,
2130        "schema": False,
2131        "row_format_before": False,
2132        "record_writer": False,
2133        "row_format_after": False,
2134        "record_reader": False,
2135    }
2136
2137
2138class SchemaCommentProperty(Property):
2139    arg_types = {"this": True}
2140
2141
2142class SerdeProperties(Property):
2143    arg_types = {"expressions": True}
2144
2145
2146class SetProperty(Property):
2147    arg_types = {"multi": True}
2148
2149
2150class SettingsProperty(Property):
2151    arg_types = {"expressions": True}
2152
2153
2154class SortKeyProperty(Property):
2155    arg_types = {"this": True, "compound": False}
2156
2157
2158class SqlSecurityProperty(Property):
2159    arg_types = {"definer": True}
2160
2161
2162class StabilityProperty(Property):
2163    arg_types = {"this": True}
2164
2165
2166class TemporaryProperty(Property):
2167    arg_types = {}
2168
2169
2170class TransientProperty(Property):
2171    arg_types = {"this": False}
2172
2173
2174class VolatileProperty(Property):
2175    arg_types = {"this": False}
2176
2177
2178class WithDataProperty(Property):
2179    arg_types = {"no": True, "statistics": False}
2180
2181
2182class WithJournalTableProperty(Property):
2183    arg_types = {"this": True}
2184
2185
2186class Properties(Expression):
2187    arg_types = {"expressions": True}
2188
2189    NAME_TO_PROPERTY = {
2190        "ALGORITHM": AlgorithmProperty,
2191        "AUTO_INCREMENT": AutoIncrementProperty,
2192        "CHARACTER SET": CharacterSetProperty,
2193        "CLUSTERED_BY": ClusteredByProperty,
2194        "COLLATE": CollateProperty,
2195        "COMMENT": SchemaCommentProperty,
2196        "DEFINER": DefinerProperty,
2197        "DISTKEY": DistKeyProperty,
2198        "DISTSTYLE": DistStyleProperty,
2199        "ENGINE": EngineProperty,
2200        "EXECUTE AS": ExecuteAsProperty,
2201        "FORMAT": FileFormatProperty,
2202        "LANGUAGE": LanguageProperty,
2203        "LOCATION": LocationProperty,
2204        "PARTITIONED_BY": PartitionedByProperty,
2205        "RETURNS": ReturnsProperty,
2206        "ROW_FORMAT": RowFormatProperty,
2207        "SORTKEY": SortKeyProperty,
2208    }
2209
2210    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2211
2212    # CREATE property locations
2213    # Form: schema specified
2214    #   create [POST_CREATE]
2215    #     table a [POST_NAME]
2216    #     (b int) [POST_SCHEMA]
2217    #     with ([POST_WITH])
2218    #     index (b) [POST_INDEX]
2219    #
2220    # Form: alias selection
2221    #   create [POST_CREATE]
2222    #     table a [POST_NAME]
2223    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2224    #     index (c) [POST_INDEX]
2225    class Location(AutoName):
2226        POST_CREATE = auto()
2227        POST_NAME = auto()
2228        POST_SCHEMA = auto()
2229        POST_WITH = auto()
2230        POST_ALIAS = auto()
2231        POST_EXPRESSION = auto()
2232        POST_INDEX = auto()
2233        UNSUPPORTED = auto()
2234
2235    @classmethod
2236    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2237        expressions = []
2238        for key, value in properties_dict.items():
2239            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2240            if property_cls:
2241                expressions.append(property_cls(this=convert(value)))
2242            else:
2243                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2244
2245        return cls(expressions=expressions)
2246
2247
2248class Qualify(Expression):
2249    pass
2250
2251
2252# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
2253class Return(Expression):
2254    pass
2255
2256
2257class Reference(Expression):
2258    arg_types = {"this": True, "expressions": False, "options": False}
2259
2260
2261class Tuple(Expression):
2262    arg_types = {"expressions": False}
2263
2264    def isin(
2265        self,
2266        *expressions: t.Any,
2267        query: t.Optional[ExpOrStr] = None,
2268        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2269        copy: bool = True,
2270        **opts,
2271    ) -> In:
2272        return In(
2273            this=maybe_copy(self, copy),
2274            expressions=[convert(e, copy=copy) for e in expressions],
2275            query=maybe_parse(query, copy=copy, **opts) if query else None,
2276            unnest=Unnest(
2277                expressions=[
2278                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2279                ]
2280            )
2281            if unnest
2282            else None,
2283        )
2284
2285
2286class Subqueryable(Unionable):
2287    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2288        """
2289        Convert this expression to an aliased expression that can be used as a Subquery.
2290
2291        Example:
2292            >>> subquery = Select().select("x").from_("tbl").subquery()
2293            >>> Select().select("x").from_(subquery).sql()
2294            'SELECT x FROM (SELECT x FROM tbl)'
2295
2296        Args:
2297            alias (str | Identifier): an optional alias for the subquery
2298            copy (bool): if `False`, modify this expression instance in-place.
2299
2300        Returns:
2301            Alias: the subquery
2302        """
2303        instance = maybe_copy(self, copy)
2304        if not isinstance(alias, Expression):
2305            alias = TableAlias(this=to_identifier(alias)) if alias else None
2306
2307        return Subquery(this=instance, alias=alias)
2308
2309    def limit(
2310        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2311    ) -> Select:
2312        raise NotImplementedError
2313
2314    @property
2315    def ctes(self):
2316        with_ = self.args.get("with")
2317        if not with_:
2318            return []
2319        return with_.expressions
2320
2321    @property
2322    def selects(self) -> t.List[Expression]:
2323        raise NotImplementedError("Subqueryable objects must implement `selects`")
2324
2325    @property
2326    def named_selects(self) -> t.List[str]:
2327        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2328
2329    def select(
2330        self,
2331        *expressions: t.Optional[ExpOrStr],
2332        append: bool = True,
2333        dialect: DialectType = None,
2334        copy: bool = True,
2335        **opts,
2336    ) -> Subqueryable:
2337        raise NotImplementedError("Subqueryable objects must implement `select`")
2338
2339    def with_(
2340        self,
2341        alias: ExpOrStr,
2342        as_: ExpOrStr,
2343        recursive: t.Optional[bool] = None,
2344        append: bool = True,
2345        dialect: DialectType = None,
2346        copy: bool = True,
2347        **opts,
2348    ) -> Subqueryable:
2349        """
2350        Append to or set the common table expressions.
2351
2352        Example:
2353            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2354            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2355
2356        Args:
2357            alias: the SQL code string to parse as the table name.
2358                If an `Expression` instance is passed, this is used as-is.
2359            as_: the SQL code string to parse as the table expression.
2360                If an `Expression` instance is passed, it will be used as-is.
2361            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2362            append: if `True`, add to any existing expressions.
2363                Otherwise, this resets the expressions.
2364            dialect: the dialect used to parse the input expression.
2365            copy: if `False`, modify this expression instance in-place.
2366            opts: other options to use to parse the input expressions.
2367
2368        Returns:
2369            The modified expression.
2370        """
2371        return _apply_cte_builder(
2372            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2373        )
2374
2375
2376QUERY_MODIFIERS = {
2377    "match": False,
2378    "laterals": False,
2379    "joins": False,
2380    "connect": False,
2381    "pivots": False,
2382    "where": False,
2383    "group": False,
2384    "having": False,
2385    "qualify": False,
2386    "windows": False,
2387    "distribute": False,
2388    "sort": False,
2389    "cluster": False,
2390    "order": False,
2391    "limit": False,
2392    "offset": False,
2393    "locks": False,
2394    "sample": False,
2395    "settings": False,
2396    "format": False,
2397}
2398
2399
2400# https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table?view=sql-server-ver16
2401class WithTableHint(Expression):
2402    arg_types = {"expressions": True}
2403
2404
2405# https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
2406class IndexTableHint(Expression):
2407    arg_types = {"this": True, "expressions": False, "target": False}
2408
2409
2410class Table(Expression):
2411    arg_types = {
2412        "this": True,
2413        "alias": False,
2414        "db": False,
2415        "catalog": False,
2416        "laterals": False,
2417        "joins": False,
2418        "pivots": False,
2419        "hints": False,
2420        "system_time": False,
2421        "version": False,
2422    }
2423
2424    @property
2425    def name(self) -> str:
2426        if isinstance(self.this, Func):
2427            return ""
2428        return self.this.name
2429
2430    @property
2431    def db(self) -> str:
2432        return self.text("db")
2433
2434    @property
2435    def catalog(self) -> str:
2436        return self.text("catalog")
2437
2438    @property
2439    def selects(self) -> t.List[Expression]:
2440        return []
2441
2442    @property
2443    def named_selects(self) -> t.List[str]:
2444        return []
2445
2446    @property
2447    def parts(self) -> t.List[Identifier]:
2448        """Return the parts of a table in order catalog, db, table."""
2449        parts: t.List[Identifier] = []
2450
2451        for arg in ("catalog", "db", "this"):
2452            part = self.args.get(arg)
2453
2454            if isinstance(part, Identifier):
2455                parts.append(part)
2456            elif isinstance(part, Dot):
2457                parts.extend(part.flatten())
2458
2459        return parts
2460
2461
2462class Union(Subqueryable):
2463    arg_types = {
2464        "with": False,
2465        "this": True,
2466        "expression": True,
2467        "distinct": False,
2468        "by_name": False,
2469        **QUERY_MODIFIERS,
2470    }
2471
2472    def limit(
2473        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2474    ) -> Select:
2475        """
2476        Set the LIMIT expression.
2477
2478        Example:
2479            >>> select("1").union(select("1")).limit(1).sql()
2480            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2481
2482        Args:
2483            expression: the SQL code string to parse.
2484                This can also be an integer.
2485                If a `Limit` instance is passed, this is used as-is.
2486                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2487            dialect: the dialect used to parse the input expression.
2488            copy: if `False`, modify this expression instance in-place.
2489            opts: other options to use to parse the input expressions.
2490
2491        Returns:
2492            The limited subqueryable.
2493        """
2494        return (
2495            select("*")
2496            .from_(self.subquery(alias="_l_0", copy=copy))
2497            .limit(expression, dialect=dialect, copy=False, **opts)
2498        )
2499
2500    def select(
2501        self,
2502        *expressions: t.Optional[ExpOrStr],
2503        append: bool = True,
2504        dialect: DialectType = None,
2505        copy: bool = True,
2506        **opts,
2507    ) -> Union:
2508        """Append to or set the SELECT of the union recursively.
2509
2510        Example:
2511            >>> from sqlglot import parse_one
2512            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2513            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2514
2515        Args:
2516            *expressions: the SQL code strings to parse.
2517                If an `Expression` instance is passed, it will be used as-is.
2518            append: if `True`, add to any existing expressions.
2519                Otherwise, this resets the expressions.
2520            dialect: the dialect used to parse the input expressions.
2521            copy: if `False`, modify this expression instance in-place.
2522            opts: other options to use to parse the input expressions.
2523
2524        Returns:
2525            Union: the modified expression.
2526        """
2527        this = self.copy() if copy else self
2528        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2529        this.expression.unnest().select(
2530            *expressions, append=append, dialect=dialect, copy=False, **opts
2531        )
2532        return this
2533
2534    @property
2535    def named_selects(self) -> t.List[str]:
2536        return self.this.unnest().named_selects
2537
2538    @property
2539    def is_star(self) -> bool:
2540        return self.this.is_star or self.expression.is_star
2541
2542    @property
2543    def selects(self) -> t.List[Expression]:
2544        return self.this.unnest().selects
2545
2546    @property
2547    def left(self):
2548        return self.this
2549
2550    @property
2551    def right(self):
2552        return self.expression
2553
2554
2555class Except(Union):
2556    pass
2557
2558
2559class Intersect(Union):
2560    pass
2561
2562
2563class Unnest(UDTF):
2564    arg_types = {
2565        "expressions": True,
2566        "ordinality": False,
2567        "alias": False,
2568        "offset": False,
2569    }
2570
2571
2572class Update(Expression):
2573    arg_types = {
2574        "with": False,
2575        "this": False,
2576        "expressions": True,
2577        "from": False,
2578        "where": False,
2579        "returning": False,
2580        "order": False,
2581        "limit": False,
2582    }
2583
2584
2585class Values(UDTF):
2586    arg_types = {
2587        "expressions": True,
2588        "ordinality": False,
2589        "alias": False,
2590    }
2591
2592
2593class Var(Expression):
2594    pass
2595
2596
2597class Version(Expression):
2598    """
2599    Time travel, iceberg, bigquery etc
2600    https://trino.io/docs/current/connector/iceberg.html?highlight=snapshot#using-snapshots
2601    https://www.databricks.com/blog/2019/02/04/introducing-delta-time-travel-for-large-scale-data-lakes.html
2602    https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#for_system_time_as_of
2603    https://learn.microsoft.com/en-us/sql/relational-databases/tables/querying-data-in-a-system-versioned-temporal-table?view=sql-server-ver16
2604    this is either TIMESTAMP or VERSION
2605    kind is ("AS OF", "BETWEEN")
2606    """
2607
2608    arg_types = {"this": True, "kind": True, "expression": False}
2609
2610
2611class Schema(Expression):
2612    arg_types = {"this": False, "expressions": False}
2613
2614
2615# https://dev.mysql.com/doc/refman/8.0/en/select.html
2616# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html
2617class Lock(Expression):
2618    arg_types = {"update": True, "expressions": False, "wait": False}
2619
2620
2621class Select(Subqueryable):
2622    arg_types = {
2623        "with": False,
2624        "kind": False,
2625        "expressions": False,
2626        "hint": False,
2627        "distinct": False,
2628        "into": False,
2629        "from": False,
2630        **QUERY_MODIFIERS,
2631    }
2632
2633    def from_(
2634        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2635    ) -> Select:
2636        """
2637        Set the FROM expression.
2638
2639        Example:
2640            >>> Select().from_("tbl").select("x").sql()
2641            'SELECT x FROM tbl'
2642
2643        Args:
2644            expression : the SQL code strings to parse.
2645                If a `From` instance is passed, this is used as-is.
2646                If another `Expression` instance is passed, it will be wrapped in a `From`.
2647            dialect: the dialect used to parse the input expression.
2648            copy: if `False`, modify this expression instance in-place.
2649            opts: other options to use to parse the input expressions.
2650
2651        Returns:
2652            The modified Select expression.
2653        """
2654        return _apply_builder(
2655            expression=expression,
2656            instance=self,
2657            arg="from",
2658            into=From,
2659            prefix="FROM",
2660            dialect=dialect,
2661            copy=copy,
2662            **opts,
2663        )
2664
2665    def group_by(
2666        self,
2667        *expressions: t.Optional[ExpOrStr],
2668        append: bool = True,
2669        dialect: DialectType = None,
2670        copy: bool = True,
2671        **opts,
2672    ) -> Select:
2673        """
2674        Set the GROUP BY expression.
2675
2676        Example:
2677            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2678            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2679
2680        Args:
2681            *expressions: the SQL code strings to parse.
2682                If a `Group` instance is passed, this is used as-is.
2683                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2684                If nothing is passed in then a group by is not applied to the expression
2685            append: if `True`, add to any existing expressions.
2686                Otherwise, this flattens all the `Group` expression into a single expression.
2687            dialect: the dialect used to parse the input expression.
2688            copy: if `False`, modify this expression instance in-place.
2689            opts: other options to use to parse the input expressions.
2690
2691        Returns:
2692            The modified Select expression.
2693        """
2694        if not expressions:
2695            return self if not copy else self.copy()
2696
2697        return _apply_child_list_builder(
2698            *expressions,
2699            instance=self,
2700            arg="group",
2701            append=append,
2702            copy=copy,
2703            prefix="GROUP BY",
2704            into=Group,
2705            dialect=dialect,
2706            **opts,
2707        )
2708
2709    def order_by(
2710        self,
2711        *expressions: t.Optional[ExpOrStr],
2712        append: bool = True,
2713        dialect: DialectType = None,
2714        copy: bool = True,
2715        **opts,
2716    ) -> Select:
2717        """
2718        Set the ORDER BY expression.
2719
2720        Example:
2721            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2722            'SELECT x FROM tbl ORDER BY x DESC'
2723
2724        Args:
2725            *expressions: the SQL code strings to parse.
2726                If a `Group` instance is passed, this is used as-is.
2727                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2728            append: if `True`, add to any existing expressions.
2729                Otherwise, this flattens all the `Order` expression into a single expression.
2730            dialect: the dialect used to parse the input expression.
2731            copy: if `False`, modify this expression instance in-place.
2732            opts: other options to use to parse the input expressions.
2733
2734        Returns:
2735            The modified Select expression.
2736        """
2737        return _apply_child_list_builder(
2738            *expressions,
2739            instance=self,
2740            arg="order",
2741            append=append,
2742            copy=copy,
2743            prefix="ORDER BY",
2744            into=Order,
2745            dialect=dialect,
2746            **opts,
2747        )
2748
2749    def sort_by(
2750        self,
2751        *expressions: t.Optional[ExpOrStr],
2752        append: bool = True,
2753        dialect: DialectType = None,
2754        copy: bool = True,
2755        **opts,
2756    ) -> Select:
2757        """
2758        Set the SORT BY expression.
2759
2760        Example:
2761            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2762            'SELECT x FROM tbl SORT BY x DESC'
2763
2764        Args:
2765            *expressions: the SQL code strings to parse.
2766                If a `Group` instance is passed, this is used as-is.
2767                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2768            append: if `True`, add to any existing expressions.
2769                Otherwise, this flattens all the `Order` expression into a single expression.
2770            dialect: the dialect used to parse the input expression.
2771            copy: if `False`, modify this expression instance in-place.
2772            opts: other options to use to parse the input expressions.
2773
2774        Returns:
2775            The modified Select expression.
2776        """
2777        return _apply_child_list_builder(
2778            *expressions,
2779            instance=self,
2780            arg="sort",
2781            append=append,
2782            copy=copy,
2783            prefix="SORT BY",
2784            into=Sort,
2785            dialect=dialect,
2786            **opts,
2787        )
2788
2789    def cluster_by(
2790        self,
2791        *expressions: t.Optional[ExpOrStr],
2792        append: bool = True,
2793        dialect: DialectType = None,
2794        copy: bool = True,
2795        **opts,
2796    ) -> Select:
2797        """
2798        Set the CLUSTER BY expression.
2799
2800        Example:
2801            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2802            'SELECT x FROM tbl CLUSTER BY x DESC'
2803
2804        Args:
2805            *expressions: the SQL code strings to parse.
2806                If a `Group` instance is passed, this is used as-is.
2807                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2808            append: if `True`, add to any existing expressions.
2809                Otherwise, this flattens all the `Order` expression into a single expression.
2810            dialect: the dialect used to parse the input expression.
2811            copy: if `False`, modify this expression instance in-place.
2812            opts: other options to use to parse the input expressions.
2813
2814        Returns:
2815            The modified Select expression.
2816        """
2817        return _apply_child_list_builder(
2818            *expressions,
2819            instance=self,
2820            arg="cluster",
2821            append=append,
2822            copy=copy,
2823            prefix="CLUSTER BY",
2824            into=Cluster,
2825            dialect=dialect,
2826            **opts,
2827        )
2828
2829    def limit(
2830        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2831    ) -> Select:
2832        """
2833        Set the LIMIT expression.
2834
2835        Example:
2836            >>> Select().from_("tbl").select("x").limit(10).sql()
2837            'SELECT x FROM tbl LIMIT 10'
2838
2839        Args:
2840            expression: the SQL code string to parse.
2841                This can also be an integer.
2842                If a `Limit` instance is passed, this is used as-is.
2843                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2844            dialect: the dialect used to parse the input expression.
2845            copy: if `False`, modify this expression instance in-place.
2846            opts: other options to use to parse the input expressions.
2847
2848        Returns:
2849            Select: the modified expression.
2850        """
2851        return _apply_builder(
2852            expression=expression,
2853            instance=self,
2854            arg="limit",
2855            into=Limit,
2856            prefix="LIMIT",
2857            dialect=dialect,
2858            copy=copy,
2859            **opts,
2860        )
2861
2862    def offset(
2863        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2864    ) -> Select:
2865        """
2866        Set the OFFSET expression.
2867
2868        Example:
2869            >>> Select().from_("tbl").select("x").offset(10).sql()
2870            'SELECT x FROM tbl OFFSET 10'
2871
2872        Args:
2873            expression: the SQL code string to parse.
2874                This can also be an integer.
2875                If a `Offset` instance is passed, this is used as-is.
2876                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2877            dialect: the dialect used to parse the input expression.
2878            copy: if `False`, modify this expression instance in-place.
2879            opts: other options to use to parse the input expressions.
2880
2881        Returns:
2882            The modified Select expression.
2883        """
2884        return _apply_builder(
2885            expression=expression,
2886            instance=self,
2887            arg="offset",
2888            into=Offset,
2889            prefix="OFFSET",
2890            dialect=dialect,
2891            copy=copy,
2892            **opts,
2893        )
2894
2895    def select(
2896        self,
2897        *expressions: t.Optional[ExpOrStr],
2898        append: bool = True,
2899        dialect: DialectType = None,
2900        copy: bool = True,
2901        **opts,
2902    ) -> Select:
2903        """
2904        Append to or set the SELECT expressions.
2905
2906        Example:
2907            >>> Select().select("x", "y").sql()
2908            'SELECT x, y'
2909
2910        Args:
2911            *expressions: the SQL code strings to parse.
2912                If an `Expression` instance is passed, it will be used as-is.
2913            append: if `True`, add to any existing expressions.
2914                Otherwise, this resets the expressions.
2915            dialect: the dialect used to parse the input expressions.
2916            copy: if `False`, modify this expression instance in-place.
2917            opts: other options to use to parse the input expressions.
2918
2919        Returns:
2920            The modified Select expression.
2921        """
2922        return _apply_list_builder(
2923            *expressions,
2924            instance=self,
2925            arg="expressions",
2926            append=append,
2927            dialect=dialect,
2928            copy=copy,
2929            **opts,
2930        )
2931
2932    def lateral(
2933        self,
2934        *expressions: t.Optional[ExpOrStr],
2935        append: bool = True,
2936        dialect: DialectType = None,
2937        copy: bool = True,
2938        **opts,
2939    ) -> Select:
2940        """
2941        Append to or set the LATERAL expressions.
2942
2943        Example:
2944            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2945            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2946
2947        Args:
2948            *expressions: the SQL code strings to parse.
2949                If an `Expression` instance is passed, it will be used as-is.
2950            append: if `True`, add to any existing expressions.
2951                Otherwise, this resets the expressions.
2952            dialect: the dialect used to parse the input expressions.
2953            copy: if `False`, modify this expression instance in-place.
2954            opts: other options to use to parse the input expressions.
2955
2956        Returns:
2957            The modified Select expression.
2958        """
2959        return _apply_list_builder(
2960            *expressions,
2961            instance=self,
2962            arg="laterals",
2963            append=append,
2964            into=Lateral,
2965            prefix="LATERAL VIEW",
2966            dialect=dialect,
2967            copy=copy,
2968            **opts,
2969        )
2970
2971    def join(
2972        self,
2973        expression: ExpOrStr,
2974        on: t.Optional[ExpOrStr] = None,
2975        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
2976        append: bool = True,
2977        join_type: t.Optional[str] = None,
2978        join_alias: t.Optional[Identifier | str] = None,
2979        dialect: DialectType = None,
2980        copy: bool = True,
2981        **opts,
2982    ) -> Select:
2983        """
2984        Append to or set the JOIN expressions.
2985
2986        Example:
2987            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2988            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2989
2990            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2991            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2992
2993            Use `join_type` to change the type of join:
2994
2995            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2996            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2997
2998        Args:
2999            expression: the SQL code string to parse.
3000                If an `Expression` instance is passed, it will be used as-is.
3001            on: optionally specify the join "on" criteria as a SQL string.
3002                If an `Expression` instance is passed, it will be used as-is.
3003            using: optionally specify the join "using" criteria as a SQL string.
3004                If an `Expression` instance is passed, it will be used as-is.
3005            append: if `True`, add to any existing expressions.
3006                Otherwise, this resets the expressions.
3007            join_type: if set, alter the parsed join type.
3008            join_alias: an optional alias for the joined source.
3009            dialect: the dialect used to parse the input expressions.
3010            copy: if `False`, modify this expression instance in-place.
3011            opts: other options to use to parse the input expressions.
3012
3013        Returns:
3014            Select: the modified expression.
3015        """
3016        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
3017
3018        try:
3019            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
3020        except ParseError:
3021            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
3022
3023        join = expression if isinstance(expression, Join) else Join(this=expression)
3024
3025        if isinstance(join.this, Select):
3026            join.this.replace(join.this.subquery())
3027
3028        if join_type:
3029            method: t.Optional[Token]
3030            side: t.Optional[Token]
3031            kind: t.Optional[Token]
3032
3033            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
3034
3035            if method:
3036                join.set("method", method.text)
3037            if side:
3038                join.set("side", side.text)
3039            if kind:
3040                join.set("kind", kind.text)
3041
3042        if on:
3043            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
3044            join.set("on", on)
3045
3046        if using:
3047            join = _apply_list_builder(
3048                *ensure_list(using),
3049                instance=join,
3050                arg="using",
3051                append=append,
3052                copy=copy,
3053                into=Identifier,
3054                **opts,
3055            )
3056
3057        if join_alias:
3058            join.set("this", alias_(join.this, join_alias, table=True))
3059
3060        return _apply_list_builder(
3061            join,
3062            instance=self,
3063            arg="joins",
3064            append=append,
3065            copy=copy,
3066            **opts,
3067        )
3068
3069    def where(
3070        self,
3071        *expressions: t.Optional[ExpOrStr],
3072        append: bool = True,
3073        dialect: DialectType = None,
3074        copy: bool = True,
3075        **opts,
3076    ) -> Select:
3077        """
3078        Append to or set the WHERE expressions.
3079
3080        Example:
3081            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3082            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3083
3084        Args:
3085            *expressions: the SQL code strings to parse.
3086                If an `Expression` instance is passed, it will be used as-is.
3087                Multiple expressions are combined with an AND operator.
3088            append: if `True`, AND the new expressions to any existing expression.
3089                Otherwise, this resets the expression.
3090            dialect: the dialect used to parse the input expressions.
3091            copy: if `False`, modify this expression instance in-place.
3092            opts: other options to use to parse the input expressions.
3093
3094        Returns:
3095            Select: the modified expression.
3096        """
3097        return _apply_conjunction_builder(
3098            *expressions,
3099            instance=self,
3100            arg="where",
3101            append=append,
3102            into=Where,
3103            dialect=dialect,
3104            copy=copy,
3105            **opts,
3106        )
3107
3108    def having(
3109        self,
3110        *expressions: t.Optional[ExpOrStr],
3111        append: bool = True,
3112        dialect: DialectType = None,
3113        copy: bool = True,
3114        **opts,
3115    ) -> Select:
3116        """
3117        Append to or set the HAVING expressions.
3118
3119        Example:
3120            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3121            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3122
3123        Args:
3124            *expressions: the SQL code strings to parse.
3125                If an `Expression` instance is passed, it will be used as-is.
3126                Multiple expressions are combined with an AND operator.
3127            append: if `True`, AND the new expressions to any existing expression.
3128                Otherwise, this resets the expression.
3129            dialect: the dialect used to parse the input expressions.
3130            copy: if `False`, modify this expression instance in-place.
3131            opts: other options to use to parse the input expressions.
3132
3133        Returns:
3134            The modified Select expression.
3135        """
3136        return _apply_conjunction_builder(
3137            *expressions,
3138            instance=self,
3139            arg="having",
3140            append=append,
3141            into=Having,
3142            dialect=dialect,
3143            copy=copy,
3144            **opts,
3145        )
3146
3147    def window(
3148        self,
3149        *expressions: t.Optional[ExpOrStr],
3150        append: bool = True,
3151        dialect: DialectType = None,
3152        copy: bool = True,
3153        **opts,
3154    ) -> Select:
3155        return _apply_list_builder(
3156            *expressions,
3157            instance=self,
3158            arg="windows",
3159            append=append,
3160            into=Window,
3161            dialect=dialect,
3162            copy=copy,
3163            **opts,
3164        )
3165
3166    def qualify(
3167        self,
3168        *expressions: t.Optional[ExpOrStr],
3169        append: bool = True,
3170        dialect: DialectType = None,
3171        copy: bool = True,
3172        **opts,
3173    ) -> Select:
3174        return _apply_conjunction_builder(
3175            *expressions,
3176            instance=self,
3177            arg="qualify",
3178            append=append,
3179            into=Qualify,
3180            dialect=dialect,
3181            copy=copy,
3182            **opts,
3183        )
3184
3185    def distinct(
3186        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3187    ) -> Select:
3188        """
3189        Set the OFFSET expression.
3190
3191        Example:
3192            >>> Select().from_("tbl").select("x").distinct().sql()
3193            'SELECT DISTINCT x FROM tbl'
3194
3195        Args:
3196            ons: the expressions to distinct on
3197            distinct: whether the Select should be distinct
3198            copy: if `False`, modify this expression instance in-place.
3199
3200        Returns:
3201            Select: the modified expression.
3202        """
3203        instance = maybe_copy(self, copy)
3204        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3205        instance.set("distinct", Distinct(on=on) if distinct else None)
3206        return instance
3207
3208    def ctas(
3209        self,
3210        table: ExpOrStr,
3211        properties: t.Optional[t.Dict] = None,
3212        dialect: DialectType = None,
3213        copy: bool = True,
3214        **opts,
3215    ) -> Create:
3216        """
3217        Convert this expression to a CREATE TABLE AS statement.
3218
3219        Example:
3220            >>> Select().select("*").from_("tbl").ctas("x").sql()
3221            'CREATE TABLE x AS SELECT * FROM tbl'
3222
3223        Args:
3224            table: the SQL code string to parse as the table name.
3225                If another `Expression` instance is passed, it will be used as-is.
3226            properties: an optional mapping of table properties
3227            dialect: the dialect used to parse the input table.
3228            copy: if `False`, modify this expression instance in-place.
3229            opts: other options to use to parse the input table.
3230
3231        Returns:
3232            The new Create expression.
3233        """
3234        instance = maybe_copy(self, copy)
3235        table_expression = maybe_parse(
3236            table,
3237            into=Table,
3238            dialect=dialect,
3239            **opts,
3240        )
3241        properties_expression = None
3242        if properties:
3243            properties_expression = Properties.from_dict(properties)
3244
3245        return Create(
3246            this=table_expression,
3247            kind="table",
3248            expression=instance,
3249            properties=properties_expression,
3250        )
3251
3252    def lock(self, update: bool = True, copy: bool = True) -> Select:
3253        """
3254        Set the locking read mode for this expression.
3255
3256        Examples:
3257            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3258            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3259
3260            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3261            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3262
3263        Args:
3264            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3265            copy: if `False`, modify this expression instance in-place.
3266
3267        Returns:
3268            The modified expression.
3269        """
3270        inst = maybe_copy(self, copy)
3271        inst.set("locks", [Lock(update=update)])
3272
3273        return inst
3274
3275    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3276        """
3277        Set hints for this expression.
3278
3279        Examples:
3280            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3281            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3282
3283        Args:
3284            hints: The SQL code strings to parse as the hints.
3285                If an `Expression` instance is passed, it will be used as-is.
3286            dialect: The dialect used to parse the hints.
3287            copy: If `False`, modify this expression instance in-place.
3288
3289        Returns:
3290            The modified expression.
3291        """
3292        inst = maybe_copy(self, copy)
3293        inst.set(
3294            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3295        )
3296
3297        return inst
3298
3299    @property
3300    def named_selects(self) -> t.List[str]:
3301        return [e.output_name for e in self.expressions if e.alias_or_name]
3302
3303    @property
3304    def is_star(self) -> bool:
3305        return any(expression.is_star for expression in self.expressions)
3306
3307    @property
3308    def selects(self) -> t.List[Expression]:
3309        return self.expressions
3310
3311
3312class Subquery(DerivedTable, Unionable):
3313    arg_types = {
3314        "this": True,
3315        "alias": False,
3316        "with": False,
3317        **QUERY_MODIFIERS,
3318    }
3319
3320    def unnest(self):
3321        """
3322        Returns the first non subquery.
3323        """
3324        expression = self
3325        while isinstance(expression, Subquery):
3326            expression = expression.this
3327        return expression
3328
3329    def unwrap(self) -> Subquery:
3330        expression = self
3331        while expression.same_parent and expression.is_wrapper:
3332            expression = t.cast(Subquery, expression.parent)
3333        return expression
3334
3335    @property
3336    def is_wrapper(self) -> bool:
3337        """
3338        Whether this Subquery acts as a simple wrapper around another expression.
3339
3340        SELECT * FROM (((SELECT * FROM t)))
3341                      ^
3342                      This corresponds to a "wrapper" Subquery node
3343        """
3344        return all(v is None for k, v in self.args.items() if k != "this")
3345
3346    @property
3347    def is_star(self) -> bool:
3348        return self.this.is_star
3349
3350    @property
3351    def output_name(self) -> str:
3352        return self.alias
3353
3354
3355class TableSample(Expression):
3356    arg_types = {
3357        "this": False,
3358        "expressions": False,
3359        "method": False,
3360        "bucket_numerator": False,
3361        "bucket_denominator": False,
3362        "bucket_field": False,
3363        "percent": False,
3364        "rows": False,
3365        "size": False,
3366        "seed": False,
3367        "kind": False,
3368    }
3369
3370
3371class Tag(Expression):
3372    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3373
3374    arg_types = {
3375        "this": False,
3376        "prefix": False,
3377        "postfix": False,
3378    }
3379
3380
3381# Represents both the standard SQL PIVOT operator and DuckDB's "simplified" PIVOT syntax
3382# https://duckdb.org/docs/sql/statements/pivot
3383class Pivot(Expression):
3384    arg_types = {
3385        "this": False,
3386        "alias": False,
3387        "expressions": True,
3388        "field": False,
3389        "unpivot": False,
3390        "using": False,
3391        "group": False,
3392        "columns": False,
3393        "include_nulls": False,
3394    }
3395
3396
3397class Window(Condition):
3398    arg_types = {
3399        "this": True,
3400        "partition_by": False,
3401        "order": False,
3402        "spec": False,
3403        "alias": False,
3404        "over": False,
3405        "first": False,
3406    }
3407
3408
3409class WindowSpec(Expression):
3410    arg_types = {
3411        "kind": False,
3412        "start": False,
3413        "start_side": False,
3414        "end": False,
3415        "end_side": False,
3416    }
3417
3418
3419class Where(Expression):
3420    pass
3421
3422
3423class Star(Expression):
3424    arg_types = {"except": False, "replace": False}
3425
3426    @property
3427    def name(self) -> str:
3428        return "*"
3429
3430    @property
3431    def output_name(self) -> str:
3432        return self.name
3433
3434
3435class Parameter(Condition):
3436    arg_types = {"this": True, "wrapped": False}
3437
3438
3439class SessionParameter(Condition):
3440    arg_types = {"this": True, "kind": False}
3441
3442
3443class Placeholder(Condition):
3444    arg_types = {"this": False, "kind": False}
3445
3446
3447class Null(Condition):
3448    arg_types: t.Dict[str, t.Any] = {}
3449
3450    @property
3451    def name(self) -> str:
3452        return "NULL"
3453
3454
3455class Boolean(Condition):
3456    pass
3457
3458
3459class DataTypeParam(Expression):
3460    arg_types = {"this": True, "expression": False}
3461
3462
3463class DataType(Expression):
3464    arg_types = {
3465        "this": True,
3466        "expressions": False,
3467        "nested": False,
3468        "values": False,
3469        "prefix": False,
3470        "kind": False,
3471    }
3472
3473    class Type(AutoName):
3474        ARRAY = auto()
3475        BIGDECIMAL = auto()
3476        BIGINT = auto()
3477        BIGSERIAL = auto()
3478        BINARY = auto()
3479        BIT = auto()
3480        BOOLEAN = auto()
3481        CHAR = auto()
3482        DATE = auto()
3483        DATEMULTIRANGE = auto()
3484        DATERANGE = auto()
3485        DATETIME = auto()
3486        DATETIME64 = auto()
3487        DECIMAL = auto()
3488        DOUBLE = auto()
3489        ENUM = auto()
3490        ENUM8 = auto()
3491        ENUM16 = auto()
3492        FIXEDSTRING = auto()
3493        FLOAT = auto()
3494        GEOGRAPHY = auto()
3495        GEOMETRY = auto()
3496        HLLSKETCH = auto()
3497        HSTORE = auto()
3498        IMAGE = auto()
3499        INET = auto()
3500        INT = auto()
3501        INT128 = auto()
3502        INT256 = auto()
3503        INT4MULTIRANGE = auto()
3504        INT4RANGE = auto()
3505        INT8MULTIRANGE = auto()
3506        INT8RANGE = auto()
3507        INTERVAL = auto()
3508        IPADDRESS = auto()
3509        IPPREFIX = auto()
3510        JSON = auto()
3511        JSONB = auto()
3512        LONGBLOB = auto()
3513        LONGTEXT = auto()
3514        LOWCARDINALITY = auto()
3515        MAP = auto()
3516        MEDIUMBLOB = auto()
3517        MEDIUMINT = auto()
3518        MEDIUMTEXT = auto()
3519        MONEY = auto()
3520        NCHAR = auto()
3521        NESTED = auto()
3522        NULL = auto()
3523        NULLABLE = auto()
3524        NUMMULTIRANGE = auto()
3525        NUMRANGE = auto()
3526        NVARCHAR = auto()
3527        OBJECT = auto()
3528        ROWVERSION = auto()
3529        SERIAL = auto()
3530        SET = auto()
3531        SMALLINT = auto()
3532        SMALLMONEY = auto()
3533        SMALLSERIAL = auto()
3534        STRUCT = auto()
3535        SUPER = auto()
3536        TEXT = auto()
3537        TINYBLOB = auto()
3538        TINYTEXT = auto()
3539        TIME = auto()
3540        TIMETZ = auto()
3541        TIMESTAMP = auto()
3542        TIMESTAMPLTZ = auto()
3543        TIMESTAMPTZ = auto()
3544        TINYINT = auto()
3545        TSMULTIRANGE = auto()
3546        TSRANGE = auto()
3547        TSTZMULTIRANGE = auto()
3548        TSTZRANGE = auto()
3549        UBIGINT = auto()
3550        UINT = auto()
3551        UINT128 = auto()
3552        UINT256 = auto()
3553        UMEDIUMINT = auto()
3554        UNIQUEIDENTIFIER = auto()
3555        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3556        USERDEFINED = "USER-DEFINED"
3557        USMALLINT = auto()
3558        UTINYINT = auto()
3559        UUID = auto()
3560        VARBINARY = auto()
3561        VARCHAR = auto()
3562        VARIANT = auto()
3563        XML = auto()
3564        YEAR = auto()
3565
3566    TEXT_TYPES = {
3567        Type.CHAR,
3568        Type.NCHAR,
3569        Type.VARCHAR,
3570        Type.NVARCHAR,
3571        Type.TEXT,
3572    }
3573
3574    INTEGER_TYPES = {
3575        Type.INT,
3576        Type.TINYINT,
3577        Type.SMALLINT,
3578        Type.BIGINT,
3579        Type.INT128,
3580        Type.INT256,
3581    }
3582
3583    FLOAT_TYPES = {
3584        Type.FLOAT,
3585        Type.DOUBLE,
3586    }
3587
3588    NUMERIC_TYPES = {
3589        *INTEGER_TYPES,
3590        *FLOAT_TYPES,
3591    }
3592
3593    TEMPORAL_TYPES = {
3594        Type.TIME,
3595        Type.TIMETZ,
3596        Type.TIMESTAMP,
3597        Type.TIMESTAMPTZ,
3598        Type.TIMESTAMPLTZ,
3599        Type.DATE,
3600        Type.DATETIME,
3601        Type.DATETIME64,
3602    }
3603
3604    @classmethod
3605    def build(
3606        cls,
3607        dtype: str | DataType | DataType.Type,
3608        dialect: DialectType = None,
3609        udt: bool = False,
3610        **kwargs,
3611    ) -> DataType:
3612        """
3613        Constructs a DataType object.
3614
3615        Args:
3616            dtype: the data type of interest.
3617            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3618            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3619                DataType, thus creating a user-defined type.
3620            kawrgs: additional arguments to pass in the constructor of DataType.
3621
3622        Returns:
3623            The constructed DataType object.
3624        """
3625        from sqlglot import parse_one
3626
3627        if isinstance(dtype, str):
3628            if dtype.upper() == "UNKNOWN":
3629                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3630
3631            try:
3632                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3633            except ParseError:
3634                if udt:
3635                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3636                raise
3637        elif isinstance(dtype, DataType.Type):
3638            data_type_exp = DataType(this=dtype)
3639        elif isinstance(dtype, DataType):
3640            return dtype
3641        else:
3642            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3643
3644        return DataType(**{**data_type_exp.args, **kwargs})
3645
3646    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3647        """
3648        Checks whether this DataType matches one of the provided data types. Nested types or precision
3649        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3650
3651        Args:
3652            dtypes: the data types to compare this DataType to.
3653
3654        Returns:
3655            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3656        """
3657        for dtype in dtypes:
3658            other = DataType.build(dtype, udt=True)
3659
3660            if (
3661                other.expressions
3662                or self.this == DataType.Type.USERDEFINED
3663                or other.this == DataType.Type.USERDEFINED
3664            ):
3665                matches = self == other
3666            else:
3667                matches = self.this == other.this
3668
3669            if matches:
3670                return True
3671        return False
3672
3673
3674# https://www.postgresql.org/docs/15/datatype-pseudo.html
3675class PseudoType(Expression):
3676    pass
3677
3678
3679# https://www.postgresql.org/docs/15/datatype-oid.html
3680class ObjectIdentifier(Expression):
3681    pass
3682
3683
3684# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
3685class SubqueryPredicate(Predicate):
3686    pass
3687
3688
3689class All(SubqueryPredicate):
3690    pass
3691
3692
3693class Any(SubqueryPredicate):
3694    pass
3695
3696
3697class Exists(SubqueryPredicate):
3698    pass
3699
3700
3701# Commands to interact with the databases or engines. For most of the command
3702# expressions we parse whatever comes after the command's name as a string.
3703class Command(Expression):
3704    arg_types = {"this": True, "expression": False}
3705
3706
3707class Transaction(Expression):
3708    arg_types = {"this": False, "modes": False, "mark": False}
3709
3710
3711class Commit(Expression):
3712    arg_types = {"chain": False, "this": False, "durability": False}
3713
3714
3715class Rollback(Expression):
3716    arg_types = {"savepoint": False, "this": False}
3717
3718
3719class AlterTable(Expression):
3720    arg_types = {"this": True, "actions": True, "exists": False, "only": False}
3721
3722
3723class AddConstraint(Expression):
3724    arg_types = {"this": False, "expression": False, "enforced": False}
3725
3726
3727class DropPartition(Expression):
3728    arg_types = {"expressions": True, "exists": False}
3729
3730
3731# Binary expressions like (ADD a b)
3732class Binary(Condition):
3733    arg_types = {"this": True, "expression": True}
3734
3735    @property
3736    def left(self):
3737        return self.this
3738
3739    @property
3740    def right(self):
3741        return self.expression
3742
3743
3744class Add(Binary):
3745    pass
3746
3747
3748class Connector(Binary):
3749    pass
3750
3751
3752class And(Connector):
3753    pass
3754
3755
3756class Or(Connector):
3757    pass
3758
3759
3760class BitwiseAnd(Binary):
3761    pass
3762
3763
3764class BitwiseLeftShift(Binary):
3765    pass
3766
3767
3768class BitwiseOr(Binary):
3769    pass
3770
3771
3772class BitwiseRightShift(Binary):
3773    pass
3774
3775
3776class BitwiseXor(Binary):
3777    pass
3778
3779
3780class Div(Binary):
3781    pass
3782
3783
3784class Overlaps(Binary):
3785    pass
3786
3787
3788class Dot(Binary):
3789    @property
3790    def name(self) -> str:
3791        return self.expression.name
3792
3793    @property
3794    def output_name(self) -> str:
3795        return self.name
3796
3797    @classmethod
3798    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3799        """Build a Dot object with a sequence of expressions."""
3800        if len(expressions) < 2:
3801            raise ValueError(f"Dot requires >= 2 expressions.")
3802
3803        return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))
3804
3805
3806class DPipe(Binary):
3807    pass
3808
3809
3810class SafeDPipe(DPipe):
3811    pass
3812
3813
3814class EQ(Binary, Predicate):
3815    pass
3816
3817
3818class NullSafeEQ(Binary, Predicate):
3819    pass
3820
3821
3822class NullSafeNEQ(Binary, Predicate):
3823    pass
3824
3825
3826class Distance(Binary):
3827    pass
3828
3829
3830class Escape(Binary):
3831    pass
3832
3833
3834class Glob(Binary, Predicate):
3835    pass
3836
3837
3838class GT(Binary, Predicate):
3839    pass
3840
3841
3842class GTE(Binary, Predicate):
3843    pass
3844
3845
3846class ILike(Binary, Predicate):
3847    pass
3848
3849
3850class ILikeAny(Binary, Predicate):
3851    pass
3852
3853
3854class IntDiv(Binary):
3855    pass
3856
3857
3858class Is(Binary, Predicate):
3859    pass
3860
3861
3862class Kwarg(Binary):
3863    """Kwarg in special functions like func(kwarg => y)."""
3864
3865
3866class Like(Binary, Predicate):
3867    pass
3868
3869
3870class LikeAny(Binary, Predicate):
3871    pass
3872
3873
3874class LT(Binary, Predicate):
3875    pass
3876
3877
3878class LTE(Binary, Predicate):
3879    pass
3880
3881
3882class Mod(Binary):
3883    pass
3884
3885
3886class Mul(Binary):
3887    pass
3888
3889
3890class NEQ(Binary, Predicate):
3891    pass
3892
3893
3894class SimilarTo(Binary, Predicate):
3895    pass
3896
3897
3898class Slice(Binary):
3899    arg_types = {"this": False, "expression": False}
3900
3901
3902class Sub(Binary):
3903    pass
3904
3905
3906class ArrayOverlaps(Binary):
3907    pass
3908
3909
3910# Unary Expressions
3911# (NOT a)
3912class Unary(Condition):
3913    pass
3914
3915
3916class BitwiseNot(Unary):
3917    pass
3918
3919
3920class Not(Unary):
3921    pass
3922
3923
3924class Paren(Unary):
3925    arg_types = {"this": True, "with": False}
3926
3927    @property
3928    def output_name(self) -> str:
3929        return self.this.name
3930
3931
3932class Neg(Unary):
3933    pass
3934
3935
3936class Alias(Expression):
3937    arg_types = {"this": True, "alias": False}
3938
3939    @property
3940    def output_name(self) -> str:
3941        return self.alias
3942
3943
3944class Aliases(Expression):
3945    arg_types = {"this": True, "expressions": True}
3946
3947    @property
3948    def aliases(self):
3949        return self.expressions
3950
3951
3952class AtTimeZone(Expression):
3953    arg_types = {"this": True, "zone": True}
3954
3955
3956class Between(Predicate):
3957    arg_types = {"this": True, "low": True, "high": True}
3958
3959
3960class Bracket(Condition):
3961    arg_types = {"this": True, "expressions": True}
3962
3963    @property
3964    def output_name(self) -> str:
3965        if len(self.expressions) == 1:
3966            return self.expressions[0].output_name
3967
3968        return super().output_name
3969
3970
3971class SafeBracket(Bracket):
3972    """Represents array lookup where OOB index yields NULL instead of causing a failure."""
3973
3974
3975class Distinct(Expression):
3976    arg_types = {"expressions": False, "on": False}
3977
3978
3979class In(Predicate):
3980    arg_types = {
3981        "this": True,
3982        "expressions": False,
3983        "query": False,
3984        "unnest": False,
3985        "field": False,
3986        "is_global": False,
3987    }
3988
3989
3990class TimeUnit(Expression):
3991    """Automatically converts unit arg into a var."""
3992
3993    arg_types = {"unit": False}
3994
3995    def __init__(self, **args):
3996        unit = args.get("unit")
3997        if isinstance(unit, (Column, Literal)):
3998            args["unit"] = Var(this=unit.name)
3999        elif isinstance(unit, Week):
4000            unit.set("this", Var(this=unit.this.name))
4001
4002        super().__init__(**args)
4003
4004
4005# https://www.oracletutorial.com/oracle-basics/oracle-interval/
4006# https://trino.io/docs/current/language/types.html#interval-day-to-second
4007# https://docs.databricks.com/en/sql/language-manual/data-types/interval-type.html
4008class IntervalSpan(Expression):
4009    arg_types = {"this": True, "expression": True}
4010
4011
4012class Interval(TimeUnit):
4013    arg_types = {"this": False, "unit": False}
4014
4015    @property
4016    def unit(self) -> t.Optional[Var]:
4017        return self.args.get("unit")
4018
4019
4020class IgnoreNulls(Expression):
4021    pass
4022
4023
4024class RespectNulls(Expression):
4025    pass
4026
4027
4028# Functions
4029class Func(Condition):
4030    """
4031    The base class for all function expressions.
4032
4033    Attributes:
4034        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
4035            treated as a variable length argument and the argument's value will be stored as a list.
4036        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
4037            for this function expression. These values are used to map this node to a name during parsing
4038            as well as to provide the function's name during SQL string generation. By default the SQL
4039            name is set to the expression's class name transformed to snake case.
4040    """
4041
4042    is_var_len_args = False
4043
4044    @classmethod
4045    def from_arg_list(cls, args):
4046        if cls.is_var_len_args:
4047            all_arg_keys = list(cls.arg_types)
4048            # If this function supports variable length argument treat the last argument as such.
4049            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4050            num_non_var = len(non_var_len_arg_keys)
4051
4052            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4053            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4054        else:
4055            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4056
4057        return cls(**args_dict)
4058
4059    @classmethod
4060    def sql_names(cls):
4061        if cls is Func:
4062            raise NotImplementedError(
4063                "SQL name is only supported by concrete function implementations"
4064            )
4065        if "_sql_names" not in cls.__dict__:
4066            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4067        return cls._sql_names
4068
4069    @classmethod
4070    def sql_name(cls):
4071        return cls.sql_names()[0]
4072
4073    @classmethod
4074    def default_parser_mappings(cls):
4075        return {name: cls.from_arg_list for name in cls.sql_names()}
4076
4077
4078class AggFunc(Func):
4079    pass
4080
4081
4082class ParameterizedAgg(AggFunc):
4083    arg_types = {"this": True, "expressions": True, "params": True}
4084
4085
4086class Abs(Func):
4087    pass
4088
4089
4090# https://spark.apache.org/docs/latest/api/sql/index.html#transform
4091class Transform(Func):
4092    arg_types = {"this": True, "expression": True}
4093
4094
4095class Anonymous(Func):
4096    arg_types = {"this": True, "expressions": False}
4097    is_var_len_args = True
4098
4099
4100# https://docs.snowflake.com/en/sql-reference/functions/hll
4101# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
4102class Hll(AggFunc):
4103    arg_types = {"this": True, "expressions": False}
4104    is_var_len_args = True
4105
4106
4107class ApproxDistinct(AggFunc):
4108    arg_types = {"this": True, "accuracy": False}
4109    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
4110
4111
4112class Array(Func):
4113    arg_types = {"expressions": False}
4114    is_var_len_args = True
4115
4116
4117# https://docs.snowflake.com/en/sql-reference/functions/to_char
4118class ToChar(Func):
4119    arg_types = {"this": True, "format": False}
4120
4121
4122class GenerateSeries(Func):
4123    arg_types = {"start": True, "end": True, "step": False}
4124
4125
4126class ArrayAgg(AggFunc):
4127    pass
4128
4129
4130class ArrayAll(Func):
4131    arg_types = {"this": True, "expression": True}
4132
4133
4134class ArrayAny(Func):
4135    arg_types = {"this": True, "expression": True}
4136
4137
4138class ArrayConcat(Func):
4139    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4140    arg_types = {"this": True, "expressions": False}
4141    is_var_len_args = True
4142
4143
4144class ArrayContains(Binary, Func):
4145    pass
4146
4147
4148class ArrayContained(Binary):
4149    pass
4150
4151
4152class ArrayFilter(Func):
4153    arg_types = {"this": True, "expression": True}
4154    _sql_names = ["FILTER", "ARRAY_FILTER"]
4155
4156
4157class ArrayJoin(Func):
4158    arg_types = {"this": True, "expression": True, "null": False}
4159
4160
4161class ArraySize(Func):
4162    arg_types = {"this": True, "expression": False}
4163
4164
4165class ArraySort(Func):
4166    arg_types = {"this": True, "expression": False}
4167
4168
4169class ArraySum(Func):
4170    pass
4171
4172
4173class ArrayUnionAgg(AggFunc):
4174    pass
4175
4176
4177class Avg(AggFunc):
4178    pass
4179
4180
4181class AnyValue(AggFunc):
4182    arg_types = {"this": True, "having": False, "max": False, "ignore_nulls": False}
4183
4184
4185class First(Func):
4186    arg_types = {"this": True, "ignore_nulls": False}
4187
4188
4189class Last(Func):
4190    arg_types = {"this": True, "ignore_nulls": False}
4191
4192
4193class Case(Func):
4194    arg_types = {"this": False, "ifs": True, "default": False}
4195
4196    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4197        instance = maybe_copy(self, copy)
4198        instance.append(
4199            "ifs",
4200            If(
4201                this=maybe_parse(condition, copy=copy, **opts),
4202                true=maybe_parse(then, copy=copy, **opts),
4203            ),
4204        )
4205        return instance
4206
4207    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4208        instance = maybe_copy(self, copy)
4209        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4210        return instance
4211
4212
4213class Cast(Func):
4214    arg_types = {"this": True, "to": True, "format": False}
4215
4216    @property
4217    def name(self) -> str:
4218        return self.this.name
4219
4220    @property
4221    def to(self) -> DataType:
4222        return self.args["to"]
4223
4224    @property
4225    def output_name(self) -> str:
4226        return self.name
4227
4228    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4229        """
4230        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4231        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4232        array<int> != array<float>.
4233
4234        Args:
4235            dtypes: the data types to compare this Cast's DataType to.
4236
4237        Returns:
4238            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4239        """
4240        return self.to.is_type(*dtypes)
4241
4242
4243class TryCast(Cast):
4244    pass
4245
4246
4247class CastToStrType(Func):
4248    arg_types = {"this": True, "to": True}
4249
4250
4251class Collate(Binary):
4252    pass
4253
4254
4255class Ceil(Func):
4256    arg_types = {"this": True, "decimals": False}
4257    _sql_names = ["CEIL", "CEILING"]
4258
4259
4260class Coalesce(Func):
4261    arg_types = {"this": True, "expressions": False}
4262    is_var_len_args = True
4263    _sql_names = ["COALESCE", "IFNULL", "NVL"]
4264
4265
4266class Concat(Func):
4267    arg_types = {"expressions": True}
4268    is_var_len_args = True
4269
4270
4271class SafeConcat(Concat):
4272    pass
4273
4274
4275class ConcatWs(Concat):
4276    _sql_names = ["CONCAT_WS"]
4277
4278
4279class Count(AggFunc):
4280    arg_types = {"this": False, "expressions": False}
4281    is_var_len_args = True
4282
4283
4284class CountIf(AggFunc):
4285    pass
4286
4287
4288class CurrentDate(Func):
4289    arg_types = {"this": False}
4290
4291
4292class CurrentDatetime(Func):
4293    arg_types = {"this": False}
4294
4295
4296class CurrentTime(Func):
4297    arg_types = {"this": False}
4298
4299
4300class CurrentTimestamp(Func):
4301    arg_types = {"this": False}
4302
4303
4304class CurrentUser(Func):
4305    arg_types = {"this": False}
4306
4307
4308class DateAdd(Func, TimeUnit):
4309    arg_types = {"this": True, "expression": True, "unit": False}
4310
4311
4312class DateSub(Func, TimeUnit):
4313    arg_types = {"this": True, "expression": True, "unit": False}
4314
4315
4316class DateDiff(Func, TimeUnit):
4317    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4318    arg_types = {"this": True, "expression": True, "unit": False}
4319
4320
4321class DateTrunc(Func):
4322    arg_types = {"unit": True, "this": True, "zone": False}
4323
4324
4325class DatetimeAdd(Func, TimeUnit):
4326    arg_types = {"this": True, "expression": True, "unit": False}
4327
4328
4329class DatetimeSub(Func, TimeUnit):
4330    arg_types = {"this": True, "expression": True, "unit": False}
4331
4332
4333class DatetimeDiff(Func, TimeUnit):
4334    arg_types = {"this": True, "expression": True, "unit": False}
4335
4336
4337class DatetimeTrunc(Func, TimeUnit):
4338    arg_types = {"this": True, "unit": True, "zone": False}
4339
4340
4341class DayOfWeek(Func):
4342    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
4343
4344
4345class DayOfMonth(Func):
4346    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
4347
4348
4349class DayOfYear(Func):
4350    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
4351
4352
4353class WeekOfYear(Func):
4354    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
4355
4356
4357class MonthsBetween(Func):
4358    arg_types = {"this": True, "expression": True, "roundoff": False}
4359
4360
4361class LastDateOfMonth(Func):
4362    pass
4363
4364
4365class Extract(Func):
4366    arg_types = {"this": True, "expression": True}
4367
4368
4369class TimestampAdd(Func, TimeUnit):
4370    arg_types = {"this": True, "expression": True, "unit": False}
4371
4372
4373class TimestampSub(Func, TimeUnit):
4374    arg_types = {"this": True, "expression": True, "unit": False}
4375
4376
4377class TimestampDiff(Func, TimeUnit):
4378    arg_types = {"this": True, "expression": True, "unit": False}
4379
4380
4381class TimestampTrunc(Func, TimeUnit):
4382    arg_types = {"this": True, "unit": True, "zone": False}
4383
4384
4385class TimeAdd(Func, TimeUnit):
4386    arg_types = {"this": True, "expression": True, "unit": False}
4387
4388
4389class TimeSub(Func, TimeUnit):
4390    arg_types = {"this": True, "expression": True, "unit": False}
4391
4392
4393class TimeDiff(Func, TimeUnit):
4394    arg_types = {"this": True, "expression": True, "unit": False}
4395
4396
4397class TimeTrunc(Func, TimeUnit):
4398    arg_types = {"this": True, "unit": True, "zone": False}
4399
4400
4401class DateFromParts(Func):
4402    _sql_names = ["DATEFROMPARTS"]
4403    arg_types = {"year": True, "month": True, "day": True}
4404
4405
4406class DateStrToDate(Func):
4407    pass
4408
4409
4410class DateToDateStr(Func):
4411    pass
4412
4413
4414class DateToDi(Func):
4415    pass
4416
4417
4418# https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#date
4419class Date(Func):
4420    arg_types = {"this": True, "zone": False}
4421
4422
4423class Day(Func):
4424    pass
4425
4426
4427class Decode(Func):
4428    arg_types = {"this": True, "charset": True, "replace": False}
4429
4430
4431class DiToDate(Func):
4432    pass
4433
4434
4435class Encode(Func):
4436    arg_types = {"this": True, "charset": True}
4437
4438
4439class Exp(Func):
4440    pass
4441
4442
4443class Explode(Func):
4444    pass
4445
4446
4447class Floor(Func):
4448    arg_types = {"this": True, "decimals": False}
4449
4450
4451class FromBase64(Func):
4452    pass
4453
4454
4455class ToBase64(Func):
4456    pass
4457
4458
4459class Greatest(Func):
4460    arg_types = {"this": True, "expressions": False}
4461    is_var_len_args = True
4462
4463
4464class GroupConcat(AggFunc):
4465    arg_types = {"this": True, "separator": False}
4466
4467
4468class Hex(Func):
4469    pass
4470
4471
4472class Xor(Connector, Func):
4473    arg_types = {"this": False, "expression": False, "expressions": False}
4474
4475
4476class If(Func):
4477    arg_types = {"this": True, "true": True, "false": False}
4478
4479
4480class Initcap(Func):
4481    arg_types = {"this": True, "expression": False}
4482
4483
4484class IsNan(Func):
4485    _sql_names = ["IS_NAN", "ISNAN"]
4486
4487
4488class FormatJson(Expression):
4489    pass
4490
4491
4492class JSONKeyValue(Expression):
4493    arg_types = {"this": True, "expression": True}
4494
4495
4496class JSONObject(Func):
4497    arg_types = {
4498        "expressions": False,
4499        "null_handling": False,
4500        "unique_keys": False,
4501        "return_type": False,
4502        "encoding": False,
4503    }
4504
4505
4506# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/JSON_ARRAY.html
4507class JSONArray(Func):
4508    arg_types = {
4509        "expressions": True,
4510        "null_handling": False,
4511        "return_type": False,
4512        "strict": False,
4513    }
4514
4515
4516# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/JSON_ARRAYAGG.html
4517class JSONArrayAgg(Func):
4518    arg_types = {
4519        "this": True,
4520        "order": False,
4521        "null_handling": False,
4522        "return_type": False,
4523        "strict": False,
4524    }
4525
4526
4527# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/JSON_TABLE.html
4528# Note: parsing of JSON column definitions is currently incomplete.
4529class JSONColumnDef(Expression):
4530    arg_types = {"this": True, "kind": False, "path": False}
4531
4532
4533# # https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/JSON_TABLE.html
4534class JSONTable(Func):
4535    arg_types = {
4536        "this": True,
4537        "expressions": True,
4538        "path": False,
4539        "error_handling": False,
4540        "empty_handling": False,
4541    }
4542
4543
4544class OpenJSONColumnDef(Expression):
4545    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
4546
4547
4548class OpenJSON(Func):
4549    arg_types = {"this": True, "path": False, "expressions": False}
4550
4551
4552class JSONBContains(Binary):
4553    _sql_names = ["JSONB_CONTAINS"]
4554
4555
4556class JSONExtract(Binary, Func):
4557    _sql_names = ["JSON_EXTRACT"]
4558
4559
4560class JSONExtractScalar(JSONExtract):
4561    _sql_names = ["JSON_EXTRACT_SCALAR"]
4562
4563
4564class JSONBExtract(JSONExtract):
4565    _sql_names = ["JSONB_EXTRACT"]
4566
4567
4568class JSONBExtractScalar(JSONExtract):
4569    _sql_names = ["JSONB_EXTRACT_SCALAR"]
4570
4571
4572class JSONFormat(Func):
4573    arg_types = {"this": False, "options": False}
4574    _sql_names = ["JSON_FORMAT"]
4575
4576
4577# https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#operator_member-of
4578class JSONArrayContains(Binary, Predicate, Func):
4579    _sql_names = ["JSON_ARRAY_CONTAINS"]
4580
4581
4582class Least(Func):
4583    arg_types = {"this": True, "expressions": False}
4584    is_var_len_args = True
4585
4586
4587class Left(Func):
4588    arg_types = {"this": True, "expression": True}
4589
4590
4591class Right(Func):
4592    arg_types = {"this": True, "expression": True}
4593
4594
4595class Length(Func):
4596    _sql_names = ["LENGTH", "LEN"]
4597
4598
4599class Levenshtein(Func):
4600    arg_types = {
4601        "this": True,
4602        "expression": False,
4603        "ins_cost": False,
4604        "del_cost": False,
4605        "sub_cost": False,
4606    }
4607
4608
4609class Ln(Func):
4610    pass
4611
4612
4613class Log(Func):
4614    arg_types = {"this": True, "expression": False}
4615
4616
4617class Log2(Func):
4618    pass
4619
4620
4621class Log10(Func):
4622    pass
4623
4624
4625class LogicalOr(AggFunc):
4626    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
4627
4628
4629class LogicalAnd(AggFunc):
4630    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
4631
4632
4633class Lower(Func):
4634    _sql_names = ["LOWER", "LCASE"]
4635
4636
4637class Map(Func):
4638    arg_types = {"keys": False, "values": False}
4639
4640
4641class MapFromEntries(Func):
4642    pass
4643
4644
4645class StarMap(Func):
4646    pass
4647
4648
4649class VarMap(Func):
4650    arg_types = {"keys": True, "values": True}
4651    is_var_len_args = True
4652
4653    @property
4654    def keys(self) -> t.List[Expression]:
4655        return self.args["keys"].expressions
4656
4657    @property
4658    def values(self) -> t.List[Expression]:
4659        return self.args["values"].expressions
4660
4661
4662# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
4663class MatchAgainst(Func):
4664    arg_types = {"this": True, "expressions": True, "modifier": False}
4665
4666
4667class Max(AggFunc):
4668    arg_types = {"this": True, "expressions": False}
4669    is_var_len_args = True
4670
4671
4672class MD5(Func):
4673    _sql_names = ["MD5"]
4674
4675
4676# Represents the variant of the MD5 function that returns a binary value
4677class MD5Digest(Func):
4678    _sql_names = ["MD5_DIGEST"]
4679
4680
4681class Min(AggFunc):
4682    arg_types = {"this": True, "expressions": False}
4683    is_var_len_args = True
4684
4685
4686class Month(Func):
4687    pass
4688
4689
4690class Nvl2(Func):
4691    arg_types = {"this": True, "true": True, "false": False}
4692
4693
4694class Posexplode(Func):
4695    pass
4696
4697
4698class Pow(Binary, Func):
4699    _sql_names = ["POWER", "POW"]
4700
4701
4702class PercentileCont(AggFunc):
4703    arg_types = {"this": True, "expression": False}
4704
4705
4706class PercentileDisc(AggFunc):
4707    arg_types = {"this": True, "expression": False}
4708
4709
4710class Quantile(AggFunc):
4711    arg_types = {"this": True, "quantile": True}
4712
4713
4714class ApproxQuantile(Quantile):
4715    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
4716
4717
4718class RangeN(Func):
4719    arg_types = {"this": True, "expressions": True, "each": False}
4720
4721
4722class ReadCSV(Func):
4723    _sql_names = ["READ_CSV"]
4724    is_var_len_args = True
4725    arg_types = {"this": True, "expressions": False}
4726
4727
4728class Reduce(Func):
4729    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
4730
4731
4732class RegexpExtract(Func):
4733    arg_types = {
4734        "this": True,
4735        "expression": True,
4736        "position": False,
4737        "occurrence": False,
4738        "parameters": False,
4739        "group": False,
4740    }
4741
4742
4743class RegexpReplace(Func):
4744    arg_types = {
4745        "this": True,
4746        "expression": True,
4747        "replacement": True,
4748        "position": False,
4749        "occurrence": False,
4750        "parameters": False,
4751    }
4752
4753
4754class RegexpLike(Binary, Func):
4755    arg_types = {"this": True, "expression": True, "flag": False}
4756
4757
4758class RegexpILike(Func):
4759    arg_types = {"this": True, "expression": True, "flag": False}
4760
4761
4762# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
4763# limit is the number of times a pattern is applied
4764class RegexpSplit(Func):
4765    arg_types = {"this": True, "expression": True, "limit": False}
4766
4767
4768class Repeat(Func):
4769    arg_types = {"this": True, "times": True}
4770
4771
4772class Round(Func):
4773    arg_types = {"this": True, "decimals": False}
4774
4775
4776class RowNumber(Func):
4777    arg_types: t.Dict[str, t.Any] = {}
4778
4779
4780class SafeDivide(Func):
4781    arg_types = {"this": True, "expression": True}
4782
4783
4784class SetAgg(AggFunc):
4785    pass
4786
4787
4788class SHA(Func):
4789    _sql_names = ["SHA", "SHA1"]
4790
4791
4792class SHA2(Func):
4793    _sql_names = ["SHA2"]
4794    arg_types = {"this": True, "length": False}
4795
4796
4797class SortArray(Func):
4798    arg_types = {"this": True, "asc": False}
4799
4800
4801class Split(Func):
4802    arg_types = {"this": True, "expression": True, "limit": False}
4803
4804
4805# Start may be omitted in the case of postgres
4806# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
4807class Substring(Func):
4808    arg_types = {"this": True, "start": False, "length": False}
4809
4810
4811class StandardHash(Func):
4812    arg_types = {"this": True, "expression": False}
4813
4814
4815class StartsWith(Func):
4816    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4817    arg_types = {"this": True, "expression": True}
4818
4819
4820class StrPosition(Func):
4821    arg_types = {
4822        "this": True,
4823        "substr": True,
4824        "position": False,
4825        "instance": False,
4826    }
4827
4828
4829class StrToDate(Func):
4830    arg_types = {"this": True, "format": True}
4831
4832
4833class StrToTime(Func):
4834    arg_types = {"this": True, "format": True, "zone": False}
4835
4836
4837# Spark allows unix_timestamp()
4838# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
4839class StrToUnix(Func):
4840    arg_types = {"this": False, "format": False}
4841
4842
4843# https://prestodb.io/docs/current/functions/string.html
4844# https://spark.apache.org/docs/latest/api/sql/index.html#str_to_map
4845class StrToMap(Func):
4846    arg_types = {
4847        "this": True,
4848        "pair_delim": False,
4849        "key_value_delim": False,
4850        "duplicate_resolution_callback": False,
4851    }
4852
4853
4854class NumberToStr(Func):
4855    arg_types = {"this": True, "format": True, "culture": False}
4856
4857
4858class FromBase(Func):
4859    arg_types = {"this": True, "expression": True}
4860
4861
4862class Struct(Func):
4863    arg_types = {"expressions": True}
4864    is_var_len_args = True
4865
4866
4867class StructExtract(Func):
4868    arg_types = {"this": True, "expression": True}
4869
4870
4871# https://learn.microsoft.com/en-us/sql/t-sql/functions/stuff-transact-sql?view=sql-server-ver16
4872# https://docs.snowflake.com/en/sql-reference/functions/insert
4873class Stuff(Func):
4874    _sql_names = ["STUFF", "INSERT"]
4875    arg_types = {"this": True, "start": True, "length": True, "expression": True}
4876
4877
4878class Sum(AggFunc):
4879    pass
4880
4881
4882class Sqrt(Func):
4883    pass
4884
4885
4886class Stddev(AggFunc):
4887    pass
4888
4889
4890class StddevPop(AggFunc):
4891    pass
4892
4893
4894class StddevSamp(AggFunc):
4895    pass
4896
4897
4898class TimeToStr(Func):
4899    arg_types = {"this": True, "format": True, "culture": False}
4900
4901
4902class TimeToTimeStr(Func):
4903    pass
4904
4905
4906class TimeToUnix(Func):
4907    pass
4908
4909
4910class TimeStrToDate(Func):
4911    pass
4912
4913
4914class TimeStrToTime(Func):
4915    pass
4916
4917
4918class TimeStrToUnix(Func):
4919    pass
4920
4921
4922class Trim(Func):
4923    arg_types = {
4924        "this": True,
4925        "expression": False,
4926        "position": False,
4927        "collation": False,
4928    }
4929
4930
4931class TsOrDsAdd(Func, TimeUnit):
4932    arg_types = {"this": True, "expression": True, "unit": False}
4933
4934
4935class TsOrDsToDateStr(Func):
4936    pass
4937
4938
4939class TsOrDsToDate(Func):
4940    arg_types = {"this": True, "format": False}
4941
4942
4943class TsOrDiToDi(Func):
4944    pass
4945
4946
4947class Unhex(Func):
4948    pass
4949
4950
4951class UnixToStr(Func):
4952    arg_types = {"this": True, "format": False}
4953
4954
4955# https://prestodb.io/docs/current/functions/datetime.html
4956# presto has weird zone/hours/minutes
4957class UnixToTime(Func):
4958    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4959
4960    SECONDS = Literal.string("seconds")
4961    MILLIS = Literal.string("millis")
4962    MICROS = Literal.string("micros")
4963
4964
4965class UnixToTimeStr(Func):
4966    pass
4967
4968
4969class Upper(Func):
4970    _sql_names = ["UPPER", "UCASE"]
4971
4972
4973class Variance(AggFunc):
4974    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
4975
4976
4977class VariancePop(AggFunc):
4978    _sql_names = ["VARIANCE_POP", "VAR_POP"]
4979
4980
4981class Week(Func):
4982    arg_types = {"this": True, "mode": False}
4983
4984
4985class XMLTable(Func):
4986    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4987
4988
4989class Year(Func):
4990    pass
4991
4992
4993class Use(Expression):
4994    arg_types = {"this": True, "kind": False}
4995
4996
4997class Merge(Expression):
4998    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4999
5000
5001class When(Func):
5002    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
5003
5004
5005# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html
5006# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16
5007class NextValueFor(Func):
5008    arg_types = {"this": True, "order": False}
5009
5010
5011def _norm_arg(arg):
5012    return arg.lower() if type(arg) is str else arg
5013
5014
5015ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
5016
5017
5018# Helpers
5019@t.overload
5020def maybe_parse(
5021    sql_or_expression: ExpOrStr,
5022    *,
5023    into: t.Type[E],
5024    dialect: DialectType = None,
5025    prefix: t.Optional[str] = None,
5026    copy: bool = False,
5027    **opts,
5028) -> E:
5029    ...
5030
5031
5032@t.overload
5033def maybe_parse(
5034    sql_or_expression: str | E,
5035    *,
5036    into: t.Optional[IntoType] = None,
5037    dialect: DialectType = None,
5038    prefix: t.Optional[str] = None,
5039    copy: bool = False,
5040    **opts,
5041) -> E:
5042    ...
5043
5044
5045def maybe_parse(
5046    sql_or_expression: ExpOrStr,
5047    *,
5048    into: t.Optional[IntoType] = None,
5049    dialect: DialectType = None,
5050    prefix: t.Optional[str] = None,
5051    copy: bool = False,
5052    **opts,
5053) -> Expression:
5054    """Gracefully handle a possible string or expression.
5055
5056    Example:
5057        >>> maybe_parse("1")
5058        (LITERAL this: 1, is_string: False)
5059        >>> maybe_parse(to_identifier("x"))
5060        (IDENTIFIER this: x, quoted: False)
5061
5062    Args:
5063        sql_or_expression: the SQL code string or an expression
5064        into: the SQLGlot Expression to parse into
5065        dialect: the dialect used to parse the input expressions (in the case that an
5066            input expression is a SQL string).
5067        prefix: a string to prefix the sql with before it gets parsed
5068            (automatically includes a space)
5069        copy: whether or not to copy the expression.
5070        **opts: other options to use to parse the input expressions (again, in the case
5071            that an input expression is a SQL string).
5072
5073    Returns:
5074        Expression: the parsed or given expression.
5075    """
5076    if isinstance(sql_or_expression, Expression):
5077        if copy:
5078            return sql_or_expression.copy()
5079        return sql_or_expression
5080
5081    if sql_or_expression is None:
5082        raise ParseError(f"SQL cannot be None")
5083
5084    import sqlglot
5085
5086    sql = str(sql_or_expression)
5087    if prefix:
5088        sql = f"{prefix} {sql}"
5089
5090    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
5091
5092
5093@t.overload
5094def maybe_copy(instance: None, copy: bool = True) -> None:
5095    ...
5096
5097
5098@t.overload
5099def maybe_copy(instance: E, copy: bool = True) -> E:
5100    ...
5101
5102
5103def maybe_copy(instance, copy=True):
5104    return instance.copy() if copy and instance else instance
5105
5106
5107def _is_wrong_expression(expression, into):
5108    return isinstance(expression, Expression) and not isinstance(expression, into)
5109
5110
5111def _apply_builder(
5112    expression,
5113    instance,
5114    arg,
5115    copy=True,
5116    prefix=None,
5117    into=None,
5118    dialect=None,
5119    **opts,
5120):
5121    if _is_wrong_expression(expression, into):
5122        expression = into(this=expression)
5123    instance = maybe_copy(instance, copy)
5124    expression = maybe_parse(
5125        sql_or_expression=expression,
5126        prefix=prefix,
5127        into=into,
5128        dialect=dialect,
5129        **opts,
5130    )
5131    instance.set(arg, expression)
5132    return instance
5133
5134
5135def _apply_child_list_builder(
5136    *expressions,
5137    instance,
5138    arg,
5139    append=True,
5140    copy=True,
5141    prefix=None,
5142    into=None,
5143    dialect=None,
5144    properties=None,
5145    **opts,
5146):
5147    instance = maybe_copy(instance, copy)
5148    parsed = []
5149    for expression in expressions:
5150        if expression is not None:
5151            if _is_wrong_expression(expression, into):
5152                expression = into(expressions=[expression])
5153
5154            expression = maybe_parse(
5155                expression,
5156                into=into,
5157                dialect=dialect,
5158                prefix=prefix,
5159                **opts,
5160            )
5161            parsed.extend(expression.expressions)
5162
5163    existing = instance.args.get(arg)
5164    if append and existing:
5165        parsed = existing.expressions + parsed
5166
5167    child = into(expressions=parsed)
5168    for k, v in (properties or {}).items():
5169        child.set(k, v)
5170    instance.set(arg, child)
5171
5172    return instance
5173
5174
5175def _apply_list_builder(
5176    *expressions,
5177    instance,
5178    arg,
5179    append=True,
5180    copy=True,
5181    prefix=None,
5182    into=None,
5183    dialect=None,
5184    **opts,
5185):
5186    inst = maybe_copy(instance, copy)
5187
5188    expressions = [
5189        maybe_parse(
5190            sql_or_expression=expression,
5191            into=into,
5192            prefix=prefix,
5193            dialect=dialect,
5194            **opts,
5195        )
5196        for expression in expressions
5197        if expression is not None
5198    ]
5199
5200    existing_expressions = inst.args.get(arg)
5201    if append and existing_expressions:
5202        expressions = existing_expressions + expressions
5203
5204    inst.set(arg, expressions)
5205    return inst
5206
5207
5208def _apply_conjunction_builder(
5209    *expressions,
5210    instance,
5211    arg,
5212    into=None,
5213    append=True,
5214    copy=True,
5215    dialect=None,
5216    **opts,
5217):
5218    expressions = [exp for exp in expressions if exp is not None and exp != ""]
5219    if not expressions:
5220        return instance
5221
5222    inst = maybe_copy(instance, copy)
5223
5224    existing = inst.args.get(arg)
5225    if append and existing is not None:
5226        expressions = [existing.this if into else existing] + list(expressions)
5227
5228    node = and_(*expressions, dialect=dialect, copy=copy, **opts)
5229
5230    inst.set(arg, into(this=node) if into else node)
5231    return inst
5232
5233
5234def _apply_cte_builder(
5235    instance: E,
5236    alias: ExpOrStr,
5237    as_: ExpOrStr,
5238    recursive: t.Optional[bool] = None,
5239    append: bool = True,
5240    dialect: DialectType = None,
5241    copy: bool = True,
5242    **opts,
5243) -> E:
5244    alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts)
5245    as_expression = maybe_parse(as_, dialect=dialect, **opts)
5246    cte = CTE(this=as_expression, alias=alias_expression)
5247    return _apply_child_list_builder(
5248        cte,
5249        instance=instance,
5250        arg="with",
5251        append=append,
5252        copy=copy,
5253        into=With,
5254        properties={"recursive": recursive or False},
5255    )
5256
5257
5258def _combine(
5259    expressions: t.Sequence[t.Optional[ExpOrStr]],
5260    operator: t.Type[Connector],
5261    dialect: DialectType = None,
5262    copy: bool = True,
5263    **opts,
5264) -> Expression:
5265    conditions = [
5266        condition(expression, dialect=dialect, copy=copy, **opts)
5267        for expression in expressions
5268        if expression is not None
5269    ]
5270
5271    this, *rest = conditions
5272    if rest:
5273        this = _wrap(this, Connector)
5274    for expression in rest:
5275        this = operator(this=this, expression=_wrap(expression, Connector))
5276
5277    return this
5278
5279
5280def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:
5281    return Paren(this=expression) if isinstance(expression, kind) else expression
5282
5283
5284def union(
5285    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5286) -> Union:
5287    """
5288    Initializes a syntax tree from one UNION expression.
5289
5290    Example:
5291        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5292        'SELECT * FROM foo UNION SELECT * FROM bla'
5293
5294    Args:
5295        left: the SQL code string corresponding to the left-hand side.
5296            If an `Expression` instance is passed, it will be used as-is.
5297        right: the SQL code string corresponding to the right-hand side.
5298            If an `Expression` instance is passed, it will be used as-is.
5299        distinct: set the DISTINCT flag if and only if this is true.
5300        dialect: the dialect used to parse the input expression.
5301        opts: other options to use to parse the input expressions.
5302
5303    Returns:
5304        The new Union instance.
5305    """
5306    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5307    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5308
5309    return Union(this=left, expression=right, distinct=distinct)
5310
5311
5312def intersect(
5313    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5314) -> Intersect:
5315    """
5316    Initializes a syntax tree from one INTERSECT expression.
5317
5318    Example:
5319        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5320        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5321
5322    Args:
5323        left: the SQL code string corresponding to the left-hand side.
5324            If an `Expression` instance is passed, it will be used as-is.
5325        right: the SQL code string corresponding to the right-hand side.
5326            If an `Expression` instance is passed, it will be used as-is.
5327        distinct: set the DISTINCT flag if and only if this is true.
5328        dialect: the dialect used to parse the input expression.
5329        opts: other options to use to parse the input expressions.
5330
5331    Returns:
5332        The new Intersect instance.
5333    """
5334    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5335    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5336
5337    return Intersect(this=left, expression=right, distinct=distinct)
5338
5339
5340def except_(
5341    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5342) -> Except:
5343    """
5344    Initializes a syntax tree from one EXCEPT expression.
5345
5346    Example:
5347        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5348        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5349
5350    Args:
5351        left: the SQL code string corresponding to the left-hand side.
5352            If an `Expression` instance is passed, it will be used as-is.
5353        right: the SQL code string corresponding to the right-hand side.
5354            If an `Expression` instance is passed, it will be used as-is.
5355        distinct: set the DISTINCT flag if and only if this is true.
5356        dialect: the dialect used to parse the input expression.
5357        opts: other options to use to parse the input expressions.
5358
5359    Returns:
5360        The new Except instance.
5361    """
5362    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5363    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5364
5365    return Except(this=left, expression=right, distinct=distinct)
5366
5367
5368def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5369    """
5370    Initializes a syntax tree from one or multiple SELECT expressions.
5371
5372    Example:
5373        >>> select("col1", "col2").from_("tbl").sql()
5374        'SELECT col1, col2 FROM tbl'
5375
5376    Args:
5377        *expressions: the SQL code string to parse as the expressions of a
5378            SELECT statement. If an Expression instance is passed, this is used as-is.
5379        dialect: the dialect used to parse the input expressions (in the case that an
5380            input expression is a SQL string).
5381        **opts: other options to use to parse the input expressions (again, in the case
5382            that an input expression is a SQL string).
5383
5384    Returns:
5385        Select: the syntax tree for the SELECT statement.
5386    """
5387    return Select().select(*expressions, dialect=dialect, **opts)
5388
5389
5390def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5391    """
5392    Initializes a syntax tree from a FROM expression.
5393
5394    Example:
5395        >>> from_("tbl").select("col1", "col2").sql()
5396        'SELECT col1, col2 FROM tbl'
5397
5398    Args:
5399        *expression: the SQL code string to parse as the FROM expressions of a
5400            SELECT statement. If an Expression instance is passed, this is used as-is.
5401        dialect: the dialect used to parse the input expression (in the case that the
5402            input expression is a SQL string).
5403        **opts: other options to use to parse the input expressions (again, in the case
5404            that the input expression is a SQL string).
5405
5406    Returns:
5407        Select: the syntax tree for the SELECT statement.
5408    """
5409    return Select().from_(expression, dialect=dialect, **opts)
5410
5411
5412def update(
5413    table: str | Table,
5414    properties: dict,
5415    where: t.Optional[ExpOrStr] = None,
5416    from_: t.Optional[ExpOrStr] = None,
5417    dialect: DialectType = None,
5418    **opts,
5419) -> Update:
5420    """
5421    Creates an update statement.
5422
5423    Example:
5424        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5425        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5426
5427    Args:
5428        *properties: dictionary of properties to set which are
5429            auto converted to sql objects eg None -> NULL
5430        where: sql conditional parsed into a WHERE statement
5431        from_: sql statement parsed into a FROM statement
5432        dialect: the dialect used to parse the input expressions.
5433        **opts: other options to use to parse the input expressions.
5434
5435    Returns:
5436        Update: the syntax tree for the UPDATE statement.
5437    """
5438    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5439    update_expr.set(
5440        "expressions",
5441        [
5442            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5443            for k, v in properties.items()
5444        ],
5445    )
5446    if from_:
5447        update_expr.set(
5448            "from",
5449            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5450        )
5451    if isinstance(where, Condition):
5452        where = Where(this=where)
5453    if where:
5454        update_expr.set(
5455            "where",
5456            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5457        )
5458    return update_expr
5459
5460
5461def delete(
5462    table: ExpOrStr,
5463    where: t.Optional[ExpOrStr] = None,
5464    returning: t.Optional[ExpOrStr] = None,
5465    dialect: DialectType = None,
5466    **opts,
5467) -> Delete:
5468    """
5469    Builds a delete statement.
5470
5471    Example:
5472        >>> delete("my_table", where="id > 1").sql()
5473        'DELETE FROM my_table WHERE id > 1'
5474
5475    Args:
5476        where: sql conditional parsed into a WHERE statement
5477        returning: sql conditional parsed into a RETURNING statement
5478        dialect: the dialect used to parse the input expressions.
5479        **opts: other options to use to parse the input expressions.
5480
5481    Returns:
5482        Delete: the syntax tree for the DELETE statement.
5483    """
5484    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5485    if where:
5486        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5487    if returning:
5488        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5489    return delete_expr
5490
5491
5492def insert(
5493    expression: ExpOrStr,
5494    into: ExpOrStr,
5495    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5496    overwrite: t.Optional[bool] = None,
5497    dialect: DialectType = None,
5498    copy: bool = True,
5499    **opts,
5500) -> Insert:
5501    """
5502    Builds an INSERT statement.
5503
5504    Example:
5505        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5506        'INSERT INTO tbl VALUES (1, 2, 3)'
5507
5508    Args:
5509        expression: the sql string or expression of the INSERT statement
5510        into: the tbl to insert data to.
5511        columns: optionally the table's column names.
5512        overwrite: whether to INSERT OVERWRITE or not.
5513        dialect: the dialect used to parse the input expressions.
5514        copy: whether or not to copy the expression.
5515        **opts: other options to use to parse the input expressions.
5516
5517    Returns:
5518        Insert: the syntax tree for the INSERT statement.
5519    """
5520    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5521    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5522
5523    if columns:
5524        this = _apply_list_builder(
5525            *columns,
5526            instance=Schema(this=this),
5527            arg="expressions",
5528            into=Identifier,
5529            copy=False,
5530            dialect=dialect,
5531            **opts,
5532        )
5533
5534    return Insert(this=this, expression=expr, overwrite=overwrite)
5535
5536
5537def condition(
5538    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5539) -> Condition:
5540    """
5541    Initialize a logical condition expression.
5542
5543    Example:
5544        >>> condition("x=1").sql()
5545        'x = 1'
5546
5547        This is helpful for composing larger logical syntax trees:
5548        >>> where = condition("x=1")
5549        >>> where = where.and_("y=1")
5550        >>> Select().from_("tbl").select("*").where(where).sql()
5551        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5552
5553    Args:
5554        *expression: the SQL code string to parse.
5555            If an Expression instance is passed, this is used as-is.
5556        dialect: the dialect used to parse the input expression (in the case that the
5557            input expression is a SQL string).
5558        copy: Whether or not to copy `expression` (only applies to expressions).
5559        **opts: other options to use to parse the input expressions (again, in the case
5560            that the input expression is a SQL string).
5561
5562    Returns:
5563        The new Condition instance
5564    """
5565    return maybe_parse(
5566        expression,
5567        into=Condition,
5568        dialect=dialect,
5569        copy=copy,
5570        **opts,
5571    )
5572
5573
5574def and_(
5575    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5576) -> Condition:
5577    """
5578    Combine multiple conditions with an AND logical operator.
5579
5580    Example:
5581        >>> and_("x=1", and_("y=1", "z=1")).sql()
5582        'x = 1 AND (y = 1 AND z = 1)'
5583
5584    Args:
5585        *expressions: the SQL code strings to parse.
5586            If an Expression instance is passed, this is used as-is.
5587        dialect: the dialect used to parse the input expression.
5588        copy: whether or not to copy `expressions` (only applies to Expressions).
5589        **opts: other options to use to parse the input expressions.
5590
5591    Returns:
5592        And: the new condition
5593    """
5594    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))
5595
5596
5597def or_(
5598    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5599) -> Condition:
5600    """
5601    Combine multiple conditions with an OR logical operator.
5602
5603    Example:
5604        >>> or_("x=1", or_("y=1", "z=1")).sql()
5605        'x = 1 OR (y = 1 OR z = 1)'
5606
5607    Args:
5608        *expressions: the SQL code strings to parse.
5609            If an Expression instance is passed, this is used as-is.
5610        dialect: the dialect used to parse the input expression.
5611        copy: whether or not to copy `expressions` (only applies to Expressions).
5612        **opts: other options to use to parse the input expressions.
5613
5614    Returns:
5615        Or: the new condition
5616    """
5617    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))
5618
5619
5620def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5621    """
5622    Wrap a condition with a NOT operator.
5623
5624    Example:
5625        >>> not_("this_suit='black'").sql()
5626        "NOT this_suit = 'black'"
5627
5628    Args:
5629        expression: the SQL code string to parse.
5630            If an Expression instance is passed, this is used as-is.
5631        dialect: the dialect used to parse the input expression.
5632        copy: whether to copy the expression or not.
5633        **opts: other options to use to parse the input expressions.
5634
5635    Returns:
5636        The new condition.
5637    """
5638    this = condition(
5639        expression,
5640        dialect=dialect,
5641        copy=copy,
5642        **opts,
5643    )
5644    return Not(this=_wrap(this, Connector))
5645
5646
5647def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5648    """
5649    Wrap an expression in parentheses.
5650
5651    Example:
5652        >>> paren("5 + 3").sql()
5653        '(5 + 3)'
5654
5655    Args:
5656        expression: the SQL code string to parse.
5657            If an Expression instance is passed, this is used as-is.
5658        copy: whether to copy the expression or not.
5659
5660    Returns:
5661        The wrapped expression.
5662    """
5663    return Paren(this=maybe_parse(expression, copy=copy))
5664
5665
5666SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
5667
5668
5669@t.overload
5670def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None:
5671    ...
5672
5673
5674@t.overload
5675def to_identifier(
5676    name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True
5677) -> Identifier:
5678    ...
5679
5680
5681def to_identifier(name, quoted=None, copy=True):
5682    """Builds an identifier.
5683
5684    Args:
5685        name: The name to turn into an identifier.
5686        quoted: Whether or not force quote the identifier.
5687        copy: Whether or not to copy a passed in Identefier node.
5688
5689    Returns:
5690        The identifier ast node.
5691    """
5692
5693    if name is None:
5694        return None
5695
5696    if isinstance(name, Identifier):
5697        identifier = maybe_copy(name, copy)
5698    elif isinstance(name, str):
5699        identifier = Identifier(
5700            this=name,
5701            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5702        )
5703    else:
5704        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5705    return identifier
5706
5707
5708INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
5709
5710
5711def to_interval(interval: str | Literal) -> Interval:
5712    """Builds an interval expression from a string like '1 day' or '5 months'."""
5713    if isinstance(interval, Literal):
5714        if not interval.is_string:
5715            raise ValueError("Invalid interval string.")
5716
5717        interval = interval.this
5718
5719    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5720
5721    if not interval_parts:
5722        raise ValueError("Invalid interval string.")
5723
5724    return Interval(
5725        this=Literal.string(interval_parts.group(1)),
5726        unit=Var(this=interval_parts.group(2)),
5727    )
5728
5729
5730@t.overload
5731def to_table(sql_path: str | Table, **kwargs) -> Table:
5732    ...
5733
5734
5735@t.overload
5736def to_table(sql_path: None, **kwargs) -> None:
5737    ...
5738
5739
5740def to_table(
5741    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5742) -> t.Optional[Table]:
5743    """
5744    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5745    If a table is passed in then that table is returned.
5746
5747    Args:
5748        sql_path: a `[catalog].[schema].[table]` string.
5749        dialect: the source dialect according to which the table name will be parsed.
5750        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5751
5752    Returns:
5753        A table expression.
5754    """
5755    if sql_path is None or isinstance(sql_path, Table):
5756        return sql_path
5757    if not isinstance(sql_path, str):
5758        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5759
5760    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5761    if table:
5762        for k, v in kwargs.items():
5763            table.set(k, v)
5764
5765    return table
5766
5767
5768def to_column(sql_path: str | Column, **kwargs) -> Column:
5769    """
5770    Create a column from a `[table].[column]` sql path. Schema is optional.
5771
5772    If a column is passed in then that column is returned.
5773
5774    Args:
5775        sql_path: `[table].[column]` string
5776    Returns:
5777        Table: A column expression
5778    """
5779    if sql_path is None or isinstance(sql_path, Column):
5780        return sql_path
5781    if not isinstance(sql_path, str):
5782        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5783    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
5784
5785
5786def alias_(
5787    expression: ExpOrStr,
5788    alias: str | Identifier,
5789    table: bool | t.Sequence[str | Identifier] = False,
5790    quoted: t.Optional[bool] = None,
5791    dialect: DialectType = None,
5792    copy: bool = True,
5793    **opts,
5794):
5795    """Create an Alias expression.
5796
5797    Example:
5798        >>> alias_('foo', 'bar').sql()
5799        'foo AS bar'
5800
5801        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5802        '(SELECT 1, 2) AS bar(a, b)'
5803
5804    Args:
5805        expression: the SQL code strings to parse.
5806            If an Expression instance is passed, this is used as-is.
5807        alias: the alias name to use. If the name has
5808            special characters it is quoted.
5809        table: Whether or not to create a table alias, can also be a list of columns.
5810        quoted: whether or not to quote the alias
5811        dialect: the dialect used to parse the input expression.
5812        copy: Whether or not to copy the expression.
5813        **opts: other options to use to parse the input expressions.
5814
5815    Returns:
5816        Alias: the aliased expression
5817    """
5818    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5819    alias = to_identifier(alias, quoted=quoted)
5820
5821    if table:
5822        table_alias = TableAlias(this=alias)
5823        exp.set("alias", table_alias)
5824
5825        if not isinstance(table, bool):
5826            for column in table:
5827                table_alias.append("columns", to_identifier(column, quoted=quoted))
5828
5829        return exp
5830
5831    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5832    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5833    # for the complete Window expression.
5834    #
5835    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5836
5837    if "alias" in exp.arg_types and not isinstance(exp, Window):
5838        exp.set("alias", alias)
5839        return exp
5840    return Alias(this=exp, alias=alias)
5841
5842
5843def subquery(
5844    expression: ExpOrStr,
5845    alias: t.Optional[Identifier | str] = None,
5846    dialect: DialectType = None,
5847    **opts,
5848) -> Select:
5849    """
5850    Build a subquery expression.
5851
5852    Example:
5853        >>> subquery('select x from tbl', 'bar').select('x').sql()
5854        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5855
5856    Args:
5857        expression: the SQL code strings to parse.
5858            If an Expression instance is passed, this is used as-is.
5859        alias: the alias name to use.
5860        dialect: the dialect used to parse the input expression.
5861        **opts: other options to use to parse the input expressions.
5862
5863    Returns:
5864        A new Select instance with the subquery expression included.
5865    """
5866
5867    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5868    return Select().from_(expression, dialect=dialect, **opts)
5869
5870
5871def column(
5872    col: str | Identifier,
5873    table: t.Optional[str | Identifier] = None,
5874    db: t.Optional[str | Identifier] = None,
5875    catalog: t.Optional[str | Identifier] = None,
5876    quoted: t.Optional[bool] = None,
5877) -> Column:
5878    """
5879    Build a Column.
5880
5881    Args:
5882        col: Column name.
5883        table: Table name.
5884        db: Database name.
5885        catalog: Catalog name.
5886        quoted: Whether to force quotes on the column's identifiers.
5887
5888    Returns:
5889        The new Column instance.
5890    """
5891    return Column(
5892        this=to_identifier(col, quoted=quoted),
5893        table=to_identifier(table, quoted=quoted),
5894        db=to_identifier(db, quoted=quoted),
5895        catalog=to_identifier(catalog, quoted=quoted),
5896    )
5897
5898
5899def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5900    """Cast an expression to a data type.
5901
5902    Example:
5903        >>> cast('x + 1', 'int').sql()
5904        'CAST(x + 1 AS INT)'
5905
5906    Args:
5907        expression: The expression to cast.
5908        to: The datatype to cast to.
5909
5910    Returns:
5911        The new Cast instance.
5912    """
5913    expression = maybe_parse(expression, **opts)
5914    return Cast(this=expression, to=DataType.build(to, **opts))
5915
5916
5917def table_(
5918    table: Identifier | str,
5919    db: t.Optional[Identifier | str] = None,
5920    catalog: t.Optional[Identifier | str] = None,
5921    quoted: t.Optional[bool] = None,
5922    alias: t.Optional[Identifier | str] = None,
5923) -> Table:
5924    """Build a Table.
5925
5926    Args:
5927        table: Table name.
5928        db: Database name.
5929        catalog: Catalog name.
5930        quote: Whether to force quotes on the table's identifiers.
5931        alias: Table's alias.
5932
5933    Returns:
5934        The new Table instance.
5935    """
5936    return Table(
5937        this=to_identifier(table, quoted=quoted) if table else None,
5938        db=to_identifier(db, quoted=quoted) if db else None,
5939        catalog=to_identifier(catalog, quoted=quoted) if catalog else None,
5940        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5941    )
5942
5943
5944def values(
5945    values: t.Iterable[t.Tuple[t.Any, ...]],
5946    alias: t.Optional[str] = None,
5947    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5948) -> Values:
5949    """Build VALUES statement.
5950
5951    Example:
5952        >>> values([(1, '2')]).sql()
5953        "VALUES (1, '2')"
5954
5955    Args:
5956        values: values statements that will be converted to SQL
5957        alias: optional alias
5958        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5959         If either are provided then an alias is also required.
5960
5961    Returns:
5962        Values: the Values expression object
5963    """
5964    if columns and not alias:
5965        raise ValueError("Alias is required when providing columns")
5966
5967    return Values(
5968        expressions=[convert(tup) for tup in values],
5969        alias=(
5970            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5971            if columns
5972            else (TableAlias(this=to_identifier(alias)) if alias else None)
5973        ),
5974    )
5975
5976
5977def var(name: t.Optional[ExpOrStr]) -> Var:
5978    """Build a SQL variable.
5979
5980    Example:
5981        >>> repr(var('x'))
5982        '(VAR this: x)'
5983
5984        >>> repr(var(column('x', table='y')))
5985        '(VAR this: x)'
5986
5987    Args:
5988        name: The name of the var or an expression who's name will become the var.
5989
5990    Returns:
5991        The new variable node.
5992    """
5993    if not name:
5994        raise ValueError("Cannot convert empty name into var.")
5995
5996    if isinstance(name, Expression):
5997        name = name.name
5998    return Var(this=name)
5999
6000
6001def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
6002    """Build ALTER TABLE... RENAME... expression
6003
6004    Args:
6005        old_name: The old name of the table
6006        new_name: The new name of the table
6007
6008    Returns:
6009        Alter table expression
6010    """
6011    old_table = to_table(old_name)
6012    new_table = to_table(new_name)
6013    return AlterTable(
6014        this=old_table,
6015        actions=[
6016            RenameTable(this=new_table),
6017        ],
6018    )
6019
6020
6021def convert(value: t.Any, copy: bool = False) -> Expression:
6022    """Convert a python value into an expression object.
6023
6024    Raises an error if a conversion is not possible.
6025
6026    Args:
6027        value: A python object.
6028        copy: Whether or not to copy `value` (only applies to Expressions and collections).
6029
6030    Returns:
6031        Expression: the equivalent expression object.
6032    """
6033    if isinstance(value, Expression):
6034        return maybe_copy(value, copy)
6035    if isinstance(value, str):
6036        return Literal.string(value)
6037    if isinstance(value, bool):
6038        return Boolean(this=value)
6039    if value is None or (isinstance(value, float) and math.isnan(value)):
6040        return NULL
6041    if isinstance(value, numbers.Number):
6042        return Literal.number(value)
6043    if isinstance(value, datetime.datetime):
6044        datetime_literal = Literal.string(
6045            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
6046        )
6047        return TimeStrToTime(this=datetime_literal)
6048    if isinstance(value, datetime.date):
6049        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
6050        return DateStrToDate(this=date_literal)
6051    if isinstance(value, tuple):
6052        return Tuple(expressions=[convert(v, copy=copy) for v in value])
6053    if isinstance(value, list):
6054        return Array(expressions=[convert(v, copy=copy) for v in value])
6055    if isinstance(value, dict):
6056        return Map(
6057            keys=Array(expressions=[convert(k, copy=copy) for k in value]),
6058            values=Array(expressions=[convert(v, copy=copy) for v in value.values()]),
6059        )
6060    raise ValueError(f"Cannot convert {value}")
6061
6062
6063def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
6064    """
6065    Replace children of an expression with the result of a lambda fun(child) -> exp.
6066    """
6067    for k, v in expression.args.items():
6068        is_list_arg = type(v) is list
6069
6070        child_nodes = v if is_list_arg else [v]
6071        new_child_nodes = []
6072
6073        for cn in child_nodes:
6074            if isinstance(cn, Expression):
6075                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
6076                    new_child_nodes.append(child_node)
6077                    child_node.parent = expression
6078                    child_node.arg_key = k
6079            else:
6080                new_child_nodes.append(cn)
6081
6082        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
6083
6084
6085def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
6086    """
6087    Return all table names referenced through columns in an expression.
6088
6089    Example:
6090        >>> import sqlglot
6091        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
6092        ['a', 'c']
6093
6094    Args:
6095        expression: expression to find table names.
6096        exclude: a table name to exclude
6097
6098    Returns:
6099        A list of unique names.
6100    """
6101    return {
6102        table
6103        for table in (column.table for column in expression.find_all(Column))
6104        if table and table != exclude
6105    }
6106
6107
6108def table_name(table: Table | str, dialect: DialectType = None) -> str:
6109    """Get the full name of a table as a string.
6110
6111    Args:
6112        table: Table expression node or string.
6113        dialect: The dialect to generate the table name for.
6114
6115    Examples:
6116        >>> from sqlglot import exp, parse_one
6117        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
6118        'a.b.c'
6119
6120    Returns:
6121        The table name.
6122    """
6123
6124    table = maybe_parse(table, into=Table)
6125
6126    if not table:
6127        raise ValueError(f"Cannot parse {table}")
6128
6129    return ".".join(
6130        part.sql(dialect=dialect, identify=True)
6131        if not SAFE_IDENTIFIER_RE.match(part.name)
6132        else part.name
6133        for part in table.parts
6134    )
6135
6136
6137def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
6138    """Replace all tables in expression according to the mapping.
6139
6140    Args:
6141        expression: expression node to be transformed and replaced.
6142        mapping: mapping of table names.
6143        copy: whether or not to copy the expression.
6144
6145    Examples:
6146        >>> from sqlglot import exp, parse_one
6147        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
6148        'SELECT * FROM c'
6149
6150    Returns:
6151        The mapped expression.
6152    """
6153
6154    def _replace_tables(node: Expression) -> Expression:
6155        if isinstance(node, Table):
6156            new_name = mapping.get(table_name(node))
6157            if new_name:
6158                return to_table(
6159                    new_name,
6160                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
6161                )
6162        return node
6163
6164    return expression.transform(_replace_tables, copy=copy)
6165
6166
6167def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
6168    """Replace placeholders in an expression.
6169
6170    Args:
6171        expression: expression node to be transformed and replaced.
6172        args: positional names that will substitute unnamed placeholders in the given order.
6173        kwargs: keyword arguments that will substitute named placeholders.
6174
6175    Examples:
6176        >>> from sqlglot import exp, parse_one
6177        >>> replace_placeholders(
6178        ...     parse_one("select * from :tbl where ? = ?"),
6179        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
6180        ... ).sql()
6181        "SELECT * FROM foo WHERE str_col = 'b'"
6182
6183    Returns:
6184        The mapped expression.
6185    """
6186
6187    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
6188        if isinstance(node, Placeholder):
6189            if node.name:
6190                new_name = kwargs.get(node.name)
6191                if new_name:
6192                    return convert(new_name)
6193            else:
6194                try:
6195                    return convert(next(args))
6196                except StopIteration:
6197                    pass
6198        return node
6199
6200    return expression.transform(_replace_placeholders, iter(args), **kwargs)
6201
6202
6203def expand(
6204    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
6205) -> Expression:
6206    """Transforms an expression by expanding all referenced sources into subqueries.
6207
6208    Examples:
6209        >>> from sqlglot import parse_one
6210        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
6211        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
6212
6213        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
6214        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
6215
6216    Args:
6217        expression: The expression to expand.
6218        sources: A dictionary of name to Subqueryables.
6219        copy: Whether or not to copy the expression during transformation. Defaults to True.
6220
6221    Returns:
6222        The transformed expression.
6223    """
6224
6225    def _expand(node: Expression):
6226        if isinstance(node, Table):
6227            name = table_name(node)
6228            source = sources.get(name)
6229            if source:
6230                subquery = source.subquery(node.alias or name)
6231                subquery.comments = [f"source: {name}"]
6232                return subquery.transform(_expand, copy=False)
6233        return node
6234
6235    return expression.transform(_expand, copy=copy)
6236
6237
6238def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6239    """
6240    Returns a Func expression.
6241
6242    Examples:
6243        >>> func("abs", 5).sql()
6244        'ABS(5)'
6245
6246        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6247        'CAST(5 AS DOUBLE)'
6248
6249    Args:
6250        name: the name of the function to build.
6251        args: the args used to instantiate the function of interest.
6252        dialect: the source dialect.
6253        kwargs: the kwargs used to instantiate the function of interest.
6254
6255    Note:
6256        The arguments `args` and `kwargs` are mutually exclusive.
6257
6258    Returns:
6259        An instance of the function of interest, or an anonymous function, if `name` doesn't
6260        correspond to an existing `sqlglot.expressions.Func` class.
6261    """
6262    if args and kwargs:
6263        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6264
6265    from sqlglot.dialects.dialect import Dialect
6266
6267    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6268    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6269
6270    parser = Dialect.get_or_raise(dialect)().parser()
6271    from_args_list = parser.FUNCTIONS.get(name.upper())
6272
6273    if from_args_list:
6274        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6275    else:
6276        kwargs = kwargs or {"expressions": converted}
6277        function = Anonymous(this=name, **kwargs)
6278
6279    for error_message in function.error_messages(converted):
6280        raise ValueError(error_message)
6281
6282    return function
6283
6284
6285def true() -> Boolean:
6286    """
6287    Returns a true Boolean expression.
6288    """
6289    return Boolean(this=True)
6290
6291
6292def false() -> Boolean:
6293    """
6294    Returns a false Boolean expression.
6295    """
6296    return Boolean(this=False)
6297
6298
6299def null() -> Null:
6300    """
6301    Returns a Null expression.
6302    """
6303    return Null()
6304
6305
6306# TODO: deprecate this
6307TRUE = Boolean(this=True)
6308FALSE = Boolean(this=False)
6309NULL = Null()
class Expression:
 56class Expression(metaclass=_Expression):
 57    """
 58    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 59    context, such as its child expressions, their names (arg keys), and whether a given child expression
 60    is optional or not.
 61
 62    Attributes:
 63        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 64            and representing expressions as strings.
 65        arg_types: determines what arguments (child nodes) are supported by an expression. It
 66            maps arg keys to booleans that indicate whether the corresponding args are optional.
 67        parent: a reference to the parent expression (or None, in case of root expressions).
 68        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 69            uses to refer to it.
 70        comments: a list of comments that are associated with a given expression. This is used in
 71            order to preserve comments when transpiling SQL code.
 72        type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 73            optimizer, in order to enable some transformations that require type information.
 74        meta: a dictionary that can be used to store useful metadata for a given expression.
 75
 76    Example:
 77        >>> class Foo(Expression):
 78        ...     arg_types = {"this": True, "expression": False}
 79
 80        The above definition informs us that Foo is an Expression that requires an argument called
 81        "this" and may also optionally receive an argument called "expression".
 82
 83    Args:
 84        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 85    """
 86
 87    key = "expression"
 88    arg_types = {"this": True}
 89    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 90
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
102
103    def __eq__(self, other) -> bool:
104        return type(self) is type(other) and hash(self) == hash(other)
105
106    @property
107    def hashable_args(self) -> t.Any:
108        return frozenset(
109            (k, tuple(_norm_arg(a) for a in v) if type(v) is list else _norm_arg(v))
110            for k, v in self.args.items()
111            if not (v is None or v is False or (type(v) is list and not v))
112        )
113
114    def __hash__(self) -> int:
115        if self._hash is not None:
116            return self._hash
117
118        return hash((self.__class__, self.hashable_args))
119
120    @property
121    def this(self):
122        """
123        Retrieves the argument with key "this".
124        """
125        return self.args.get("this")
126
127    @property
128    def expression(self):
129        """
130        Retrieves the argument with key "expression".
131        """
132        return self.args.get("expression")
133
134    @property
135    def expressions(self):
136        """
137        Retrieves the argument with key "expressions".
138        """
139        return self.args.get("expressions") or []
140
141    def text(self, key) -> str:
142        """
143        Returns a textual representation of the argument corresponding to "key". This can only be used
144        for args that are strings or leaf Expression instances, such as identifiers and literals.
145        """
146        field = self.args.get(key)
147        if isinstance(field, str):
148            return field
149        if isinstance(field, (Identifier, Literal, Var)):
150            return field.this
151        if isinstance(field, (Star, Null)):
152            return field.name
153        return ""
154
155    @property
156    def is_string(self) -> bool:
157        """
158        Checks whether a Literal expression is a string.
159        """
160        return isinstance(self, Literal) and self.args["is_string"]
161
162    @property
163    def is_number(self) -> bool:
164        """
165        Checks whether a Literal expression is a number.
166        """
167        return isinstance(self, Literal) and not self.args["is_string"]
168
169    @property
170    def is_int(self) -> bool:
171        """
172        Checks whether a Literal expression is an integer.
173        """
174        if self.is_number:
175            try:
176                int(self.name)
177                return True
178            except ValueError:
179                pass
180        return False
181
182    @property
183    def is_star(self) -> bool:
184        """Checks whether an expression is a star."""
185        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
186
187    @property
188    def alias(self) -> str:
189        """
190        Returns the alias of the expression, or an empty string if it's not aliased.
191        """
192        if isinstance(self.args.get("alias"), TableAlias):
193            return self.args["alias"].name
194        return self.text("alias")
195
196    @property
197    def alias_column_names(self) -> t.List[str]:
198        table_alias = self.args.get("alias")
199        if not table_alias:
200            return []
201        return [c.name for c in table_alias.args.get("columns") or []]
202
203    @property
204    def name(self) -> str:
205        return self.text("this")
206
207    @property
208    def alias_or_name(self) -> str:
209        return self.alias or self.name
210
211    @property
212    def output_name(self) -> str:
213        """
214        Name of the output column if this expression is a selection.
215
216        If the Expression has no output name, an empty string is returned.
217
218        Example:
219            >>> from sqlglot import parse_one
220            >>> parse_one("SELECT a").expressions[0].output_name
221            'a'
222            >>> parse_one("SELECT b AS c").expressions[0].output_name
223            'c'
224            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
225            ''
226        """
227        return ""
228
229    @property
230    def type(self) -> t.Optional[DataType]:
231        return self._type
232
233    @type.setter
234    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
235        if dtype and not isinstance(dtype, DataType):
236            dtype = DataType.build(dtype)
237        self._type = dtype  # type: ignore
238
239    @property
240    def meta(self) -> t.Dict[str, t.Any]:
241        if self._meta is None:
242            self._meta = {}
243        return self._meta
244
245    def __deepcopy__(self, memo):
246        copy = self.__class__(**deepcopy(self.args))
247        if self.comments is not None:
248            copy.comments = deepcopy(self.comments)
249
250        if self._type is not None:
251            copy._type = self._type.copy()
252
253        if self._meta is not None:
254            copy._meta = deepcopy(self._meta)
255
256        return copy
257
258    def copy(self):
259        """
260        Returns a deep copy of the expression.
261        """
262        new = deepcopy(self)
263        new.parent = self.parent
264        return new
265
266    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
267        if self.comments is None:
268            self.comments = []
269        if comments:
270            self.comments.extend(comments)
271
272    def append(self, arg_key: str, value: t.Any) -> None:
273        """
274        Appends value to arg_key if it's a list or sets it as a new list.
275
276        Args:
277            arg_key (str): name of the list expression arg
278            value (Any): value to append to the list
279        """
280        if not isinstance(self.args.get(arg_key), list):
281            self.args[arg_key] = []
282        self.args[arg_key].append(value)
283        self._set_parent(arg_key, value)
284
285    def set(self, arg_key: str, value: t.Any) -> None:
286        """
287        Sets arg_key to value.
288
289        Args:
290            arg_key: name of the expression arg.
291            value: value to set the arg to.
292        """
293        if value is None:
294            self.args.pop(arg_key, None)
295            return
296
297        self.args[arg_key] = value
298        self._set_parent(arg_key, value)
299
300    def _set_parent(self, arg_key: str, value: t.Any) -> None:
301        if hasattr(value, "parent"):
302            value.parent = self
303            value.arg_key = arg_key
304        elif type(value) is list:
305            for v in value:
306                if hasattr(v, "parent"):
307                    v.parent = self
308                    v.arg_key = arg_key
309
310    @property
311    def depth(self) -> int:
312        """
313        Returns the depth of this tree.
314        """
315        if self.parent:
316            return self.parent.depth + 1
317        return 0
318
319    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
320        """Yields the key and expression for all arguments, exploding list args."""
321        for k, vs in self.args.items():
322            if type(vs) is list:
323                for v in vs:
324                    if hasattr(v, "parent"):
325                        yield k, v
326            else:
327                if hasattr(vs, "parent"):
328                    yield k, vs
329
330    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
331        """
332        Returns the first node in this tree which matches at least one of
333        the specified types.
334
335        Args:
336            expression_types: the expression type(s) to match.
337            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
338
339        Returns:
340            The node which matches the criteria or None if no such node was found.
341        """
342        return next(self.find_all(*expression_types, bfs=bfs), None)
343
344    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
345        """
346        Returns a generator object which visits all nodes in this tree and only
347        yields those that match at least one of the specified expression types.
348
349        Args:
350            expression_types: the expression type(s) to match.
351            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
352
353        Returns:
354            The generator object.
355        """
356        for expression, *_ in self.walk(bfs=bfs):
357            if isinstance(expression, expression_types):
358                yield expression
359
360    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
361        """
362        Returns a nearest parent matching expression_types.
363
364        Args:
365            expression_types: the expression type(s) to match.
366
367        Returns:
368            The parent node.
369        """
370        ancestor = self.parent
371        while ancestor and not isinstance(ancestor, expression_types):
372            ancestor = ancestor.parent
373        return t.cast(E, ancestor)
374
375    @property
376    def parent_select(self) -> t.Optional[Select]:
377        """
378        Returns the parent select statement.
379        """
380        return self.find_ancestor(Select)
381
382    @property
383    def same_parent(self) -> bool:
384        """Returns if the parent is the same class as itself."""
385        return type(self.parent) is self.__class__
386
387    def root(self) -> Expression:
388        """
389        Returns the root expression of this tree.
390        """
391        expression = self
392        while expression.parent:
393            expression = expression.parent
394        return expression
395
396    def walk(self, bfs=True, prune=None):
397        """
398        Returns a generator object which visits all nodes in this tree.
399
400        Args:
401            bfs (bool): if set to True the BFS traversal order will be applied,
402                otherwise the DFS traversal will be used instead.
403            prune ((node, parent, arg_key) -> bool): callable that returns True if
404                the generator should stop traversing this branch of the tree.
405
406        Returns:
407            the generator object.
408        """
409        if bfs:
410            yield from self.bfs(prune=prune)
411        else:
412            yield from self.dfs(prune=prune)
413
414    def dfs(self, parent=None, key=None, prune=None):
415        """
416        Returns a generator object which visits all nodes in this tree in
417        the DFS (Depth-first) order.
418
419        Returns:
420            The generator object.
421        """
422        parent = parent or self.parent
423        yield self, parent, key
424        if prune and prune(self, parent, key):
425            return
426
427        for k, v in self.iter_expressions():
428            yield from v.dfs(self, k, prune)
429
430    def bfs(self, prune=None):
431        """
432        Returns a generator object which visits all nodes in this tree in
433        the BFS (Breadth-first) order.
434
435        Returns:
436            The generator object.
437        """
438        queue = deque([(self, self.parent, None)])
439
440        while queue:
441            item, parent, key = queue.popleft()
442
443            yield item, parent, key
444            if prune and prune(item, parent, key):
445                continue
446
447            for k, v in item.iter_expressions():
448                queue.append((v, item, k))
449
450    def unnest(self):
451        """
452        Returns the first non parenthesis child or self.
453        """
454        expression = self
455        while type(expression) is Paren:
456            expression = expression.this
457        return expression
458
459    def unalias(self):
460        """
461        Returns the inner expression if this is an Alias.
462        """
463        if isinstance(self, Alias):
464            return self.this
465        return self
466
467    def unnest_operands(self):
468        """
469        Returns unnested operands as a tuple.
470        """
471        return tuple(arg.unnest() for _, arg in self.iter_expressions())
472
473    def flatten(self, unnest=True):
474        """
475        Returns a generator which yields child nodes who's parents are the same class.
476
477        A AND B AND C -> [A, B, C]
478        """
479        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
480            if not type(node) is self.__class__:
481                yield node.unnest() if unnest else node
482
483    def __str__(self) -> str:
484        return self.sql()
485
486    def __repr__(self) -> str:
487        return self._to_s()
488
489    def sql(self, dialect: DialectType = None, **opts) -> str:
490        """
491        Returns SQL string representation of this tree.
492
493        Args:
494            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
495            opts: other `sqlglot.generator.Generator` options.
496
497        Returns:
498            The SQL string.
499        """
500        from sqlglot.dialects import Dialect
501
502        return Dialect.get_or_raise(dialect)().generate(self, **opts)
503
504    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
505        indent = "" if not level else "\n"
506        indent += "".join(["  "] * level)
507        left = f"({self.key.upper()} "
508
509        args: t.Dict[str, t.Any] = {
510            k: ", ".join(
511                v._to_s(hide_missing=hide_missing, level=level + 1)
512                if hasattr(v, "_to_s")
513                else str(v)
514                for v in ensure_list(vs)
515                if v is not None
516            )
517            for k, vs in self.args.items()
518        }
519        args["comments"] = self.comments
520        args["type"] = self.type
521        args = {k: v for k, v in args.items() if v or not hide_missing}
522
523        right = ", ".join(f"{k}: {v}" for k, v in args.items())
524        right += ")"
525
526        return indent + left + right
527
528    def transform(self, fun, *args, copy=True, **kwargs):
529        """
530        Recursively visits all tree nodes (excluding already transformed ones)
531        and applies the given transformation function to each node.
532
533        Args:
534            fun (function): a function which takes a node as an argument and returns a
535                new transformed node or the same node without modifications. If the function
536                returns None, then the corresponding node will be removed from the syntax tree.
537            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
538                modified in place.
539
540        Returns:
541            The transformed tree.
542        """
543        node = self.copy() if copy else self
544        new_node = fun(node, *args, **kwargs)
545
546        if new_node is None or not isinstance(new_node, Expression):
547            return new_node
548        if new_node is not node:
549            new_node.parent = node.parent
550            return new_node
551
552        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
553        return new_node
554
555    @t.overload
556    def replace(self, expression: E) -> E:
557        ...
558
559    @t.overload
560    def replace(self, expression: None) -> None:
561        ...
562
563    def replace(self, expression):
564        """
565        Swap out this expression with a new expression.
566
567        For example::
568
569            >>> tree = Select().select("x").from_("tbl")
570            >>> tree.find(Column).replace(Column(this="y"))
571            (COLUMN this: y)
572            >>> tree.sql()
573            'SELECT y FROM tbl'
574
575        Args:
576            expression: new node
577
578        Returns:
579            The new expression or expressions.
580        """
581        if not self.parent:
582            return expression
583
584        parent = self.parent
585        self.parent = None
586
587        replace_children(parent, lambda child: expression if child is self else child)
588        return expression
589
590    def pop(self: E) -> E:
591        """
592        Remove this expression from its AST.
593
594        Returns:
595            The popped expression.
596        """
597        self.replace(None)
598        return self
599
600    def assert_is(self, type_: t.Type[E]) -> E:
601        """
602        Assert that this `Expression` is an instance of `type_`.
603
604        If it is NOT an instance of `type_`, this raises an assertion error.
605        Otherwise, this returns this expression.
606
607        Examples:
608            This is useful for type security in chained expressions:
609
610            >>> import sqlglot
611            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
612            'SELECT x, z FROM y'
613        """
614        assert isinstance(self, type_)
615        return self
616
617    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
618        """
619        Checks if this expression is valid (e.g. all mandatory args are set).
620
621        Args:
622            args: a sequence of values that were used to instantiate a Func expression. This is used
623                to check that the provided arguments don't exceed the function argument limit.
624
625        Returns:
626            A list of error messages for all possible errors that were found.
627        """
628        errors: t.List[str] = []
629
630        for k in self.args:
631            if k not in self.arg_types:
632                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
633        for k, mandatory in self.arg_types.items():
634            v = self.args.get(k)
635            if mandatory and (v is None or (isinstance(v, list) and not v)):
636                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
637
638        if (
639            args
640            and isinstance(self, Func)
641            and len(args) > len(self.arg_types)
642            and not self.is_var_len_args
643        ):
644            errors.append(
645                f"The number of provided arguments ({len(args)}) is greater than "
646                f"the maximum number of supported arguments ({len(self.arg_types)})"
647            )
648
649        return errors
650
651    def dump(self):
652        """
653        Dump this Expression to a JSON-serializable dict.
654        """
655        from sqlglot.serde import dump
656
657        return dump(self)
658
659    @classmethod
660    def load(cls, obj):
661        """
662        Load a dict (as returned by `Expression.dump`) into an Expression instance.
663        """
664        from sqlglot.serde import load
665
666        return load(obj)

The base class for all expressions in a syntax tree. Each Expression 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 Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are 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.
  • 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 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(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression 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.
Expression(**args: Any)
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
key = 'expression'
arg_types = {'this': True}
args: Dict[str, Any]
parent: Optional[Expression]
arg_key: Optional[str]
comments: Optional[List[str]]
hashable_args: Any
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
141    def text(self, key) -> str:
142        """
143        Returns a textual representation of the argument corresponding to "key". This can only be used
144        for args that are strings or leaf Expression instances, such as identifiers and literals.
145        """
146        field = self.args.get(key)
147        if isinstance(field, str):
148            return field
149        if isinstance(field, (Identifier, Literal, Var)):
150            return field.this
151        if isinstance(field, (Star, Null)):
152            return field.name
153        return ""

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

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

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

alias_column_names: List[str]
name: str
alias_or_name: str
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
type: Optional[DataType]
meta: Dict[str, Any]
def copy(self):
258    def copy(self):
259        """
260        Returns a deep copy of the expression.
261        """
262        new = deepcopy(self)
263        new.parent = self.parent
264        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
266    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
267        if self.comments is None:
268            self.comments = []
269        if comments:
270            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
272    def append(self, arg_key: str, value: t.Any) -> None:
273        """
274        Appends value to arg_key if it's a list or sets it as a new list.
275
276        Args:
277            arg_key (str): name of the list expression arg
278            value (Any): value to append to the list
279        """
280        if not isinstance(self.args.get(arg_key), list):
281            self.args[arg_key] = []
282        self.args[arg_key].append(value)
283        self._set_parent(arg_key, 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: Any) -> None:
285    def set(self, arg_key: str, value: t.Any) -> None:
286        """
287        Sets arg_key to value.
288
289        Args:
290            arg_key: name of the expression arg.
291            value: value to set the arg to.
292        """
293        if value is None:
294            self.args.pop(arg_key, None)
295            return
296
297        self.args[arg_key] = value
298        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key: name of the expression arg.
  • value: value to set the arg to.
depth: int

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, Expression]]:
319    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
320        """Yields the key and expression for all arguments, exploding list args."""
321        for k, vs in self.args.items():
322            if type(vs) is list:
323                for v in vs:
324                    if hasattr(v, "parent"):
325                        yield k, v
326            else:
327                if hasattr(vs, "parent"):
328                    yield k, vs

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

def find(self, *expression_types: Type[~E], bfs: bool = True) -> Optional[~E]:
330    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
331        """
332        Returns the first node in this tree which matches at least one of
333        the specified types.
334
335        Args:
336            expression_types: the expression type(s) to match.
337            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
338
339        Returns:
340            The node which matches the criteria or None if no such node was found.
341        """
342        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]:
344    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
345        """
346        Returns a generator object which visits all nodes in this tree and only
347        yields those that match at least one of the specified expression types.
348
349        Args:
350            expression_types: the expression type(s) to match.
351            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
352
353        Returns:
354            The generator object.
355        """
356        for expression, *_ in self.walk(bfs=bfs):
357            if isinstance(expression, expression_types):
358                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]:
360    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
361        """
362        Returns a nearest parent matching expression_types.
363
364        Args:
365            expression_types: the expression type(s) to match.
366
367        Returns:
368            The parent node.
369        """
370        ancestor = self.parent
371        while ancestor and not isinstance(ancestor, expression_types):
372            ancestor = ancestor.parent
373        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

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

The parent node.

parent_select: Optional[Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

def root(self) -> Expression:
387    def root(self) -> Expression:
388        """
389        Returns the root expression of this tree.
390        """
391        expression = self
392        while expression.parent:
393            expression = expression.parent
394        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
396    def walk(self, bfs=True, prune=None):
397        """
398        Returns a generator object which visits all nodes in this tree.
399
400        Args:
401            bfs (bool): if set to True the BFS traversal order will be applied,
402                otherwise the DFS traversal will be used instead.
403            prune ((node, parent, arg_key) -> bool): callable that returns True if
404                the generator should stop traversing this branch of the tree.
405
406        Returns:
407            the generator object.
408        """
409        if bfs:
410            yield from self.bfs(prune=prune)
411        else:
412            yield from self.dfs(prune=prune)

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

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

the generator object.

def dfs(self, parent=None, key=None, prune=None):
414    def dfs(self, parent=None, key=None, prune=None):
415        """
416        Returns a generator object which visits all nodes in this tree in
417        the DFS (Depth-first) order.
418
419        Returns:
420            The generator object.
421        """
422        parent = parent or self.parent
423        yield self, parent, key
424        if prune and prune(self, parent, key):
425            return
426
427        for k, v in self.iter_expressions():
428            yield from v.dfs(self, k, prune)

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=None):
430    def bfs(self, prune=None):
431        """
432        Returns a generator object which visits all nodes in this tree in
433        the BFS (Breadth-first) order.
434
435        Returns:
436            The generator object.
437        """
438        queue = deque([(self, self.parent, None)])
439
440        while queue:
441            item, parent, key = queue.popleft()
442
443            yield item, parent, key
444            if prune and prune(item, parent, key):
445                continue
446
447            for k, v in item.iter_expressions():
448                queue.append((v, item, k))

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

Returns:

The generator object.

def unnest(self):
450    def unnest(self):
451        """
452        Returns the first non parenthesis child or self.
453        """
454        expression = self
455        while type(expression) is Paren:
456            expression = expression.this
457        return expression

Returns the first non parenthesis child or self.

def unalias(self):
459    def unalias(self):
460        """
461        Returns the inner expression if this is an Alias.
462        """
463        if isinstance(self, Alias):
464            return self.this
465        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
467    def unnest_operands(self):
468        """
469        Returns unnested operands as a tuple.
470        """
471        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
473    def flatten(self, unnest=True):
474        """
475        Returns a generator which yields child nodes who's parents are the same class.
476
477        A AND B AND C -> [A, B, C]
478        """
479        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
480            if not type(node) is self.__class__:
481                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

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

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
489    def sql(self, dialect: DialectType = None, **opts) -> str:
490        """
491        Returns SQL string representation of this tree.
492
493        Args:
494            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
495            opts: other `sqlglot.generator.Generator` options.
496
497        Returns:
498            The SQL string.
499        """
500        from sqlglot.dialects import Dialect
501
502        return Dialect.get_or_raise(dialect)().generate(self, **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, *args, copy=True, **kwargs):
528    def transform(self, fun, *args, copy=True, **kwargs):
529        """
530        Recursively visits all tree nodes (excluding already transformed ones)
531        and applies the given transformation function to each node.
532
533        Args:
534            fun (function): a function which takes a node as an argument and returns a
535                new transformed node or the same node without modifications. If the function
536                returns None, then the corresponding node will be removed from the syntax tree.
537            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
538                modified in place.
539
540        Returns:
541            The transformed tree.
542        """
543        node = self.copy() if copy else self
544        new_node = fun(node, *args, **kwargs)
545
546        if new_node is None or not isinstance(new_node, Expression):
547            return new_node
548        if new_node is not node:
549            new_node.parent = node.parent
550            return new_node
551
552        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
553        return new_node

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

Arguments:
  • fun (function): 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 (bool): 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):
563    def replace(self, expression):
564        """
565        Swap out this expression with a new expression.
566
567        For example::
568
569            >>> tree = Select().select("x").from_("tbl")
570            >>> tree.find(Column).replace(Column(this="y"))
571            (COLUMN this: y)
572            >>> tree.sql()
573            'SELECT y FROM tbl'
574
575        Args:
576            expression: new node
577
578        Returns:
579            The new expression or expressions.
580        """
581        if not self.parent:
582            return expression
583
584        parent = self.parent
585        self.parent = None
586
587        replace_children(parent, lambda child: expression if child is self else child)
588        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression: new node
Returns:

The new expression or expressions.

def pop(self: ~E) -> ~E:
590    def pop(self: E) -> E:
591        """
592        Remove this expression from its AST.
593
594        Returns:
595            The popped expression.
596        """
597        self.replace(None)
598        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_: Type[~E]) -> ~E:
600    def assert_is(self, type_: t.Type[E]) -> E:
601        """
602        Assert that this `Expression` is an instance of `type_`.
603
604        If it is NOT an instance of `type_`, this raises an assertion error.
605        Otherwise, this returns this expression.
606
607        Examples:
608            This is useful for type security in chained expressions:
609
610            >>> import sqlglot
611            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
612            'SELECT x, z FROM y'
613        """
614        assert isinstance(self, type_)
615        return self

Assert that this Expression 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(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
617    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
618        """
619        Checks if this expression is valid (e.g. all mandatory args are set).
620
621        Args:
622            args: a sequence of values that were used to instantiate a Func expression. This is used
623                to check that the provided arguments don't exceed the function argument limit.
624
625        Returns:
626            A list of error messages for all possible errors that were found.
627        """
628        errors: t.List[str] = []
629
630        for k in self.args:
631            if k not in self.arg_types:
632                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
633        for k, mandatory in self.arg_types.items():
634            v = self.args.get(k)
635            if mandatory and (v is None or (isinstance(v, list) and not v)):
636                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
637
638        if (
639            args
640            and isinstance(self, Func)
641            and len(args) > len(self.arg_types)
642            and not self.is_var_len_args
643        ):
644            errors.append(
645                f"The number of provided arguments ({len(args)}) is greater than "
646                f"the maximum number of supported arguments ({len(self.arg_types)})"
647            )
648
649        return errors

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):
651    def dump(self):
652        """
653        Dump this Expression to a JSON-serializable dict.
654        """
655        from sqlglot.serde import dump
656
657        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
659    @classmethod
660    def load(cls, obj):
661        """
662        Load a dict (as returned by `Expression.dump`) into an Expression instance.
663        """
664        from sqlglot.serde import load
665
666        return load(obj)

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

IntoType = typing.Union[str, typing.Type[Expression], typing.Collection[typing.Union[str, typing.Type[Expression]]]]
ExpOrStr = typing.Union[str, Expression]
class Condition(Expression):
677class Condition(Expression):
678    def and_(
679        self,
680        *expressions: t.Optional[ExpOrStr],
681        dialect: DialectType = None,
682        copy: bool = True,
683        **opts,
684    ) -> Condition:
685        """
686        AND this condition with one or multiple expressions.
687
688        Example:
689            >>> condition("x=1").and_("y=1").sql()
690            'x = 1 AND y = 1'
691
692        Args:
693            *expressions: the SQL code strings to parse.
694                If an `Expression` instance is passed, it will be used as-is.
695            dialect: the dialect used to parse the input expression.
696            copy: whether or not to copy the involved expressions (only applies to Expressions).
697            opts: other options to use to parse the input expressions.
698
699        Returns:
700            The new And condition.
701        """
702        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
703
704    def or_(
705        self,
706        *expressions: t.Optional[ExpOrStr],
707        dialect: DialectType = None,
708        copy: bool = True,
709        **opts,
710    ) -> Condition:
711        """
712        OR this condition with one or multiple expressions.
713
714        Example:
715            >>> condition("x=1").or_("y=1").sql()
716            'x = 1 OR y = 1'
717
718        Args:
719            *expressions: the SQL code strings to parse.
720                If an `Expression` instance is passed, it will be used as-is.
721            dialect: the dialect used to parse the input expression.
722            copy: whether or not to copy the involved expressions (only applies to Expressions).
723            opts: other options to use to parse the input expressions.
724
725        Returns:
726            The new Or condition.
727        """
728        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
729
730    def not_(self, copy: bool = True):
731        """
732        Wrap this condition with NOT.
733
734        Example:
735            >>> condition("x=1").not_().sql()
736            'NOT x = 1'
737
738        Args:
739            copy: whether or not to copy this object.
740
741        Returns:
742            The new Not instance.
743        """
744        return not_(self, copy=copy)
745
746    def as_(
747        self,
748        alias: str | Identifier,
749        quoted: t.Optional[bool] = None,
750        dialect: DialectType = None,
751        copy: bool = True,
752        **opts,
753    ) -> Alias:
754        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
755
756    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
757        this = self.copy()
758        other = convert(other, copy=True)
759        if not isinstance(this, klass) and not isinstance(other, klass):
760            this = _wrap(this, Binary)
761            other = _wrap(other, Binary)
762        if reverse:
763            return klass(this=other, expression=this)
764        return klass(this=this, expression=other)
765
766    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
767        return Bracket(
768            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
769        )
770
771    def isin(
772        self,
773        *expressions: t.Any,
774        query: t.Optional[ExpOrStr] = None,
775        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
776        copy: bool = True,
777        **opts,
778    ) -> In:
779        return In(
780            this=maybe_copy(self, copy),
781            expressions=[convert(e, copy=copy) for e in expressions],
782            query=maybe_parse(query, copy=copy, **opts) if query else None,
783            unnest=Unnest(
784                expressions=[
785                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
786                ]
787            )
788            if unnest
789            else None,
790        )
791
792    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
793        return Between(
794            this=maybe_copy(self, copy),
795            low=convert(low, copy=copy, **opts),
796            high=convert(high, copy=copy, **opts),
797        )
798
799    def is_(self, other: ExpOrStr) -> Is:
800        return self._binop(Is, other)
801
802    def like(self, other: ExpOrStr) -> Like:
803        return self._binop(Like, other)
804
805    def ilike(self, other: ExpOrStr) -> ILike:
806        return self._binop(ILike, other)
807
808    def eq(self, other: t.Any) -> EQ:
809        return self._binop(EQ, other)
810
811    def neq(self, other: t.Any) -> NEQ:
812        return self._binop(NEQ, other)
813
814    def rlike(self, other: ExpOrStr) -> RegexpLike:
815        return self._binop(RegexpLike, other)
816
817    def __lt__(self, other: t.Any) -> LT:
818        return self._binop(LT, other)
819
820    def __le__(self, other: t.Any) -> LTE:
821        return self._binop(LTE, other)
822
823    def __gt__(self, other: t.Any) -> GT:
824        return self._binop(GT, other)
825
826    def __ge__(self, other: t.Any) -> GTE:
827        return self._binop(GTE, other)
828
829    def __add__(self, other: t.Any) -> Add:
830        return self._binop(Add, other)
831
832    def __radd__(self, other: t.Any) -> Add:
833        return self._binop(Add, other, reverse=True)
834
835    def __sub__(self, other: t.Any) -> Sub:
836        return self._binop(Sub, other)
837
838    def __rsub__(self, other: t.Any) -> Sub:
839        return self._binop(Sub, other, reverse=True)
840
841    def __mul__(self, other: t.Any) -> Mul:
842        return self._binop(Mul, other)
843
844    def __rmul__(self, other: t.Any) -> Mul:
845        return self._binop(Mul, other, reverse=True)
846
847    def __truediv__(self, other: t.Any) -> Div:
848        return self._binop(Div, other)
849
850    def __rtruediv__(self, other: t.Any) -> Div:
851        return self._binop(Div, other, reverse=True)
852
853    def __floordiv__(self, other: t.Any) -> IntDiv:
854        return self._binop(IntDiv, other)
855
856    def __rfloordiv__(self, other: t.Any) -> IntDiv:
857        return self._binop(IntDiv, other, reverse=True)
858
859    def __mod__(self, other: t.Any) -> Mod:
860        return self._binop(Mod, other)
861
862    def __rmod__(self, other: t.Any) -> Mod:
863        return self._binop(Mod, other, reverse=True)
864
865    def __pow__(self, other: t.Any) -> Pow:
866        return self._binop(Pow, other)
867
868    def __rpow__(self, other: t.Any) -> Pow:
869        return self._binop(Pow, other, reverse=True)
870
871    def __and__(self, other: t.Any) -> And:
872        return self._binop(And, other)
873
874    def __rand__(self, other: t.Any) -> And:
875        return self._binop(And, other, reverse=True)
876
877    def __or__(self, other: t.Any) -> Or:
878        return self._binop(Or, other)
879
880    def __ror__(self, other: t.Any) -> Or:
881        return self._binop(Or, other, reverse=True)
882
883    def __neg__(self) -> Neg:
884        return Neg(this=_wrap(self.copy(), Binary))
885
886    def __invert__(self) -> Not:
887        return not_(self.copy())
def and_( self, *expressions: Union[str, Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
678    def and_(
679        self,
680        *expressions: t.Optional[ExpOrStr],
681        dialect: DialectType = None,
682        copy: bool = True,
683        **opts,
684    ) -> Condition:
685        """
686        AND this condition with one or multiple expressions.
687
688        Example:
689            >>> condition("x=1").and_("y=1").sql()
690            'x = 1 AND y = 1'
691
692        Args:
693            *expressions: the SQL code strings to parse.
694                If an `Expression` instance is passed, it will be used as-is.
695            dialect: the dialect used to parse the input expression.
696            copy: whether or not to copy the involved expressions (only applies to Expressions).
697            opts: other options to use to parse the input expressions.
698
699        Returns:
700            The new And condition.
701        """
702        return and_(self, *expressions, dialect=dialect, copy=copy, **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 Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new And condition.

def or_( self, *expressions: Union[str, Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
704    def or_(
705        self,
706        *expressions: t.Optional[ExpOrStr],
707        dialect: DialectType = None,
708        copy: bool = True,
709        **opts,
710    ) -> Condition:
711        """
712        OR this condition with one or multiple expressions.
713
714        Example:
715            >>> condition("x=1").or_("y=1").sql()
716            'x = 1 OR y = 1'
717
718        Args:
719            *expressions: the SQL code strings to parse.
720                If an `Expression` instance is passed, it will be used as-is.
721            dialect: the dialect used to parse the input expression.
722            copy: whether or not to copy the involved expressions (only applies to Expressions).
723            opts: other options to use to parse the input expressions.
724
725        Returns:
726            The new Or condition.
727        """
728        return or_(self, *expressions, dialect=dialect, copy=copy, **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 Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new Or condition.

def not_(self, copy: bool = True):
730    def not_(self, copy: bool = True):
731        """
732        Wrap this condition with NOT.
733
734        Example:
735            >>> condition("x=1").not_().sql()
736            'NOT x = 1'
737
738        Args:
739            copy: whether or not to copy this object.
740
741        Returns:
742            The new Not instance.
743        """
744        return not_(self, copy=copy)

Wrap this condition with NOT.

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

The new Not instance.

def as_( self, alias: str | Identifier, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Alias:
746    def as_(
747        self,
748        alias: str | Identifier,
749        quoted: t.Optional[bool] = None,
750        dialect: DialectType = None,
751        copy: bool = True,
752        **opts,
753    ) -> Alias:
754        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
def isin( self, *expressions: Any, query: Union[str, Expression, NoneType] = None, unnest: Union[str, Expression, NoneType, Collection[Union[str, Expression]]] = None, copy: bool = True, **opts) -> In:
771    def isin(
772        self,
773        *expressions: t.Any,
774        query: t.Optional[ExpOrStr] = None,
775        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
776        copy: bool = True,
777        **opts,
778    ) -> In:
779        return In(
780            this=maybe_copy(self, copy),
781            expressions=[convert(e, copy=copy) for e in expressions],
782            query=maybe_parse(query, copy=copy, **opts) if query else None,
783            unnest=Unnest(
784                expressions=[
785                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
786                ]
787            )
788            if unnest
789            else None,
790        )
def between( self, low: Any, high: Any, copy: bool = True, **opts) -> Between:
792    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
793        return Between(
794            this=maybe_copy(self, copy),
795            low=convert(low, copy=copy, **opts),
796            high=convert(high, copy=copy, **opts),
797        )
def is_( self, other: Union[str, Expression]) -> Is:
799    def is_(self, other: ExpOrStr) -> Is:
800        return self._binop(Is, other)
def like( self, other: Union[str, Expression]) -> Like:
802    def like(self, other: ExpOrStr) -> Like:
803        return self._binop(Like, other)
def ilike( self, other: Union[str, Expression]) -> ILike:
805    def ilike(self, other: ExpOrStr) -> ILike:
806        return self._binop(ILike, other)
def eq(self, other: Any) -> EQ:
808    def eq(self, other: t.Any) -> EQ:
809        return self._binop(EQ, other)
def neq(self, other: Any) -> NEQ:
811    def neq(self, other: t.Any) -> NEQ:
812        return self._binop(NEQ, other)
def rlike( self, other: Union[str, Expression]) -> RegexpLike:
814    def rlike(self, other: ExpOrStr) -> RegexpLike:
815        return self._binop(RegexpLike, other)
key = 'condition'
class Predicate(Condition):
890class Predicate(Condition):
891    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

key = 'predicate'
class DerivedTable(Expression):
894class DerivedTable(Expression):
895    @property
896    def selects(self) -> t.List[Expression]:
897        return self.this.selects if isinstance(self.this, Subqueryable) else []
898
899    @property
900    def named_selects(self) -> t.List[str]:
901        return [select.output_name for select in self.selects]
selects: List[Expression]
named_selects: List[str]
key = 'derivedtable'
class Unionable(Expression):
904class Unionable(Expression):
905    def union(
906        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
907    ) -> Unionable:
908        """
909        Builds a UNION expression.
910
911        Example:
912            >>> import sqlglot
913            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
914            'SELECT * FROM foo UNION SELECT * FROM bla'
915
916        Args:
917            expression: the SQL code string.
918                If an `Expression` instance is passed, it will be used as-is.
919            distinct: set the DISTINCT flag if and only if this is true.
920            dialect: the dialect used to parse the input expression.
921            opts: other options to use to parse the input expressions.
922
923        Returns:
924            The new Union expression.
925        """
926        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
927
928    def intersect(
929        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
930    ) -> Unionable:
931        """
932        Builds an INTERSECT expression.
933
934        Example:
935            >>> import sqlglot
936            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
937            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
938
939        Args:
940            expression: the SQL code string.
941                If an `Expression` instance is passed, it will be used as-is.
942            distinct: set the DISTINCT flag if and only if this is true.
943            dialect: the dialect used to parse the input expression.
944            opts: other options to use to parse the input expressions.
945
946        Returns:
947            The new Intersect expression.
948        """
949        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
950
951    def except_(
952        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
953    ) -> Unionable:
954        """
955        Builds an EXCEPT expression.
956
957        Example:
958            >>> import sqlglot
959            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
960            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
961
962        Args:
963            expression: the SQL code string.
964                If an `Expression` instance is passed, it will be used as-is.
965            distinct: set the DISTINCT flag if and only if this is true.
966            dialect: the dialect used to parse the input expression.
967            opts: other options to use to parse the input expressions.
968
969        Returns:
970            The new Except expression.
971        """
972        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union( self, expression: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Unionable:
905    def union(
906        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
907    ) -> Unionable:
908        """
909        Builds a UNION expression.
910
911        Example:
912            >>> import sqlglot
913            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
914            'SELECT * FROM foo UNION SELECT * FROM bla'
915
916        Args:
917            expression: the SQL code string.
918                If an `Expression` instance is passed, it will be used as-is.
919            distinct: set the DISTINCT flag if and only if this is true.
920            dialect: the dialect used to parse the input expression.
921            opts: other options to use to parse the input expressions.
922
923        Returns:
924            The new Union expression.
925        """
926        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union expression.

def intersect( self, expression: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Unionable:
928    def intersect(
929        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
930    ) -> Unionable:
931        """
932        Builds an INTERSECT expression.
933
934        Example:
935            >>> import sqlglot
936            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
937            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
938
939        Args:
940            expression: the SQL code string.
941                If an `Expression` instance is passed, it will be used as-is.
942            distinct: set the DISTINCT flag if and only if this is true.
943            dialect: the dialect used to parse the input expression.
944            opts: other options to use to parse the input expressions.
945
946        Returns:
947            The new Intersect expression.
948        """
949        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect expression.

def except_( self, expression: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Unionable:
951    def except_(
952        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
953    ) -> Unionable:
954        """
955        Builds an EXCEPT expression.
956
957        Example:
958            >>> import sqlglot
959            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
960            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
961
962        Args:
963            expression: the SQL code string.
964                If an `Expression` instance is passed, it will be used as-is.
965            distinct: set the DISTINCT flag if and only if this is true.
966            dialect: the dialect used to parse the input expression.
967            opts: other options to use to parse the input expressions.
968
969        Returns:
970            The new Except expression.
971        """
972        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except expression.

key = 'unionable'
class UDTF(DerivedTable, Unionable):
975class UDTF(DerivedTable, Unionable):
976    @property
977    def selects(self) -> t.List[Expression]:
978        alias = self.args.get("alias")
979        return alias.columns if alias else []
selects: List[Expression]
key = 'udtf'
class Cache(Expression):
982class Cache(Expression):
983    arg_types = {
984        "with": False,
985        "this": True,
986        "lazy": False,
987        "options": False,
988        "expression": False,
989    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
992class Uncache(Expression):
993    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class DDL(Expression):
 996class DDL(Expression):
 997    @property
 998    def ctes(self):
 999        with_ = self.args.get("with")
1000        if not with_:
1001            return []
1002        return with_.expressions
1003
1004    @property
1005    def named_selects(self) -> t.List[str]:
1006        if isinstance(self.expression, Subqueryable):
1007            return self.expression.named_selects
1008        return []
1009
1010    @property
1011    def selects(self) -> t.List[Expression]:
1012        if isinstance(self.expression, Subqueryable):
1013            return self.expression.selects
1014        return []
ctes
named_selects: List[str]
selects: List[Expression]
key = 'ddl'
class Create(DDL):
1017class Create(DDL):
1018    arg_types = {
1019        "with": False,
1020        "this": True,
1021        "kind": True,
1022        "expression": False,
1023        "exists": False,
1024        "properties": False,
1025        "replace": False,
1026        "unique": False,
1027        "indexes": False,
1028        "no_schema_binding": False,
1029        "begin": False,
1030        "clone": False,
1031    }
arg_types = {'with': False, 'this': True, 'kind': True, 'expression': False, 'exists': False, 'properties': False, 'replace': False, 'unique': False, 'indexes': False, 'no_schema_binding': False, 'begin': False, 'clone': False}
key = 'create'
class Clone(Expression):
1035class Clone(Expression):
1036    arg_types = {
1037        "this": True,
1038        "when": False,
1039        "kind": False,
1040        "shallow": False,
1041        "expression": False,
1042    }
arg_types = {'this': True, 'when': False, 'kind': False, 'shallow': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1045class Describe(Expression):
1046    arg_types = {"this": True, "kind": False, "expressions": False}
arg_types = {'this': True, 'kind': False, 'expressions': False}
key = 'describe'
class Pragma(Expression):
1049class Pragma(Expression):
1050    pass
key = 'pragma'
class Set(Expression):
1053class Set(Expression):
1054    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1057class SetItem(Expression):
1058    arg_types = {
1059        "this": False,
1060        "expressions": False,
1061        "kind": False,
1062        "collate": False,  # MySQL SET NAMES statement
1063        "global": False,
1064    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1067class Show(Expression):
1068    arg_types = {
1069        "this": True,
1070        "target": False,
1071        "offset": False,
1072        "limit": False,
1073        "like": False,
1074        "where": False,
1075        "db": False,
1076        "scope": False,
1077        "scope_kind": False,
1078        "full": False,
1079        "mutex": False,
1080        "query": False,
1081        "channel": False,
1082        "global": False,
1083        "log": False,
1084        "position": False,
1085        "types": False,
1086    }
arg_types = {'this': True, 'target': False, 'offset': False, 'limit': False, 'like': False, 'where': False, 'db': False, 'scope': False, 'scope_kind': False, 'full': False, 'mutex': False, 'query': False, 'channel': False, 'global': False, 'log': False, 'position': False, 'types': False}
key = 'show'
class UserDefinedFunction(Expression):
1089class UserDefinedFunction(Expression):
1090    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1093class CharacterSet(Expression):
1094    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1097class With(Expression):
1098    arg_types = {"expressions": True, "recursive": False}
1099
1100    @property
1101    def recursive(self) -> bool:
1102        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1105class WithinGroup(Expression):
1106    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1109class CTE(DerivedTable):
1110    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1113class TableAlias(Expression):
1114    arg_types = {"this": False, "columns": False}
1115
1116    @property
1117    def columns(self):
1118        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1121class BitString(Condition):
1122    pass
key = 'bitstring'
class HexString(Condition):
1125class HexString(Condition):
1126    pass
key = 'hexstring'
class ByteString(Condition):
1129class ByteString(Condition):
1130    pass
key = 'bytestring'
class RawString(Condition):
1133class RawString(Condition):
1134    pass
key = 'rawstring'
class Column(Condition):
1137class Column(Condition):
1138    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1139
1140    @property
1141    def table(self) -> str:
1142        return self.text("table")
1143
1144    @property
1145    def db(self) -> str:
1146        return self.text("db")
1147
1148    @property
1149    def catalog(self) -> str:
1150        return self.text("catalog")
1151
1152    @property
1153    def output_name(self) -> str:
1154        return self.name
1155
1156    @property
1157    def parts(self) -> t.List[Identifier]:
1158        """Return the parts of a column in order catalog, db, table, name."""
1159        return [
1160            t.cast(Identifier, self.args[part])
1161            for part in ("catalog", "db", "table", "this")
1162            if self.args.get(part)
1163        ]
1164
1165    def to_dot(self) -> Dot:
1166        """Converts the column into a dot expression."""
1167        parts = self.parts
1168        parent = self.parent
1169
1170        while parent:
1171            if isinstance(parent, Dot):
1172                parts.append(parent.expression)
1173            parent = parent.parent
1174
1175        return Dot.build(deepcopy(parts))
arg_types = {'this': True, 'table': False, 'db': False, 'catalog': False, 'join_mark': False}
table: str
db: str
catalog: str
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
parts: List[Identifier]

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

def to_dot(self) -> Dot:
1165    def to_dot(self) -> Dot:
1166        """Converts the column into a dot expression."""
1167        parts = self.parts
1168        parent = self.parent
1169
1170        while parent:
1171            if isinstance(parent, Dot):
1172                parts.append(parent.expression)
1173            parent = parent.parent
1174
1175        return Dot.build(deepcopy(parts))

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1178class ColumnPosition(Expression):
1179    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1182class ColumnDef(Expression):
1183    arg_types = {
1184        "this": True,
1185        "kind": False,
1186        "constraints": False,
1187        "exists": False,
1188        "position": False,
1189    }
1190
1191    @property
1192    def constraints(self) -> t.List[ColumnConstraint]:
1193        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
constraints: List[ColumnConstraint]
key = 'columndef'
class AlterColumn(Expression):
1196class AlterColumn(Expression):
1197    arg_types = {
1198        "this": True,
1199        "dtype": False,
1200        "collate": False,
1201        "using": False,
1202        "default": False,
1203        "drop": False,
1204    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1207class RenameTable(Expression):
1208    pass
key = 'renametable'
class Comment(Expression):
1211class Comment(Expression):
1212    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
arg_types = {'this': True, 'kind': True, 'expression': True, 'exists': False}
key = 'comment'
class Comprehension(Expression):
1215class Comprehension(Expression):
1216    arg_types = {"this": True, "expression": True, "iterator": True, "condition": False}
arg_types = {'this': True, 'expression': True, 'iterator': True, 'condition': False}
key = 'comprehension'
class MergeTreeTTLAction(Expression):
1220class MergeTreeTTLAction(Expression):
1221    arg_types = {
1222        "this": True,
1223        "delete": False,
1224        "recompress": False,
1225        "to_disk": False,
1226        "to_volume": False,
1227    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1231class MergeTreeTTL(Expression):
1232    arg_types = {
1233        "expressions": True,
1234        "where": False,
1235        "group": False,
1236        "aggregates": False,
1237    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class IndexConstraintOption(Expression):
1241class IndexConstraintOption(Expression):
1242    arg_types = {
1243        "key_block_size": False,
1244        "using": False,
1245        "parser": False,
1246        "comment": False,
1247        "visible": False,
1248        "engine_attr": False,
1249        "secondary_engine_attr": False,
1250    }
arg_types = {'key_block_size': False, 'using': False, 'parser': False, 'comment': False, 'visible': False, 'engine_attr': False, 'secondary_engine_attr': False}
key = 'indexconstraintoption'
class ColumnConstraint(Expression):
1253class ColumnConstraint(Expression):
1254    arg_types = {"this": False, "kind": True}
1255
1256    @property
1257    def kind(self) -> ColumnConstraintKind:
1258        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1261class ColumnConstraintKind(Expression):
1262    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1265class AutoIncrementColumnConstraint(ColumnConstraintKind):
1266    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1269class CaseSpecificColumnConstraint(ColumnConstraintKind):
1270    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1273class CharacterSetColumnConstraint(ColumnConstraintKind):
1274    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1277class CheckColumnConstraint(ColumnConstraintKind):
1278    pass
key = 'checkcolumnconstraint'
class ClusteredColumnConstraint(ColumnConstraintKind):
1281class ClusteredColumnConstraint(ColumnConstraintKind):
1282    pass
key = 'clusteredcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1285class CollateColumnConstraint(ColumnConstraintKind):
1286    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1289class CommentColumnConstraint(ColumnConstraintKind):
1290    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1293class CompressColumnConstraint(ColumnConstraintKind):
1294    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1297class DateFormatColumnConstraint(ColumnConstraintKind):
1298    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1301class DefaultColumnConstraint(ColumnConstraintKind):
1302    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1305class EncodeColumnConstraint(ColumnConstraintKind):
1306    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1309class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1310    # this: True -> ALWAYS, this: False -> BY DEFAULT
1311    arg_types = {
1312        "this": False,
1313        "expression": False,
1314        "on_null": False,
1315        "start": False,
1316        "increment": False,
1317        "minvalue": False,
1318        "maxvalue": False,
1319        "cycle": False,
1320    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class IndexColumnConstraint(ColumnConstraintKind):
1324class IndexColumnConstraint(ColumnConstraintKind):
1325    arg_types = {"this": False, "schema": True, "kind": False, "type": False, "options": False}
arg_types = {'this': False, 'schema': True, 'kind': False, 'type': False, 'options': False}
key = 'indexcolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1328class InlineLengthColumnConstraint(ColumnConstraintKind):
1329    pass
key = 'inlinelengthcolumnconstraint'
class NonClusteredColumnConstraint(ColumnConstraintKind):
1332class NonClusteredColumnConstraint(ColumnConstraintKind):
1333    pass
key = 'nonclusteredcolumnconstraint'
class NotForReplicationColumnConstraint(ColumnConstraintKind):
1336class NotForReplicationColumnConstraint(ColumnConstraintKind):
1337    arg_types = {}
arg_types = {}
key = 'notforreplicationcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1340class NotNullColumnConstraint(ColumnConstraintKind):
1341    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1345class OnUpdateColumnConstraint(ColumnConstraintKind):
1346    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1349class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1350    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1353class TitleColumnConstraint(ColumnConstraintKind):
1354    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1357class UniqueColumnConstraint(ColumnConstraintKind):
1358    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1361class UppercaseColumnConstraint(ColumnConstraintKind):
1362    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1365class PathColumnConstraint(ColumnConstraintKind):
1366    pass
key = 'pathcolumnconstraint'
class ComputedColumnConstraint(ColumnConstraintKind):
1371class ComputedColumnConstraint(ColumnConstraintKind):
1372    arg_types = {"this": True, "persisted": False, "not_null": False}
arg_types = {'this': True, 'persisted': False, 'not_null': False}
key = 'computedcolumnconstraint'
class Constraint(Expression):
1375class Constraint(Expression):
1376    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1379class Delete(Expression):
1380    arg_types = {
1381        "with": False,
1382        "this": False,
1383        "using": False,
1384        "where": False,
1385        "returning": False,
1386        "limit": False,
1387        "tables": False,  # Multiple-Table Syntax (MySQL)
1388    }
1389
1390    def delete(
1391        self,
1392        table: ExpOrStr,
1393        dialect: DialectType = None,
1394        copy: bool = True,
1395        **opts,
1396    ) -> Delete:
1397        """
1398        Create a DELETE expression or replace the table on an existing DELETE expression.
1399
1400        Example:
1401            >>> delete("tbl").sql()
1402            'DELETE FROM tbl'
1403
1404        Args:
1405            table: the table from which to delete.
1406            dialect: the dialect used to parse the input expression.
1407            copy: if `False`, modify this expression instance in-place.
1408            opts: other options to use to parse the input expressions.
1409
1410        Returns:
1411            Delete: the modified expression.
1412        """
1413        return _apply_builder(
1414            expression=table,
1415            instance=self,
1416            arg="this",
1417            dialect=dialect,
1418            into=Table,
1419            copy=copy,
1420            **opts,
1421        )
1422
1423    def where(
1424        self,
1425        *expressions: t.Optional[ExpOrStr],
1426        append: bool = True,
1427        dialect: DialectType = None,
1428        copy: bool = True,
1429        **opts,
1430    ) -> Delete:
1431        """
1432        Append to or set the WHERE expressions.
1433
1434        Example:
1435            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1436            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1437
1438        Args:
1439            *expressions: the SQL code strings to parse.
1440                If an `Expression` instance is passed, it will be used as-is.
1441                Multiple expressions are combined with an AND operator.
1442            append: if `True`, AND the new expressions to any existing expression.
1443                Otherwise, this resets the expression.
1444            dialect: the dialect used to parse the input expressions.
1445            copy: if `False`, modify this expression instance in-place.
1446            opts: other options to use to parse the input expressions.
1447
1448        Returns:
1449            Delete: the modified expression.
1450        """
1451        return _apply_conjunction_builder(
1452            *expressions,
1453            instance=self,
1454            arg="where",
1455            append=append,
1456            into=Where,
1457            dialect=dialect,
1458            copy=copy,
1459            **opts,
1460        )
1461
1462    def returning(
1463        self,
1464        expression: ExpOrStr,
1465        dialect: DialectType = None,
1466        copy: bool = True,
1467        **opts,
1468    ) -> Delete:
1469        """
1470        Set the RETURNING expression. Not supported by all dialects.
1471
1472        Example:
1473            >>> delete("tbl").returning("*", dialect="postgres").sql()
1474            'DELETE FROM tbl RETURNING *'
1475
1476        Args:
1477            expression: the SQL code strings to parse.
1478                If an `Expression` instance is passed, it will be used as-is.
1479            dialect: the dialect used to parse the input expressions.
1480            copy: if `False`, modify this expression instance in-place.
1481            opts: other options to use to parse the input expressions.
1482
1483        Returns:
1484            Delete: the modified expression.
1485        """
1486        return _apply_builder(
1487            expression=expression,
1488            instance=self,
1489            arg="returning",
1490            prefix="RETURNING",
1491            dialect=dialect,
1492            copy=copy,
1493            into=Returning,
1494            **opts,
1495        )
arg_types = {'with': False, 'this': False, 'using': False, 'where': False, 'returning': False, 'limit': False, 'tables': False}
def delete( self, table: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Delete:
1390    def delete(
1391        self,
1392        table: ExpOrStr,
1393        dialect: DialectType = None,
1394        copy: bool = True,
1395        **opts,
1396    ) -> Delete:
1397        """
1398        Create a DELETE expression or replace the table on an existing DELETE expression.
1399
1400        Example:
1401            >>> delete("tbl").sql()
1402            'DELETE FROM tbl'
1403
1404        Args:
1405            table: the table from which to delete.
1406            dialect: the dialect used to parse the input expression.
1407            copy: if `False`, modify this expression instance in-place.
1408            opts: other options to use to parse the input expressions.
1409
1410        Returns:
1411            Delete: the modified expression.
1412        """
1413        return _apply_builder(
1414            expression=table,
1415            instance=self,
1416            arg="this",
1417            dialect=dialect,
1418            into=Table,
1419            copy=copy,
1420            **opts,
1421        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Delete:
1423    def where(
1424        self,
1425        *expressions: t.Optional[ExpOrStr],
1426        append: bool = True,
1427        dialect: DialectType = None,
1428        copy: bool = True,
1429        **opts,
1430    ) -> Delete:
1431        """
1432        Append to or set the WHERE expressions.
1433
1434        Example:
1435            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1436            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1437
1438        Args:
1439            *expressions: the SQL code strings to parse.
1440                If an `Expression` instance is passed, it will be used as-is.
1441                Multiple expressions are combined with an AND operator.
1442            append: if `True`, AND the new expressions to any existing expression.
1443                Otherwise, this resets the expression.
1444            dialect: the dialect used to parse the input expressions.
1445            copy: if `False`, modify this expression instance in-place.
1446            opts: other options to use to parse the input expressions.
1447
1448        Returns:
1449            Delete: the modified expression.
1450        """
1451        return _apply_conjunction_builder(
1452            *expressions,
1453            instance=self,
1454            arg="where",
1455            append=append,
1456            into=Where,
1457            dialect=dialect,
1458            copy=copy,
1459            **opts,
1460        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Delete:
1462    def returning(
1463        self,
1464        expression: ExpOrStr,
1465        dialect: DialectType = None,
1466        copy: bool = True,
1467        **opts,
1468    ) -> Delete:
1469        """
1470        Set the RETURNING expression. Not supported by all dialects.
1471
1472        Example:
1473            >>> delete("tbl").returning("*", dialect="postgres").sql()
1474            'DELETE FROM tbl RETURNING *'
1475
1476        Args:
1477            expression: the SQL code strings to parse.
1478                If an `Expression` instance is passed, it will be used as-is.
1479            dialect: the dialect used to parse the input expressions.
1480            copy: if `False`, modify this expression instance in-place.
1481            opts: other options to use to parse the input expressions.
1482
1483        Returns:
1484            Delete: the modified expression.
1485        """
1486        return _apply_builder(
1487            expression=expression,
1488            instance=self,
1489            arg="returning",
1490            prefix="RETURNING",
1491            dialect=dialect,
1492            copy=copy,
1493            into=Returning,
1494            **opts,
1495        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

key = 'delete'
class Drop(Expression):
1498class Drop(Expression):
1499    arg_types = {
1500        "this": False,
1501        "kind": False,
1502        "exists": False,
1503        "temporary": False,
1504        "materialized": False,
1505        "cascade": False,
1506        "constraints": False,
1507        "purge": False,
1508    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1511class Filter(Expression):
1512    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1515class Check(Expression):
1516    pass
key = 'check'
class Connect(Expression):
1520class Connect(Expression):
1521    arg_types = {"start": False, "connect": True}
arg_types = {'start': False, 'connect': True}
key = 'connect'
class Prior(Expression):
1524class Prior(Expression):
1525    pass
key = 'prior'
class Directory(Expression):
1528class Directory(Expression):
1529    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1530    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1533class ForeignKey(Expression):
1534    arg_types = {
1535        "expressions": True,
1536        "reference": False,
1537        "delete": False,
1538        "update": False,
1539    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class ColumnPrefix(Expression):
1542class ColumnPrefix(Expression):
1543    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'columnprefix'
class PrimaryKey(Expression):
1546class PrimaryKey(Expression):
1547    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1552class Into(Expression):
1553    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1556class From(Expression):
1557    @property
1558    def name(self) -> str:
1559        return self.this.name
1560
1561    @property
1562    def alias_or_name(self) -> str:
1563        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1566class Having(Expression):
1567    pass
key = 'having'
class Hint(Expression):
1570class Hint(Expression):
1571    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1574class JoinHint(Expression):
1575    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1578class Identifier(Expression):
1579    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1580
1581    @property
1582    def quoted(self) -> bool:
1583        return bool(self.args.get("quoted"))
1584
1585    @property
1586    def hashable_args(self) -> t.Any:
1587        return (self.this, self.quoted)
1588
1589    @property
1590    def output_name(self) -> str:
1591        return self.name
arg_types = {'this': True, 'quoted': False, 'global': False, 'temporary': False}
quoted: bool
hashable_args: Any
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'identifier'
class Index(Expression):
1594class Index(Expression):
1595    arg_types = {
1596        "this": False,
1597        "table": False,
1598        "using": False,
1599        "where": False,
1600        "columns": False,
1601        "unique": False,
1602        "primary": False,
1603        "amp": False,  # teradata
1604        "partition_by": False,  # teradata
1605    }
arg_types = {'this': False, 'table': False, 'using': False, 'where': False, 'columns': False, 'unique': False, 'primary': False, 'amp': False, 'partition_by': False}
key = 'index'
class Insert(DDL):
1608class Insert(DDL):
1609    arg_types = {
1610        "with": False,
1611        "this": True,
1612        "expression": False,
1613        "conflict": False,
1614        "returning": False,
1615        "overwrite": False,
1616        "exists": False,
1617        "partition": False,
1618        "alternative": False,
1619        "where": False,
1620        "ignore": False,
1621        "by_name": False,
1622    }
1623
1624    def with_(
1625        self,
1626        alias: ExpOrStr,
1627        as_: ExpOrStr,
1628        recursive: t.Optional[bool] = None,
1629        append: bool = True,
1630        dialect: DialectType = None,
1631        copy: bool = True,
1632        **opts,
1633    ) -> Insert:
1634        """
1635        Append to or set the common table expressions.
1636
1637        Example:
1638            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1639            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1640
1641        Args:
1642            alias: the SQL code string to parse as the table name.
1643                If an `Expression` instance is passed, this is used as-is.
1644            as_: the SQL code string to parse as the table expression.
1645                If an `Expression` instance is passed, it will be used as-is.
1646            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1647            append: if `True`, add to any existing expressions.
1648                Otherwise, this resets the expressions.
1649            dialect: the dialect used to parse the input expression.
1650            copy: if `False`, modify this expression instance in-place.
1651            opts: other options to use to parse the input expressions.
1652
1653        Returns:
1654            The modified expression.
1655        """
1656        return _apply_cte_builder(
1657            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1658        )
arg_types = {'with': False, 'this': True, 'expression': False, 'conflict': False, 'returning': False, 'overwrite': False, 'exists': False, 'partition': False, 'alternative': False, 'where': False, 'ignore': False, 'by_name': False}
def with_( self, alias: Union[str, Expression], as_: Union[str, Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Insert:
1624    def with_(
1625        self,
1626        alias: ExpOrStr,
1627        as_: ExpOrStr,
1628        recursive: t.Optional[bool] = None,
1629        append: bool = True,
1630        dialect: DialectType = None,
1631        copy: bool = True,
1632        **opts,
1633    ) -> Insert:
1634        """
1635        Append to or set the common table expressions.
1636
1637        Example:
1638            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1639            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1640
1641        Args:
1642            alias: the SQL code string to parse as the table name.
1643                If an `Expression` instance is passed, this is used as-is.
1644            as_: the SQL code string to parse as the table expression.
1645                If an `Expression` instance is passed, it will be used as-is.
1646            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1647            append: if `True`, add to any existing expressions.
1648                Otherwise, this resets the expressions.
1649            dialect: the dialect used to parse the input expression.
1650            copy: if `False`, modify this expression instance in-place.
1651            opts: other options to use to parse the input expressions.
1652
1653        Returns:
1654            The modified expression.
1655        """
1656        return _apply_cte_builder(
1657            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1658        )

Append to or set the common table expressions.

Example:
>>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'insert'
class OnConflict(Expression):
1661class OnConflict(Expression):
1662    arg_types = {
1663        "duplicate": False,
1664        "expressions": False,
1665        "nothing": False,
1666        "key": False,
1667        "constraint": False,
1668    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1671class Returning(Expression):
1672    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1676class Introducer(Expression):
1677    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1681class National(Expression):
1682    pass
key = 'national'
class LoadData(Expression):
1685class LoadData(Expression):
1686    arg_types = {
1687        "this": True,
1688        "local": False,
1689        "overwrite": False,
1690        "inpath": True,
1691        "partition": False,
1692        "input_format": False,
1693        "serde": False,
1694    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1697class Partition(Expression):
1698    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1701class Fetch(Expression):
1702    arg_types = {
1703        "direction": False,
1704        "count": False,
1705        "percent": False,
1706        "with_ties": False,
1707    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1710class Group(Expression):
1711    arg_types = {
1712        "expressions": False,
1713        "grouping_sets": False,
1714        "cube": False,
1715        "rollup": False,
1716        "totals": False,
1717        "all": False,
1718    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1721class Lambda(Expression):
1722    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1725class Limit(Expression):
1726    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1729class Literal(Condition):
1730    arg_types = {"this": True, "is_string": True}
1731
1732    @property
1733    def hashable_args(self) -> t.Any:
1734        return (self.this, self.args.get("is_string"))
1735
1736    @classmethod
1737    def number(cls, number) -> Literal:
1738        return cls(this=str(number), is_string=False)
1739
1740    @classmethod
1741    def string(cls, string) -> Literal:
1742        return cls(this=str(string), is_string=True)
1743
1744    @property
1745    def output_name(self) -> str:
1746        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> Literal:
1736    @classmethod
1737    def number(cls, number) -> Literal:
1738        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> Literal:
1740    @classmethod
1741    def string(cls, string) -> Literal:
1742        return cls(this=str(string), is_string=True)
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'literal'
class Join(Expression):
1749class Join(Expression):
1750    arg_types = {
1751        "this": True,
1752        "on": False,
1753        "side": False,
1754        "kind": False,
1755        "using": False,
1756        "method": False,
1757        "global": False,
1758        "hint": False,
1759    }
1760
1761    @property
1762    def method(self) -> str:
1763        return self.text("method").upper()
1764
1765    @property
1766    def kind(self) -> str:
1767        return self.text("kind").upper()
1768
1769    @property
1770    def side(self) -> str:
1771        return self.text("side").upper()
1772
1773    @property
1774    def hint(self) -> str:
1775        return self.text("hint").upper()
1776
1777    @property
1778    def alias_or_name(self) -> str:
1779        return self.this.alias_or_name
1780
1781    def on(
1782        self,
1783        *expressions: t.Optional[ExpOrStr],
1784        append: bool = True,
1785        dialect: DialectType = None,
1786        copy: bool = True,
1787        **opts,
1788    ) -> Join:
1789        """
1790        Append to or set the ON expressions.
1791
1792        Example:
1793            >>> import sqlglot
1794            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1795            'JOIN x ON y = 1'
1796
1797        Args:
1798            *expressions: the SQL code strings to parse.
1799                If an `Expression` instance is passed, it will be used as-is.
1800                Multiple expressions are combined with an AND operator.
1801            append: if `True`, AND the new expressions to any existing expression.
1802                Otherwise, this resets the expression.
1803            dialect: the dialect used to parse the input expressions.
1804            copy: if `False`, modify this expression instance in-place.
1805            opts: other options to use to parse the input expressions.
1806
1807        Returns:
1808            The modified Join expression.
1809        """
1810        join = _apply_conjunction_builder(
1811            *expressions,
1812            instance=self,
1813            arg="on",
1814            append=append,
1815            dialect=dialect,
1816            copy=copy,
1817            **opts,
1818        )
1819
1820        if join.kind == "CROSS":
1821            join.set("kind", None)
1822
1823        return join
1824
1825    def using(
1826        self,
1827        *expressions: t.Optional[ExpOrStr],
1828        append: bool = True,
1829        dialect: DialectType = None,
1830        copy: bool = True,
1831        **opts,
1832    ) -> Join:
1833        """
1834        Append to or set the USING expressions.
1835
1836        Example:
1837            >>> import sqlglot
1838            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1839            'JOIN x USING (foo, bla)'
1840
1841        Args:
1842            *expressions: the SQL code strings to parse.
1843                If an `Expression` instance is passed, it will be used as-is.
1844            append: if `True`, concatenate the new expressions to the existing "using" list.
1845                Otherwise, this resets the expression.
1846            dialect: the dialect used to parse the input expressions.
1847            copy: if `False`, modify this expression instance in-place.
1848            opts: other options to use to parse the input expressions.
1849
1850        Returns:
1851            The modified Join expression.
1852        """
1853        join = _apply_list_builder(
1854            *expressions,
1855            instance=self,
1856            arg="using",
1857            append=append,
1858            dialect=dialect,
1859            copy=copy,
1860            **opts,
1861        )
1862
1863        if join.kind == "CROSS":
1864            join.set("kind", None)
1865
1866        return join
arg_types = {'this': True, 'on': False, 'side': False, 'kind': False, 'using': False, 'method': False, 'global': False, 'hint': False}
method: str
kind: str
side: str
hint: str
alias_or_name: str
def on( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Join:
1781    def on(
1782        self,
1783        *expressions: t.Optional[ExpOrStr],
1784        append: bool = True,
1785        dialect: DialectType = None,
1786        copy: bool = True,
1787        **opts,
1788    ) -> Join:
1789        """
1790        Append to or set the ON expressions.
1791
1792        Example:
1793            >>> import sqlglot
1794            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1795            'JOIN x ON y = 1'
1796
1797        Args:
1798            *expressions: the SQL code strings to parse.
1799                If an `Expression` instance is passed, it will be used as-is.
1800                Multiple expressions are combined with an AND operator.
1801            append: if `True`, AND the new expressions to any existing expression.
1802                Otherwise, this resets the expression.
1803            dialect: the dialect used to parse the input expressions.
1804            copy: if `False`, modify this expression instance in-place.
1805            opts: other options to use to parse the input expressions.
1806
1807        Returns:
1808            The modified Join expression.
1809        """
1810        join = _apply_conjunction_builder(
1811            *expressions,
1812            instance=self,
1813            arg="on",
1814            append=append,
1815            dialect=dialect,
1816            copy=copy,
1817            **opts,
1818        )
1819
1820        if join.kind == "CROSS":
1821            join.set("kind", None)
1822
1823        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

def using( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Join:
1825    def using(
1826        self,
1827        *expressions: t.Optional[ExpOrStr],
1828        append: bool = True,
1829        dialect: DialectType = None,
1830        copy: bool = True,
1831        **opts,
1832    ) -> Join:
1833        """
1834        Append to or set the USING expressions.
1835
1836        Example:
1837            >>> import sqlglot
1838            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1839            'JOIN x USING (foo, bla)'
1840
1841        Args:
1842            *expressions: the SQL code strings to parse.
1843                If an `Expression` instance is passed, it will be used as-is.
1844            append: if `True`, concatenate the new expressions to the existing "using" list.
1845                Otherwise, this resets the expression.
1846            dialect: the dialect used to parse the input expressions.
1847            copy: if `False`, modify this expression instance in-place.
1848            opts: other options to use to parse the input expressions.
1849
1850        Returns:
1851            The modified Join expression.
1852        """
1853        join = _apply_list_builder(
1854            *expressions,
1855            instance=self,
1856            arg="using",
1857            append=append,
1858            dialect=dialect,
1859            copy=copy,
1860            **opts,
1861        )
1862
1863        if join.kind == "CROSS":
1864            join.set("kind", None)
1865
1866        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

key = 'join'
class Lateral(UDTF):
1869class Lateral(UDTF):
1870    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
arg_types = {'this': True, 'view': False, 'outer': False, 'alias': False}
key = 'lateral'
class MatchRecognize(Expression):
1873class MatchRecognize(Expression):
1874    arg_types = {
1875        "partition_by": False,
1876        "order": False,
1877        "measures": False,
1878        "rows": False,
1879        "after": False,
1880        "pattern": False,
1881        "define": False,
1882        "alias": False,
1883    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1888class Final(Expression):
1889    pass
key = 'final'
class Offset(Expression):
1892class Offset(Expression):
1893    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1896class Order(Expression):
1897    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1902class Cluster(Order):
1903    pass
key = 'cluster'
class Distribute(Order):
1906class Distribute(Order):
1907    pass
key = 'distribute'
class Sort(Order):
1910class Sort(Order):
1911    pass
key = 'sort'
class Ordered(Expression):
1914class Ordered(Expression):
1915    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1918class Property(Expression):
1919    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1922class AlgorithmProperty(Property):
1923    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1926class AutoIncrementProperty(Property):
1927    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1930class BlockCompressionProperty(Property):
1931    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
arg_types = {'autotemp': False, 'always': False, 'default': True, 'manual': True, 'never': True}
key = 'blockcompressionproperty'
class CharacterSetProperty(Property):
1934class CharacterSetProperty(Property):
1935    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1938class ChecksumProperty(Property):
1939    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1942class CollateProperty(Property):
1943    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1946class CopyGrantsProperty(Property):
1947    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1950class DataBlocksizeProperty(Property):
1951    arg_types = {
1952        "size": False,
1953        "units": False,
1954        "minimum": False,
1955        "maximum": False,
1956        "default": False,
1957    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1960class DefinerProperty(Property):
1961    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1964class DistKeyProperty(Property):
1965    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1968class DistStyleProperty(Property):
1969    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1972class EngineProperty(Property):
1973    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
1976class HeapProperty(Property):
1977    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
1980class ToTableProperty(Property):
1981    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1984class ExecuteAsProperty(Property):
1985    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1988class ExternalProperty(Property):
1989    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1992class FallbackProperty(Property):
1993    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1996class FileFormatProperty(Property):
1997    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
2000class FreespaceProperty(Property):
2001    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
2004class InputOutputFormat(Expression):
2005    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
2008class IsolatedLoadingProperty(Property):
2009    arg_types = {
2010        "no": True,
2011        "concurrent": True,
2012        "for_all": True,
2013        "for_insert": True,
2014        "for_none": True,
2015    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
2018class JournalProperty(Property):
2019    arg_types = {
2020        "no": False,
2021        "dual": False,
2022        "before": False,
2023        "local": False,
2024        "after": False,
2025    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
2028class LanguageProperty(Property):
2029    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
2033class ClusteredByProperty(Property):
2034    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
2037class DictProperty(Property):
2038    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2041class DictSubProperty(Property):
2042    pass
key = 'dictsubproperty'
class DictRange(Property):
2045class DictRange(Property):
2046    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2051class OnCluster(Property):
2052    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2055class LikeProperty(Property):
2056    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2059class LocationProperty(Property):
2060    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2063class LockingProperty(Property):
2064    arg_types = {
2065        "this": False,
2066        "kind": True,
2067        "for_or_in": True,
2068        "lock_type": True,
2069        "override": False,
2070    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2073class LogProperty(Property):
2074    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2077class MaterializedProperty(Property):
2078    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2081class MergeBlockRatioProperty(Property):
2082    arg_types = {"this": False, "no": False, "default": False, "percent": False}
arg_types = {'this': False, 'no': False, 'default': False, 'percent': False}
key = 'mergeblockratioproperty'
class NoPrimaryIndexProperty(Property):
2085class NoPrimaryIndexProperty(Property):
2086    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnProperty(Property):
2089class OnProperty(Property):
2090    arg_types = {"this": True}
arg_types = {'this': True}
key = 'onproperty'
class OnCommitProperty(Property):
2093class OnCommitProperty(Property):
2094    arg_types = {"delete": False}
arg_types = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2097class PartitionedByProperty(Property):
2098    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2101class ReturnsProperty(Property):
2102    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2105class RowFormatProperty(Property):
2106    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2109class RowFormatDelimitedProperty(Property):
2110    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2111    arg_types = {
2112        "fields": False,
2113        "escaped": False,
2114        "collection_items": False,
2115        "map_keys": False,
2116        "lines": False,
2117        "null": False,
2118        "serde": False,
2119    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2122class RowFormatSerdeProperty(Property):
2123    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2127class QueryTransform(Expression):
2128    arg_types = {
2129        "expressions": True,
2130        "command_script": True,
2131        "schema": False,
2132        "row_format_before": False,
2133        "record_writer": False,
2134        "row_format_after": False,
2135        "record_reader": False,
2136    }
arg_types = {'expressions': True, 'command_script': True, 'schema': False, 'row_format_before': False, 'record_writer': False, 'row_format_after': False, 'record_reader': False}
key = 'querytransform'
class SchemaCommentProperty(Property):
2139class SchemaCommentProperty(Property):
2140    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2143class SerdeProperties(Property):
2144    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2147class SetProperty(Property):
2148    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2151class SettingsProperty(Property):
2152    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2155class SortKeyProperty(Property):
2156    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2159class SqlSecurityProperty(Property):
2160    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2163class StabilityProperty(Property):
2164    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2167class TemporaryProperty(Property):
2168    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2171class TransientProperty(Property):
2172    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2175class VolatileProperty(Property):
2176    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2179class WithDataProperty(Property):
2180    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2183class WithJournalTableProperty(Property):
2184    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2187class Properties(Expression):
2188    arg_types = {"expressions": True}
2189
2190    NAME_TO_PROPERTY = {
2191        "ALGORITHM": AlgorithmProperty,
2192        "AUTO_INCREMENT": AutoIncrementProperty,
2193        "CHARACTER SET": CharacterSetProperty,
2194        "CLUSTERED_BY": ClusteredByProperty,
2195        "COLLATE": CollateProperty,
2196        "COMMENT": SchemaCommentProperty,
2197        "DEFINER": DefinerProperty,
2198        "DISTKEY": DistKeyProperty,
2199        "DISTSTYLE": DistStyleProperty,
2200        "ENGINE": EngineProperty,
2201        "EXECUTE AS": ExecuteAsProperty,
2202        "FORMAT": FileFormatProperty,
2203        "LANGUAGE": LanguageProperty,
2204        "LOCATION": LocationProperty,
2205        "PARTITIONED_BY": PartitionedByProperty,
2206        "RETURNS": ReturnsProperty,
2207        "ROW_FORMAT": RowFormatProperty,
2208        "SORTKEY": SortKeyProperty,
2209    }
2210
2211    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2212
2213    # CREATE property locations
2214    # Form: schema specified
2215    #   create [POST_CREATE]
2216    #     table a [POST_NAME]
2217    #     (b int) [POST_SCHEMA]
2218    #     with ([POST_WITH])
2219    #     index (b) [POST_INDEX]
2220    #
2221    # Form: alias selection
2222    #   create [POST_CREATE]
2223    #     table a [POST_NAME]
2224    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2225    #     index (c) [POST_INDEX]
2226    class Location(AutoName):
2227        POST_CREATE = auto()
2228        POST_NAME = auto()
2229        POST_SCHEMA = auto()
2230        POST_WITH = auto()
2231        POST_ALIAS = auto()
2232        POST_EXPRESSION = auto()
2233        POST_INDEX = auto()
2234        UNSUPPORTED = auto()
2235
2236    @classmethod
2237    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2238        expressions = []
2239        for key, value in properties_dict.items():
2240            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2241            if property_cls:
2242                expressions.append(property_cls(this=convert(value)))
2243            else:
2244                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2245
2246        return cls(expressions=expressions)
arg_types = {'expressions': True}
NAME_TO_PROPERTY = {'ALGORITHM': <class 'AlgorithmProperty'>, 'AUTO_INCREMENT': <class 'AutoIncrementProperty'>, 'CHARACTER SET': <class 'CharacterSetProperty'>, 'CLUSTERED_BY': <class 'ClusteredByProperty'>, 'COLLATE': <class 'CollateProperty'>, 'COMMENT': <class 'SchemaCommentProperty'>, 'DEFINER': <class 'DefinerProperty'>, 'DISTKEY': <class 'DistKeyProperty'>, 'DISTSTYLE': <class 'DistStyleProperty'>, 'ENGINE': <class 'EngineProperty'>, 'EXECUTE AS': <class 'ExecuteAsProperty'>, 'FORMAT': <class 'FileFormatProperty'>, 'LANGUAGE': <class 'LanguageProperty'>, 'LOCATION': <class 'LocationProperty'>, 'PARTITIONED_BY': <class 'PartitionedByProperty'>, 'RETURNS': <class 'ReturnsProperty'>, 'ROW_FORMAT': <class 'RowFormatProperty'>, 'SORTKEY': <class 'SortKeyProperty'>}
PROPERTY_TO_NAME = {<class 'AlgorithmProperty'>: 'ALGORITHM', <class 'AutoIncrementProperty'>: 'AUTO_INCREMENT', <class 'CharacterSetProperty'>: 'CHARACTER SET', <class 'ClusteredByProperty'>: 'CLUSTERED_BY', <class 'CollateProperty'>: 'COLLATE', <class 'SchemaCommentProperty'>: 'COMMENT', <class 'DefinerProperty'>: 'DEFINER', <class 'DistKeyProperty'>: 'DISTKEY', <class 'DistStyleProperty'>: 'DISTSTYLE', <class 'EngineProperty'>: 'ENGINE', <class 'ExecuteAsProperty'>: 'EXECUTE AS', <class 'FileFormatProperty'>: 'FORMAT', <class 'LanguageProperty'>: 'LANGUAGE', <class 'LocationProperty'>: 'LOCATION', <class 'PartitionedByProperty'>: 'PARTITIONED_BY', <class 'ReturnsProperty'>: 'RETURNS', <class 'RowFormatProperty'>: 'ROW_FORMAT', <class 'SortKeyProperty'>: 'SORTKEY'}
@classmethod
def from_dict(cls, properties_dict: Dict) -> Properties:
2236    @classmethod
2237    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2238        expressions = []
2239        for key, value in properties_dict.items():
2240            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2241            if property_cls:
2242                expressions.append(property_cls(this=convert(value)))
2243            else:
2244                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2245
2246        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2226    class Location(AutoName):
2227        POST_CREATE = auto()
2228        POST_NAME = auto()
2229        POST_SCHEMA = auto()
2230        POST_WITH = auto()
2231        POST_ALIAS = auto()
2232        POST_EXPRESSION = auto()
2233        POST_INDEX = auto()
2234        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
2249class Qualify(Expression):
2250    pass
key = 'qualify'
class Return(Expression):
2254class Return(Expression):
2255    pass
key = 'return'
class Reference(Expression):
2258class Reference(Expression):
2259    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2262class Tuple(Expression):
2263    arg_types = {"expressions": False}
2264
2265    def isin(
2266        self,
2267        *expressions: t.Any,
2268        query: t.Optional[ExpOrStr] = None,
2269        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2270        copy: bool = True,
2271        **opts,
2272    ) -> In:
2273        return In(
2274            this=maybe_copy(self, copy),
2275            expressions=[convert(e, copy=copy) for e in expressions],
2276            query=maybe_parse(query, copy=copy, **opts) if query else None,
2277            unnest=Unnest(
2278                expressions=[
2279                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2280                ]
2281            )
2282            if unnest
2283            else None,
2284        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, Expression, NoneType] = None, unnest: Union[str, Expression, NoneType, Collection[Union[str, Expression]]] = None, copy: bool = True, **opts) -> In:
2265    def isin(
2266        self,
2267        *expressions: t.Any,
2268        query: t.Optional[ExpOrStr] = None,
2269        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2270        copy: bool = True,
2271        **opts,
2272    ) -> In:
2273        return In(
2274            this=maybe_copy(self, copy),
2275            expressions=[convert(e, copy=copy) for e in expressions],
2276            query=maybe_parse(query, copy=copy, **opts) if query else None,
2277            unnest=Unnest(
2278                expressions=[
2279                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2280                ]
2281            )
2282            if unnest
2283            else None,
2284        )
key = 'tuple'
class Subqueryable(Unionable):
2287class Subqueryable(Unionable):
2288    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2289        """
2290        Convert this expression to an aliased expression that can be used as a Subquery.
2291
2292        Example:
2293            >>> subquery = Select().select("x").from_("tbl").subquery()
2294            >>> Select().select("x").from_(subquery).sql()
2295            'SELECT x FROM (SELECT x FROM tbl)'
2296
2297        Args:
2298            alias (str | Identifier): an optional alias for the subquery
2299            copy (bool): if `False`, modify this expression instance in-place.
2300
2301        Returns:
2302            Alias: the subquery
2303        """
2304        instance = maybe_copy(self, copy)
2305        if not isinstance(alias, Expression):
2306            alias = TableAlias(this=to_identifier(alias)) if alias else None
2307
2308        return Subquery(this=instance, alias=alias)
2309
2310    def limit(
2311        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2312    ) -> Select:
2313        raise NotImplementedError
2314
2315    @property
2316    def ctes(self):
2317        with_ = self.args.get("with")
2318        if not with_:
2319            return []
2320        return with_.expressions
2321
2322    @property
2323    def selects(self) -> t.List[Expression]:
2324        raise NotImplementedError("Subqueryable objects must implement `selects`")
2325
2326    @property
2327    def named_selects(self) -> t.List[str]:
2328        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2329
2330    def select(
2331        self,
2332        *expressions: t.Optional[ExpOrStr],
2333        append: bool = True,
2334        dialect: DialectType = None,
2335        copy: bool = True,
2336        **opts,
2337    ) -> Subqueryable:
2338        raise NotImplementedError("Subqueryable objects must implement `select`")
2339
2340    def with_(
2341        self,
2342        alias: ExpOrStr,
2343        as_: ExpOrStr,
2344        recursive: t.Optional[bool] = None,
2345        append: bool = True,
2346        dialect: DialectType = None,
2347        copy: bool = True,
2348        **opts,
2349    ) -> Subqueryable:
2350        """
2351        Append to or set the common table expressions.
2352
2353        Example:
2354            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2355            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2356
2357        Args:
2358            alias: the SQL code string to parse as the table name.
2359                If an `Expression` instance is passed, this is used as-is.
2360            as_: the SQL code string to parse as the table expression.
2361                If an `Expression` instance is passed, it will be used as-is.
2362            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2363            append: if `True`, add to any existing expressions.
2364                Otherwise, this resets the expressions.
2365            dialect: the dialect used to parse the input expression.
2366            copy: if `False`, modify this expression instance in-place.
2367            opts: other options to use to parse the input expressions.
2368
2369        Returns:
2370            The modified expression.
2371        """
2372        return _apply_cte_builder(
2373            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2374        )
def subquery( self, alias: Union[str, Expression, NoneType] = None, copy: bool = True) -> Subquery:
2288    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2289        """
2290        Convert this expression to an aliased expression that can be used as a Subquery.
2291
2292        Example:
2293            >>> subquery = Select().select("x").from_("tbl").subquery()
2294            >>> Select().select("x").from_(subquery).sql()
2295            'SELECT x FROM (SELECT x FROM tbl)'
2296
2297        Args:
2298            alias (str | Identifier): an optional alias for the subquery
2299            copy (bool): if `False`, modify this expression instance in-place.
2300
2301        Returns:
2302            Alias: the subquery
2303        """
2304        instance = maybe_copy(self, copy)
2305        if not isinstance(alias, Expression):
2306            alias = TableAlias(this=to_identifier(alias)) if alias else None
2307
2308        return Subquery(this=instance, alias=alias)

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression: Union[str, Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2310    def limit(
2311        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2312    ) -> Select:
2313        raise NotImplementedError
ctes
selects: List[Expression]
named_selects: List[str]
def select( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Subqueryable:
2330    def select(
2331        self,
2332        *expressions: t.Optional[ExpOrStr],
2333        append: bool = True,
2334        dialect: DialectType = None,
2335        copy: bool = True,
2336        **opts,
2337    ) -> Subqueryable:
2338        raise NotImplementedError("Subqueryable objects must implement `select`")
def with_( self, alias: Union[str, Expression], as_: Union[str, Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Subqueryable:
2340    def with_(
2341        self,
2342        alias: ExpOrStr,
2343        as_: ExpOrStr,
2344        recursive: t.Optional[bool] = None,
2345        append: bool = True,
2346        dialect: DialectType = None,
2347        copy: bool = True,
2348        **opts,
2349    ) -> Subqueryable:
2350        """
2351        Append to or set the common table expressions.
2352
2353        Example:
2354            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2355            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2356
2357        Args:
2358            alias: the SQL code string to parse as the table name.
2359                If an `Expression` instance is passed, this is used as-is.
2360            as_: the SQL code string to parse as the table expression.
2361                If an `Expression` instance is passed, it will be used as-is.
2362            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2363            append: if `True`, add to any existing expressions.
2364                Otherwise, this resets the expressions.
2365            dialect: the dialect used to parse the input expression.
2366            copy: if `False`, modify this expression instance in-place.
2367            opts: other options to use to parse the input expressions.
2368
2369        Returns:
2370            The modified expression.
2371        """
2372        return _apply_cte_builder(
2373            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2374        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'subqueryable'
QUERY_MODIFIERS = {'match': False, 'laterals': False, 'joins': False, 'connect': False, 'pivots': 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}
class WithTableHint(Expression):
2402class WithTableHint(Expression):
2403    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2407class IndexTableHint(Expression):
2408    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2411class Table(Expression):
2412    arg_types = {
2413        "this": True,
2414        "alias": False,
2415        "db": False,
2416        "catalog": False,
2417        "laterals": False,
2418        "joins": False,
2419        "pivots": False,
2420        "hints": False,
2421        "system_time": False,
2422        "version": False,
2423    }
2424
2425    @property
2426    def name(self) -> str:
2427        if isinstance(self.this, Func):
2428            return ""
2429        return self.this.name
2430
2431    @property
2432    def db(self) -> str:
2433        return self.text("db")
2434
2435    @property
2436    def catalog(self) -> str:
2437        return self.text("catalog")
2438
2439    @property
2440    def selects(self) -> t.List[Expression]:
2441        return []
2442
2443    @property
2444    def named_selects(self) -> t.List[str]:
2445        return []
2446
2447    @property
2448    def parts(self) -> t.List[Identifier]:
2449        """Return the parts of a table in order catalog, db, table."""
2450        parts: t.List[Identifier] = []
2451
2452        for arg in ("catalog", "db", "this"):
2453            part = self.args.get(arg)
2454
2455            if isinstance(part, Identifier):
2456                parts.append(part)
2457            elif isinstance(part, Dot):
2458                parts.extend(part.flatten())
2459
2460        return parts
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False, 'version': False}
name: str
db: str
catalog: str
selects: List[Expression]
named_selects: List[str]
parts: List[Identifier]

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

key = 'table'
class Union(Subqueryable):
2463class Union(Subqueryable):
2464    arg_types = {
2465        "with": False,
2466        "this": True,
2467        "expression": True,
2468        "distinct": False,
2469        "by_name": False,
2470        **QUERY_MODIFIERS,
2471    }
2472
2473    def limit(
2474        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2475    ) -> Select:
2476        """
2477        Set the LIMIT expression.
2478
2479        Example:
2480            >>> select("1").union(select("1")).limit(1).sql()
2481            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2482
2483        Args:
2484            expression: the SQL code string to parse.
2485                This can also be an integer.
2486                If a `Limit` instance is passed, this is used as-is.
2487                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2488            dialect: the dialect used to parse the input expression.
2489            copy: if `False`, modify this expression instance in-place.
2490            opts: other options to use to parse the input expressions.
2491
2492        Returns:
2493            The limited subqueryable.
2494        """
2495        return (
2496            select("*")
2497            .from_(self.subquery(alias="_l_0", copy=copy))
2498            .limit(expression, dialect=dialect, copy=False, **opts)
2499        )
2500
2501    def select(
2502        self,
2503        *expressions: t.Optional[ExpOrStr],
2504        append: bool = True,
2505        dialect: DialectType = None,
2506        copy: bool = True,
2507        **opts,
2508    ) -> Union:
2509        """Append to or set the SELECT of the union recursively.
2510
2511        Example:
2512            >>> from sqlglot import parse_one
2513            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2514            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2515
2516        Args:
2517            *expressions: the SQL code strings to parse.
2518                If an `Expression` instance is passed, it will be used as-is.
2519            append: if `True`, add to any existing expressions.
2520                Otherwise, this resets the expressions.
2521            dialect: the dialect used to parse the input expressions.
2522            copy: if `False`, modify this expression instance in-place.
2523            opts: other options to use to parse the input expressions.
2524
2525        Returns:
2526            Union: the modified expression.
2527        """
2528        this = self.copy() if copy else self
2529        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2530        this.expression.unnest().select(
2531            *expressions, append=append, dialect=dialect, copy=False, **opts
2532        )
2533        return this
2534
2535    @property
2536    def named_selects(self) -> t.List[str]:
2537        return self.this.unnest().named_selects
2538
2539    @property
2540    def is_star(self) -> bool:
2541        return self.this.is_star or self.expression.is_star
2542
2543    @property
2544    def selects(self) -> t.List[Expression]:
2545        return self.this.unnest().selects
2546
2547    @property
2548    def left(self):
2549        return self.this
2550
2551    @property
2552    def right(self):
2553        return self.expression
arg_types = {'with': False, 'this': True, 'expression': True, 'distinct': False, 'by_name': False, 'match': False, 'laterals': False, 'joins': False, 'connect': False, 'pivots': 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}
def limit( self, expression: Union[str, Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2473    def limit(
2474        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2475    ) -> Select:
2476        """
2477        Set the LIMIT expression.
2478
2479        Example:
2480            >>> select("1").union(select("1")).limit(1).sql()
2481            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2482
2483        Args:
2484            expression: the SQL code string to parse.
2485                This can also be an integer.
2486                If a `Limit` instance is passed, this is used as-is.
2487                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2488            dialect: the dialect used to parse the input expression.
2489            copy: if `False`, modify this expression instance in-place.
2490            opts: other options to use to parse the input expressions.
2491
2492        Returns:
2493            The limited subqueryable.
2494        """
2495        return (
2496            select("*")
2497            .from_(self.subquery(alias="_l_0", copy=copy))
2498            .limit(expression, dialect=dialect, copy=False, **opts)
2499        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The limited subqueryable.

def select( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Union:
2501    def select(
2502        self,
2503        *expressions: t.Optional[ExpOrStr],
2504        append: bool = True,
2505        dialect: DialectType = None,
2506        copy: bool = True,
2507        **opts,
2508    ) -> Union:
2509        """Append to or set the SELECT of the union recursively.
2510
2511        Example:
2512            >>> from sqlglot import parse_one
2513            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2514            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2515
2516        Args:
2517            *expressions: the SQL code strings to parse.
2518                If an `Expression` instance is passed, it will be used as-is.
2519            append: if `True`, add to any existing expressions.
2520                Otherwise, this resets the expressions.
2521            dialect: the dialect used to parse the input expressions.
2522            copy: if `False`, modify this expression instance in-place.
2523            opts: other options to use to parse the input expressions.
2524
2525        Returns:
2526            Union: the modified expression.
2527        """
2528        this = self.copy() if copy else self
2529        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2530        this.expression.unnest().select(
2531            *expressions, append=append, dialect=dialect, copy=False, **opts
2532        )
2533        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

selects: List[Expression]
left
right
key = 'union'
class Except(Union):
2556class Except(Union):
2557    pass
key = 'except'
class Intersect(Union):
2560class Intersect(Union):
2561    pass
key = 'intersect'
class Unnest(UDTF):
2564class Unnest(UDTF):
2565    arg_types = {
2566        "expressions": True,
2567        "ordinality": False,
2568        "alias": False,
2569        "offset": False,
2570    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False, 'offset': False}
key = 'unnest'
class Update(Expression):
2573class Update(Expression):
2574    arg_types = {
2575        "with": False,
2576        "this": False,
2577        "expressions": True,
2578        "from": False,
2579        "where": False,
2580        "returning": False,
2581        "order": False,
2582        "limit": False,
2583    }
arg_types = {'with': False, 'this': False, 'expressions': True, 'from': False, 'where': False, 'returning': False, 'order': False, 'limit': False}
key = 'update'
class Values(UDTF):
2586class Values(UDTF):
2587    arg_types = {
2588        "expressions": True,
2589        "ordinality": False,
2590        "alias": False,
2591    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False}
key = 'values'
class Var(Expression):
2594class Var(Expression):
2595    pass
key = 'var'
class Version(Expression):
2598class Version(Expression):
2599    """
2600    Time travel, iceberg, bigquery etc
2601    https://trino.io/docs/current/connector/iceberg.html?highlight=snapshot#using-snapshots
2602    https://www.databricks.com/blog/2019/02/04/introducing-delta-time-travel-for-large-scale-data-lakes.html
2603    https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#for_system_time_as_of
2604    https://learn.microsoft.com/en-us/sql/relational-databases/tables/querying-data-in-a-system-versioned-temporal-table?view=sql-server-ver16
2605    this is either TIMESTAMP or VERSION
2606    kind is ("AS OF", "BETWEEN")
2607    """
2608
2609    arg_types = {"this": True, "kind": True, "expression": False}
arg_types = {'this': True, 'kind': True, 'expression': False}
key = 'version'
class Schema(Expression):
2612class Schema(Expression):
2613    arg_types = {"this": False, "expressions": False}
arg_types = {'this': False, 'expressions': False}
key = 'schema'
class Lock(Expression):
2618class Lock(Expression):
2619    arg_types = {"update": True, "expressions": False, "wait": False}
arg_types = {'update': True, 'expressions': False, 'wait': False}
key = 'lock'
class Select(Subqueryable):
2622class Select(Subqueryable):
2623    arg_types = {
2624        "with": False,
2625        "kind": False,
2626        "expressions": False,
2627        "hint": False,
2628        "distinct": False,
2629        "into": False,
2630        "from": False,
2631        **QUERY_MODIFIERS,
2632    }
2633
2634    def from_(
2635        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2636    ) -> Select:
2637        """
2638        Set the FROM expression.
2639
2640        Example:
2641            >>> Select().from_("tbl").select("x").sql()
2642            'SELECT x FROM tbl'
2643
2644        Args:
2645            expression : the SQL code strings to parse.
2646                If a `From` instance is passed, this is used as-is.
2647                If another `Expression` instance is passed, it will be wrapped in a `From`.
2648            dialect: the dialect used to parse the input expression.
2649            copy: if `False`, modify this expression instance in-place.
2650            opts: other options to use to parse the input expressions.
2651
2652        Returns:
2653            The modified Select expression.
2654        """
2655        return _apply_builder(
2656            expression=expression,
2657            instance=self,
2658            arg="from",
2659            into=From,
2660            prefix="FROM",
2661            dialect=dialect,
2662            copy=copy,
2663            **opts,
2664        )
2665
2666    def group_by(
2667        self,
2668        *expressions: t.Optional[ExpOrStr],
2669        append: bool = True,
2670        dialect: DialectType = None,
2671        copy: bool = True,
2672        **opts,
2673    ) -> Select:
2674        """
2675        Set the GROUP BY expression.
2676
2677        Example:
2678            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2679            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2680
2681        Args:
2682            *expressions: the SQL code strings to parse.
2683                If a `Group` instance is passed, this is used as-is.
2684                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2685                If nothing is passed in then a group by is not applied to the expression
2686            append: if `True`, add to any existing expressions.
2687                Otherwise, this flattens all the `Group` expression into a single expression.
2688            dialect: the dialect used to parse the input expression.
2689            copy: if `False`, modify this expression instance in-place.
2690            opts: other options to use to parse the input expressions.
2691
2692        Returns:
2693            The modified Select expression.
2694        """
2695        if not expressions:
2696            return self if not copy else self.copy()
2697
2698        return _apply_child_list_builder(
2699            *expressions,
2700            instance=self,
2701            arg="group",
2702            append=append,
2703            copy=copy,
2704            prefix="GROUP BY",
2705            into=Group,
2706            dialect=dialect,
2707            **opts,
2708        )
2709
2710    def order_by(
2711        self,
2712        *expressions: t.Optional[ExpOrStr],
2713        append: bool = True,
2714        dialect: DialectType = None,
2715        copy: bool = True,
2716        **opts,
2717    ) -> Select:
2718        """
2719        Set the ORDER BY expression.
2720
2721        Example:
2722            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2723            'SELECT x FROM tbl ORDER BY x DESC'
2724
2725        Args:
2726            *expressions: the SQL code strings to parse.
2727                If a `Group` instance is passed, this is used as-is.
2728                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2729            append: if `True`, add to any existing expressions.
2730                Otherwise, this flattens all the `Order` expression into a single expression.
2731            dialect: the dialect used to parse the input expression.
2732            copy: if `False`, modify this expression instance in-place.
2733            opts: other options to use to parse the input expressions.
2734
2735        Returns:
2736            The modified Select expression.
2737        """
2738        return _apply_child_list_builder(
2739            *expressions,
2740            instance=self,
2741            arg="order",
2742            append=append,
2743            copy=copy,
2744            prefix="ORDER BY",
2745            into=Order,
2746            dialect=dialect,
2747            **opts,
2748        )
2749
2750    def sort_by(
2751        self,
2752        *expressions: t.Optional[ExpOrStr],
2753        append: bool = True,
2754        dialect: DialectType = None,
2755        copy: bool = True,
2756        **opts,
2757    ) -> Select:
2758        """
2759        Set the SORT BY expression.
2760
2761        Example:
2762            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2763            'SELECT x FROM tbl SORT BY x DESC'
2764
2765        Args:
2766            *expressions: the SQL code strings to parse.
2767                If a `Group` instance is passed, this is used as-is.
2768                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2769            append: if `True`, add to any existing expressions.
2770                Otherwise, this flattens all the `Order` expression into a single expression.
2771            dialect: the dialect used to parse the input expression.
2772            copy: if `False`, modify this expression instance in-place.
2773            opts: other options to use to parse the input expressions.
2774
2775        Returns:
2776            The modified Select expression.
2777        """
2778        return _apply_child_list_builder(
2779            *expressions,
2780            instance=self,
2781            arg="sort",
2782            append=append,
2783            copy=copy,
2784            prefix="SORT BY",
2785            into=Sort,
2786            dialect=dialect,
2787            **opts,
2788        )
2789
2790    def cluster_by(
2791        self,
2792        *expressions: t.Optional[ExpOrStr],
2793        append: bool = True,
2794        dialect: DialectType = None,
2795        copy: bool = True,
2796        **opts,
2797    ) -> Select:
2798        """
2799        Set the CLUSTER BY expression.
2800
2801        Example:
2802            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2803            'SELECT x FROM tbl CLUSTER BY x DESC'
2804
2805        Args:
2806            *expressions: the SQL code strings to parse.
2807                If a `Group` instance is passed, this is used as-is.
2808                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2809            append: if `True`, add to any existing expressions.
2810                Otherwise, this flattens all the `Order` expression into a single expression.
2811            dialect: the dialect used to parse the input expression.
2812            copy: if `False`, modify this expression instance in-place.
2813            opts: other options to use to parse the input expressions.
2814
2815        Returns:
2816            The modified Select expression.
2817        """
2818        return _apply_child_list_builder(
2819            *expressions,
2820            instance=self,
2821            arg="cluster",
2822            append=append,
2823            copy=copy,
2824            prefix="CLUSTER BY",
2825            into=Cluster,
2826            dialect=dialect,
2827            **opts,
2828        )
2829
2830    def limit(
2831        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2832    ) -> Select:
2833        """
2834        Set the LIMIT expression.
2835
2836        Example:
2837            >>> Select().from_("tbl").select("x").limit(10).sql()
2838            'SELECT x FROM tbl LIMIT 10'
2839
2840        Args:
2841            expression: the SQL code string to parse.
2842                This can also be an integer.
2843                If a `Limit` instance is passed, this is used as-is.
2844                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2845            dialect: the dialect used to parse the input expression.
2846            copy: if `False`, modify this expression instance in-place.
2847            opts: other options to use to parse the input expressions.
2848
2849        Returns:
2850            Select: the modified expression.
2851        """
2852        return _apply_builder(
2853            expression=expression,
2854            instance=self,
2855            arg="limit",
2856            into=Limit,
2857            prefix="LIMIT",
2858            dialect=dialect,
2859            copy=copy,
2860            **opts,
2861        )
2862
2863    def offset(
2864        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2865    ) -> Select:
2866        """
2867        Set the OFFSET expression.
2868
2869        Example:
2870            >>> Select().from_("tbl").select("x").offset(10).sql()
2871            'SELECT x FROM tbl OFFSET 10'
2872
2873        Args:
2874            expression: the SQL code string to parse.
2875                This can also be an integer.
2876                If a `Offset` instance is passed, this is used as-is.
2877                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2878            dialect: the dialect used to parse the input expression.
2879            copy: if `False`, modify this expression instance in-place.
2880            opts: other options to use to parse the input expressions.
2881
2882        Returns:
2883            The modified Select expression.
2884        """
2885        return _apply_builder(
2886            expression=expression,
2887            instance=self,
2888            arg="offset",
2889            into=Offset,
2890            prefix="OFFSET",
2891            dialect=dialect,
2892            copy=copy,
2893            **opts,
2894        )
2895
2896    def select(
2897        self,
2898        *expressions: t.Optional[ExpOrStr],
2899        append: bool = True,
2900        dialect: DialectType = None,
2901        copy: bool = True,
2902        **opts,
2903    ) -> Select:
2904        """
2905        Append to or set the SELECT expressions.
2906
2907        Example:
2908            >>> Select().select("x", "y").sql()
2909            'SELECT x, y'
2910
2911        Args:
2912            *expressions: the SQL code strings to parse.
2913                If an `Expression` instance is passed, it will be used as-is.
2914            append: if `True`, add to any existing expressions.
2915                Otherwise, this resets the expressions.
2916            dialect: the dialect used to parse the input expressions.
2917            copy: if `False`, modify this expression instance in-place.
2918            opts: other options to use to parse the input expressions.
2919
2920        Returns:
2921            The modified Select expression.
2922        """
2923        return _apply_list_builder(
2924            *expressions,
2925            instance=self,
2926            arg="expressions",
2927            append=append,
2928            dialect=dialect,
2929            copy=copy,
2930            **opts,
2931        )
2932
2933    def lateral(
2934        self,
2935        *expressions: t.Optional[ExpOrStr],
2936        append: bool = True,
2937        dialect: DialectType = None,
2938        copy: bool = True,
2939        **opts,
2940    ) -> Select:
2941        """
2942        Append to or set the LATERAL expressions.
2943
2944        Example:
2945            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2946            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2947
2948        Args:
2949            *expressions: the SQL code strings to parse.
2950                If an `Expression` instance is passed, it will be used as-is.
2951            append: if `True`, add to any existing expressions.
2952                Otherwise, this resets the expressions.
2953            dialect: the dialect used to parse the input expressions.
2954            copy: if `False`, modify this expression instance in-place.
2955            opts: other options to use to parse the input expressions.
2956
2957        Returns:
2958            The modified Select expression.
2959        """
2960        return _apply_list_builder(
2961            *expressions,
2962            instance=self,
2963            arg="laterals",
2964            append=append,
2965            into=Lateral,
2966            prefix="LATERAL VIEW",
2967            dialect=dialect,
2968            copy=copy,
2969            **opts,
2970        )
2971
2972    def join(
2973        self,
2974        expression: ExpOrStr,
2975        on: t.Optional[ExpOrStr] = None,
2976        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
2977        append: bool = True,
2978        join_type: t.Optional[str] = None,
2979        join_alias: t.Optional[Identifier | str] = None,
2980        dialect: DialectType = None,
2981        copy: bool = True,
2982        **opts,
2983    ) -> Select:
2984        """
2985        Append to or set the JOIN expressions.
2986
2987        Example:
2988            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2989            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2990
2991            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2992            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2993
2994            Use `join_type` to change the type of join:
2995
2996            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2997            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2998
2999        Args:
3000            expression: the SQL code string to parse.
3001                If an `Expression` instance is passed, it will be used as-is.
3002            on: optionally specify the join "on" criteria as a SQL string.
3003                If an `Expression` instance is passed, it will be used as-is.
3004            using: optionally specify the join "using" criteria as a SQL string.
3005                If an `Expression` instance is passed, it will be used as-is.
3006            append: if `True`, add to any existing expressions.
3007                Otherwise, this resets the expressions.
3008            join_type: if set, alter the parsed join type.
3009            join_alias: an optional alias for the joined source.
3010            dialect: the dialect used to parse the input expressions.
3011            copy: if `False`, modify this expression instance in-place.
3012            opts: other options to use to parse the input expressions.
3013
3014        Returns:
3015            Select: the modified expression.
3016        """
3017        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
3018
3019        try:
3020            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
3021        except ParseError:
3022            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
3023
3024        join = expression if isinstance(expression, Join) else Join(this=expression)
3025
3026        if isinstance(join.this, Select):
3027            join.this.replace(join.this.subquery())
3028
3029        if join_type:
3030            method: t.Optional[Token]
3031            side: t.Optional[Token]
3032            kind: t.Optional[Token]
3033
3034            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
3035
3036            if method:
3037                join.set("method", method.text)
3038            if side:
3039                join.set("side", side.text)
3040            if kind:
3041                join.set("kind", kind.text)
3042
3043        if on:
3044            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
3045            join.set("on", on)
3046
3047        if using:
3048            join = _apply_list_builder(
3049                *ensure_list(using),
3050                instance=join,
3051                arg="using",
3052                append=append,
3053                copy=copy,
3054                into=Identifier,
3055                **opts,
3056            )
3057
3058        if join_alias:
3059            join.set("this", alias_(join.this, join_alias, table=True))
3060
3061        return _apply_list_builder(
3062            join,
3063            instance=self,
3064            arg="joins",
3065            append=append,
3066            copy=copy,
3067            **opts,
3068        )
3069
3070    def where(
3071        self,
3072        *expressions: t.Optional[ExpOrStr],
3073        append: bool = True,
3074        dialect: DialectType = None,
3075        copy: bool = True,
3076        **opts,
3077    ) -> Select:
3078        """
3079        Append to or set the WHERE expressions.
3080
3081        Example:
3082            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3083            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3084
3085        Args:
3086            *expressions: the SQL code strings to parse.
3087                If an `Expression` instance is passed, it will be used as-is.
3088                Multiple expressions are combined with an AND operator.
3089            append: if `True`, AND the new expressions to any existing expression.
3090                Otherwise, this resets the expression.
3091            dialect: the dialect used to parse the input expressions.
3092            copy: if `False`, modify this expression instance in-place.
3093            opts: other options to use to parse the input expressions.
3094
3095        Returns:
3096            Select: the modified expression.
3097        """
3098        return _apply_conjunction_builder(
3099            *expressions,
3100            instance=self,
3101            arg="where",
3102            append=append,
3103            into=Where,
3104            dialect=dialect,
3105            copy=copy,
3106            **opts,
3107        )
3108
3109    def having(
3110        self,
3111        *expressions: t.Optional[ExpOrStr],
3112        append: bool = True,
3113        dialect: DialectType = None,
3114        copy: bool = True,
3115        **opts,
3116    ) -> Select:
3117        """
3118        Append to or set the HAVING expressions.
3119
3120        Example:
3121            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3122            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3123
3124        Args:
3125            *expressions: the SQL code strings to parse.
3126                If an `Expression` instance is passed, it will be used as-is.
3127                Multiple expressions are combined with an AND operator.
3128            append: if `True`, AND the new expressions to any existing expression.
3129                Otherwise, this resets the expression.
3130            dialect: the dialect used to parse the input expressions.
3131            copy: if `False`, modify this expression instance in-place.
3132            opts: other options to use to parse the input expressions.
3133
3134        Returns:
3135            The modified Select expression.
3136        """
3137        return _apply_conjunction_builder(
3138            *expressions,
3139            instance=self,
3140            arg="having",
3141            append=append,
3142            into=Having,
3143            dialect=dialect,
3144            copy=copy,
3145            **opts,
3146        )
3147
3148    def window(
3149        self,
3150        *expressions: t.Optional[ExpOrStr],
3151        append: bool = True,
3152        dialect: DialectType = None,
3153        copy: bool = True,
3154        **opts,
3155    ) -> Select:
3156        return _apply_list_builder(
3157            *expressions,
3158            instance=self,
3159            arg="windows",
3160            append=append,
3161            into=Window,
3162            dialect=dialect,
3163            copy=copy,
3164            **opts,
3165        )
3166
3167    def qualify(
3168        self,
3169        *expressions: t.Optional[ExpOrStr],
3170        append: bool = True,
3171        dialect: DialectType = None,
3172        copy: bool = True,
3173        **opts,
3174    ) -> Select:
3175        return _apply_conjunction_builder(
3176            *expressions,
3177            instance=self,
3178            arg="qualify",
3179            append=append,
3180            into=Qualify,
3181            dialect=dialect,
3182            copy=copy,
3183            **opts,
3184        )
3185
3186    def distinct(
3187        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3188    ) -> Select:
3189        """
3190        Set the OFFSET expression.
3191
3192        Example:
3193            >>> Select().from_("tbl").select("x").distinct().sql()
3194            'SELECT DISTINCT x FROM tbl'
3195
3196        Args:
3197            ons: the expressions to distinct on
3198            distinct: whether the Select should be distinct
3199            copy: if `False`, modify this expression instance in-place.
3200
3201        Returns:
3202            Select: the modified expression.
3203        """
3204        instance = maybe_copy(self, copy)
3205        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3206        instance.set("distinct", Distinct(on=on) if distinct else None)
3207        return instance
3208
3209    def ctas(
3210        self,
3211        table: ExpOrStr,
3212        properties: t.Optional[t.Dict] = None,
3213        dialect: DialectType = None,
3214        copy: bool = True,
3215        **opts,
3216    ) -> Create:
3217        """
3218        Convert this expression to a CREATE TABLE AS statement.
3219
3220        Example:
3221            >>> Select().select("*").from_("tbl").ctas("x").sql()
3222            'CREATE TABLE x AS SELECT * FROM tbl'
3223
3224        Args:
3225            table: the SQL code string to parse as the table name.
3226                If another `Expression` instance is passed, it will be used as-is.
3227            properties: an optional mapping of table properties
3228            dialect: the dialect used to parse the input table.
3229            copy: if `False`, modify this expression instance in-place.
3230            opts: other options to use to parse the input table.
3231
3232        Returns:
3233            The new Create expression.
3234        """
3235        instance = maybe_copy(self, copy)
3236        table_expression = maybe_parse(
3237            table,
3238            into=Table,
3239            dialect=dialect,
3240            **opts,
3241        )
3242        properties_expression = None
3243        if properties:
3244            properties_expression = Properties.from_dict(properties)
3245
3246        return Create(
3247            this=table_expression,
3248            kind="table",
3249            expression=instance,
3250            properties=properties_expression,
3251        )
3252
3253    def lock(self, update: bool = True, copy: bool = True) -> Select:
3254        """
3255        Set the locking read mode for this expression.
3256
3257        Examples:
3258            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3259            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3260
3261            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3262            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3263
3264        Args:
3265            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3266            copy: if `False`, modify this expression instance in-place.
3267
3268        Returns:
3269            The modified expression.
3270        """
3271        inst = maybe_copy(self, copy)
3272        inst.set("locks", [Lock(update=update)])
3273
3274        return inst
3275
3276    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3277        """
3278        Set hints for this expression.
3279
3280        Examples:
3281            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3282            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3283
3284        Args:
3285            hints: The SQL code strings to parse as the hints.
3286                If an `Expression` instance is passed, it will be used as-is.
3287            dialect: The dialect used to parse the hints.
3288            copy: If `False`, modify this expression instance in-place.
3289
3290        Returns:
3291            The modified expression.
3292        """
3293        inst = maybe_copy(self, copy)
3294        inst.set(
3295            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3296        )
3297
3298        return inst
3299
3300    @property
3301    def named_selects(self) -> t.List[str]:
3302        return [e.output_name for e in self.expressions if e.alias_or_name]
3303
3304    @property
3305    def is_star(self) -> bool:
3306        return any(expression.is_star for expression in self.expressions)
3307
3308    @property
3309    def selects(self) -> t.List[Expression]:
3310        return self.expressions
arg_types = {'with': False, 'kind': False, 'expressions': False, 'hint': False, 'distinct': False, 'into': False, 'from': False, 'match': False, 'laterals': False, 'joins': False, 'connect': False, 'pivots': 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}
def from_( self, expression: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2634    def from_(
2635        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2636    ) -> Select:
2637        """
2638        Set the FROM expression.
2639
2640        Example:
2641            >>> Select().from_("tbl").select("x").sql()
2642            'SELECT x FROM tbl'
2643
2644        Args:
2645            expression : the SQL code strings to parse.
2646                If a `From` instance is passed, this is used as-is.
2647                If another `Expression` instance is passed, it will be wrapped in a `From`.
2648            dialect: the dialect used to parse the input expression.
2649            copy: if `False`, modify this expression instance in-place.
2650            opts: other options to use to parse the input expressions.
2651
2652        Returns:
2653            The modified Select expression.
2654        """
2655        return _apply_builder(
2656            expression=expression,
2657            instance=self,
2658            arg="from",
2659            into=From,
2660            prefix="FROM",
2661            dialect=dialect,
2662            copy=copy,
2663            **opts,
2664        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • expression : the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def group_by( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2666    def group_by(
2667        self,
2668        *expressions: t.Optional[ExpOrStr],
2669        append: bool = True,
2670        dialect: DialectType = None,
2671        copy: bool = True,
2672        **opts,
2673    ) -> Select:
2674        """
2675        Set the GROUP BY expression.
2676
2677        Example:
2678            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2679            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2680
2681        Args:
2682            *expressions: the SQL code strings to parse.
2683                If a `Group` instance is passed, this is used as-is.
2684                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2685                If nothing is passed in then a group by is not applied to the expression
2686            append: if `True`, add to any existing expressions.
2687                Otherwise, this flattens all the `Group` expression into a single expression.
2688            dialect: the dialect used to parse the input expression.
2689            copy: if `False`, modify this expression instance in-place.
2690            opts: other options to use to parse the input expressions.
2691
2692        Returns:
2693            The modified Select expression.
2694        """
2695        if not expressions:
2696            return self if not copy else self.copy()
2697
2698        return _apply_child_list_builder(
2699            *expressions,
2700            instance=self,
2701            arg="group",
2702            append=append,
2703            copy=copy,
2704            prefix="GROUP BY",
2705            into=Group,
2706            dialect=dialect,
2707            **opts,
2708        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def order_by( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2710    def order_by(
2711        self,
2712        *expressions: t.Optional[ExpOrStr],
2713        append: bool = True,
2714        dialect: DialectType = None,
2715        copy: bool = True,
2716        **opts,
2717    ) -> Select:
2718        """
2719        Set the ORDER BY expression.
2720
2721        Example:
2722            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2723            'SELECT x FROM tbl ORDER BY x DESC'
2724
2725        Args:
2726            *expressions: the SQL code strings to parse.
2727                If a `Group` instance is passed, this is used as-is.
2728                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2729            append: if `True`, add to any existing expressions.
2730                Otherwise, this flattens all the `Order` expression into a single expression.
2731            dialect: the dialect used to parse the input expression.
2732            copy: if `False`, modify this expression instance in-place.
2733            opts: other options to use to parse the input expressions.
2734
2735        Returns:
2736            The modified Select expression.
2737        """
2738        return _apply_child_list_builder(
2739            *expressions,
2740            instance=self,
2741            arg="order",
2742            append=append,
2743            copy=copy,
2744            prefix="ORDER BY",
2745            into=Order,
2746            dialect=dialect,
2747            **opts,
2748        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def sort_by( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2750    def sort_by(
2751        self,
2752        *expressions: t.Optional[ExpOrStr],
2753        append: bool = True,
2754        dialect: DialectType = None,
2755        copy: bool = True,
2756        **opts,
2757    ) -> Select:
2758        """
2759        Set the SORT BY expression.
2760
2761        Example:
2762            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2763            'SELECT x FROM tbl SORT BY x DESC'
2764
2765        Args:
2766            *expressions: the SQL code strings to parse.
2767                If a `Group` instance is passed, this is used as-is.
2768                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2769            append: if `True`, add to any existing expressions.
2770                Otherwise, this flattens all the `Order` expression into a single expression.
2771            dialect: the dialect used to parse the input expression.
2772            copy: if `False`, modify this expression instance in-place.
2773            opts: other options to use to parse the input expressions.
2774
2775        Returns:
2776            The modified Select expression.
2777        """
2778        return _apply_child_list_builder(
2779            *expressions,
2780            instance=self,
2781            arg="sort",
2782            append=append,
2783            copy=copy,
2784            prefix="SORT BY",
2785            into=Sort,
2786            dialect=dialect,
2787            **opts,
2788        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def cluster_by( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2790    def cluster_by(
2791        self,
2792        *expressions: t.Optional[ExpOrStr],
2793        append: bool = True,
2794        dialect: DialectType = None,
2795        copy: bool = True,
2796        **opts,
2797    ) -> Select:
2798        """
2799        Set the CLUSTER BY expression.
2800
2801        Example:
2802            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2803            'SELECT x FROM tbl CLUSTER BY x DESC'
2804
2805        Args:
2806            *expressions: the SQL code strings to parse.
2807                If a `Group` instance is passed, this is used as-is.
2808                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2809            append: if `True`, add to any existing expressions.
2810                Otherwise, this flattens all the `Order` expression into a single expression.
2811            dialect: the dialect used to parse the input expression.
2812            copy: if `False`, modify this expression instance in-place.
2813            opts: other options to use to parse the input expressions.
2814
2815        Returns:
2816            The modified Select expression.
2817        """
2818        return _apply_child_list_builder(
2819            *expressions,
2820            instance=self,
2821            arg="cluster",
2822            append=append,
2823            copy=copy,
2824            prefix="CLUSTER BY",
2825            into=Cluster,
2826            dialect=dialect,
2827            **opts,
2828        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def limit( self, expression: Union[str, Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2830    def limit(
2831        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2832    ) -> Select:
2833        """
2834        Set the LIMIT expression.
2835
2836        Example:
2837            >>> Select().from_("tbl").select("x").limit(10).sql()
2838            'SELECT x FROM tbl LIMIT 10'
2839
2840        Args:
2841            expression: the SQL code string to parse.
2842                This can also be an integer.
2843                If a `Limit` instance is passed, this is used as-is.
2844                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2845            dialect: the dialect used to parse the input expression.
2846            copy: if `False`, modify this expression instance in-place.
2847            opts: other options to use to parse the input expressions.
2848
2849        Returns:
2850            Select: the modified expression.
2851        """
2852        return _apply_builder(
2853            expression=expression,
2854            instance=self,
2855            arg="limit",
2856            into=Limit,
2857            prefix="LIMIT",
2858            dialect=dialect,
2859            copy=copy,
2860            **opts,
2861        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression: Union[str, Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2863    def offset(
2864        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2865    ) -> Select:
2866        """
2867        Set the OFFSET expression.
2868
2869        Example:
2870            >>> Select().from_("tbl").select("x").offset(10).sql()
2871            'SELECT x FROM tbl OFFSET 10'
2872
2873        Args:
2874            expression: the SQL code string to parse.
2875                This can also be an integer.
2876                If a `Offset` instance is passed, this is used as-is.
2877                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2878            dialect: the dialect used to parse the input expression.
2879            copy: if `False`, modify this expression instance in-place.
2880            opts: other options to use to parse the input expressions.
2881
2882        Returns:
2883            The modified Select expression.
2884        """
2885        return _apply_builder(
2886            expression=expression,
2887            instance=self,
2888            arg="offset",
2889            into=Offset,
2890            prefix="OFFSET",
2891            dialect=dialect,
2892            copy=copy,
2893            **opts,
2894        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def select( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2896    def select(
2897        self,
2898        *expressions: t.Optional[ExpOrStr],
2899        append: bool = True,
2900        dialect: DialectType = None,
2901        copy: bool = True,
2902        **opts,
2903    ) -> Select:
2904        """
2905        Append to or set the SELECT expressions.
2906
2907        Example:
2908            >>> Select().select("x", "y").sql()
2909            'SELECT x, y'
2910
2911        Args:
2912            *expressions: the SQL code strings to parse.
2913                If an `Expression` instance is passed, it will be used as-is.
2914            append: if `True`, add to any existing expressions.
2915                Otherwise, this resets the expressions.
2916            dialect: the dialect used to parse the input expressions.
2917            copy: if `False`, modify this expression instance in-place.
2918            opts: other options to use to parse the input expressions.
2919
2920        Returns:
2921            The modified Select expression.
2922        """
2923        return _apply_list_builder(
2924            *expressions,
2925            instance=self,
2926            arg="expressions",
2927            append=append,
2928            dialect=dialect,
2929            copy=copy,
2930            **opts,
2931        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def lateral( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2933    def lateral(
2934        self,
2935        *expressions: t.Optional[ExpOrStr],
2936        append: bool = True,
2937        dialect: DialectType = None,
2938        copy: bool = True,
2939        **opts,
2940    ) -> Select:
2941        """
2942        Append to or set the LATERAL expressions.
2943
2944        Example:
2945            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2946            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2947
2948        Args:
2949            *expressions: the SQL code strings to parse.
2950                If an `Expression` instance is passed, it will be used as-is.
2951            append: if `True`, add to any existing expressions.
2952                Otherwise, this resets the expressions.
2953            dialect: the dialect used to parse the input expressions.
2954            copy: if `False`, modify this expression instance in-place.
2955            opts: other options to use to parse the input expressions.
2956
2957        Returns:
2958            The modified Select expression.
2959        """
2960        return _apply_list_builder(
2961            *expressions,
2962            instance=self,
2963            arg="laterals",
2964            append=append,
2965            into=Lateral,
2966            prefix="LATERAL VIEW",
2967            dialect=dialect,
2968            copy=copy,
2969            **opts,
2970        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def join( self, expression: Union[str, Expression], on: Union[str, Expression, NoneType] = None, using: Union[str, Expression, Collection[Union[str, Expression]], NoneType] = None, append: bool = True, join_type: Optional[str] = None, join_alias: Union[Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2972    def join(
2973        self,
2974        expression: ExpOrStr,
2975        on: t.Optional[ExpOrStr] = None,
2976        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
2977        append: bool = True,
2978        join_type: t.Optional[str] = None,
2979        join_alias: t.Optional[Identifier | str] = None,
2980        dialect: DialectType = None,
2981        copy: bool = True,
2982        **opts,
2983    ) -> Select:
2984        """
2985        Append to or set the JOIN expressions.
2986
2987        Example:
2988            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2989            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2990
2991            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2992            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2993
2994            Use `join_type` to change the type of join:
2995
2996            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2997            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2998
2999        Args:
3000            expression: the SQL code string to parse.
3001                If an `Expression` instance is passed, it will be used as-is.
3002            on: optionally specify the join "on" criteria as a SQL string.
3003                If an `Expression` instance is passed, it will be used as-is.
3004            using: optionally specify the join "using" criteria as a SQL string.
3005                If an `Expression` instance is passed, it will be used as-is.
3006            append: if `True`, add to any existing expressions.
3007                Otherwise, this resets the expressions.
3008            join_type: if set, alter the parsed join type.
3009            join_alias: an optional alias for the joined source.
3010            dialect: the dialect used to parse the input expressions.
3011            copy: if `False`, modify this expression instance in-place.
3012            opts: other options to use to parse the input expressions.
3013
3014        Returns:
3015            Select: the modified expression.
3016        """
3017        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
3018
3019        try:
3020            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
3021        except ParseError:
3022            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
3023
3024        join = expression if isinstance(expression, Join) else Join(this=expression)
3025
3026        if isinstance(join.this, Select):
3027            join.this.replace(join.this.subquery())
3028
3029        if join_type:
3030            method: t.Optional[Token]
3031            side: t.Optional[Token]
3032            kind: t.Optional[Token]
3033
3034            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
3035
3036            if method:
3037                join.set("method", method.text)
3038            if side:
3039                join.set("side", side.text)
3040            if kind:
3041                join.set("kind", kind.text)
3042
3043        if on:
3044            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
3045            join.set("on", on)
3046
3047        if using:
3048            join = _apply_list_builder(
3049                *ensure_list(using),
3050                instance=join,
3051                arg="using",
3052                append=append,
3053                copy=copy,
3054                into=Identifier,
3055                **opts,
3056            )
3057
3058        if join_alias:
3059            join.set("this", alias_(join.this, join_alias, table=True))
3060
3061        return _apply_list_builder(
3062            join,
3063            instance=self,
3064            arg="joins",
3065            append=append,
3066            copy=copy,
3067            **opts,
3068        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on: optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using: optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type: if set, alter the parsed join type.
  • join_alias: an optional alias for the joined source.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3070    def where(
3071        self,
3072        *expressions: t.Optional[ExpOrStr],
3073        append: bool = True,
3074        dialect: DialectType = None,
3075        copy: bool = True,
3076        **opts,
3077    ) -> Select:
3078        """
3079        Append to or set the WHERE expressions.
3080
3081        Example:
3082            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3083            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3084
3085        Args:
3086            *expressions: the SQL code strings to parse.
3087                If an `Expression` instance is passed, it will be used as-is.
3088                Multiple expressions are combined with an AND operator.
3089            append: if `True`, AND the new expressions to any existing expression.
3090                Otherwise, this resets the expression.
3091            dialect: the dialect used to parse the input expressions.
3092            copy: if `False`, modify this expression instance in-place.
3093            opts: other options to use to parse the input expressions.
3094
3095        Returns:
3096            Select: the modified expression.
3097        """
3098        return _apply_conjunction_builder(
3099            *expressions,
3100            instance=self,
3101            arg="where",
3102            append=append,
3103            into=Where,
3104            dialect=dialect,
3105            copy=copy,
3106            **opts,
3107        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3109    def having(
3110        self,
3111        *expressions: t.Optional[ExpOrStr],
3112        append: bool = True,
3113        dialect: DialectType = None,
3114        copy: bool = True,
3115        **opts,
3116    ) -> Select:
3117        """
3118        Append to or set the HAVING expressions.
3119
3120        Example:
3121            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3122            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3123
3124        Args:
3125            *expressions: the SQL code strings to parse.
3126                If an `Expression` instance is passed, it will be used as-is.
3127                Multiple expressions are combined with an AND operator.
3128            append: if `True`, AND the new expressions to any existing expression.
3129                Otherwise, this resets the expression.
3130            dialect: the dialect used to parse the input expressions.
3131            copy: if `False`, modify this expression instance in-place.
3132            opts: other options to use to parse the input expressions.
3133
3134        Returns:
3135            The modified Select expression.
3136        """
3137        return _apply_conjunction_builder(
3138            *expressions,
3139            instance=self,
3140            arg="having",
3141            append=append,
3142            into=Having,
3143            dialect=dialect,
3144            copy=copy,
3145            **opts,
3146        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def window( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3148    def window(
3149        self,
3150        *expressions: t.Optional[ExpOrStr],
3151        append: bool = True,
3152        dialect: DialectType = None,
3153        copy: bool = True,
3154        **opts,
3155    ) -> Select:
3156        return _apply_list_builder(
3157            *expressions,
3158            instance=self,
3159            arg="windows",
3160            append=append,
3161            into=Window,
3162            dialect=dialect,
3163            copy=copy,
3164            **opts,
3165        )
def qualify( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3167    def qualify(
3168        self,
3169        *expressions: t.Optional[ExpOrStr],
3170        append: bool = True,
3171        dialect: DialectType = None,
3172        copy: bool = True,
3173        **opts,
3174    ) -> Select:
3175        return _apply_conjunction_builder(
3176            *expressions,
3177            instance=self,
3178            arg="qualify",
3179            append=append,
3180            into=Qualify,
3181            dialect=dialect,
3182            copy=copy,
3183            **opts,
3184        )
def distinct( self, *ons: Union[str, Expression, NoneType], distinct: bool = True, copy: bool = True) -> Select:
3186    def distinct(
3187        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3188    ) -> Select:
3189        """
3190        Set the OFFSET expression.
3191
3192        Example:
3193            >>> Select().from_("tbl").select("x").distinct().sql()
3194            'SELECT DISTINCT x FROM tbl'
3195
3196        Args:
3197            ons: the expressions to distinct on
3198            distinct: whether the Select should be distinct
3199            copy: if `False`, modify this expression instance in-place.
3200
3201        Returns:
3202            Select: the modified expression.
3203        """
3204        instance = maybe_copy(self, copy)
3205        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3206        instance.set("distinct", Distinct(on=on) if distinct else None)
3207        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • ons: the expressions to distinct on
  • distinct: whether the Select should be distinct
  • copy: if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table: Union[str, Expression], properties: Optional[Dict] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Create:
3209    def ctas(
3210        self,
3211        table: ExpOrStr,
3212        properties: t.Optional[t.Dict] = None,
3213        dialect: DialectType = None,
3214        copy: bool = True,
3215        **opts,
3216    ) -> Create:
3217        """
3218        Convert this expression to a CREATE TABLE AS statement.
3219
3220        Example:
3221            >>> Select().select("*").from_("tbl").ctas("x").sql()
3222            'CREATE TABLE x AS SELECT * FROM tbl'
3223
3224        Args:
3225            table: the SQL code string to parse as the table name.
3226                If another `Expression` instance is passed, it will be used as-is.
3227            properties: an optional mapping of table properties
3228            dialect: the dialect used to parse the input table.
3229            copy: if `False`, modify this expression instance in-place.
3230            opts: other options to use to parse the input table.
3231
3232        Returns:
3233            The new Create expression.
3234        """
3235        instance = maybe_copy(self, copy)
3236        table_expression = maybe_parse(
3237            table,
3238            into=Table,
3239            dialect=dialect,
3240            **opts,
3241        )
3242        properties_expression = None
3243        if properties:
3244            properties_expression = Properties.from_dict(properties)
3245
3246        return Create(
3247            this=table_expression,
3248            kind="table",
3249            expression=instance,
3250            properties=properties_expression,
3251        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table: the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties: an optional mapping of table properties
  • dialect: the dialect used to parse the input table.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input table.
Returns:

The new Create expression.

def lock( self, update: bool = True, copy: bool = True) -> Select:
3253    def lock(self, update: bool = True, copy: bool = True) -> Select:
3254        """
3255        Set the locking read mode for this expression.
3256
3257        Examples:
3258            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3259            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3260
3261            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3262            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3263
3264        Args:
3265            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3266            copy: if `False`, modify this expression instance in-place.
3267
3268        Returns:
3269            The modified expression.
3270        """
3271        inst = maybe_copy(self, copy)
3272        inst.set("locks", [Lock(update=update)])
3273
3274        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

def hint( self, *hints: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True) -> Select:
3276    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3277        """
3278        Set hints for this expression.
3279
3280        Examples:
3281            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3282            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3283
3284        Args:
3285            hints: The SQL code strings to parse as the hints.
3286                If an `Expression` instance is passed, it will be used as-is.
3287            dialect: The dialect used to parse the hints.
3288            copy: If `False`, modify this expression instance in-place.
3289
3290        Returns:
3291            The modified expression.
3292        """
3293        inst = maybe_copy(self, copy)
3294        inst.set(
3295            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3296        )
3297
3298        return inst

Set hints for this expression.

Examples:
>>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
'SELECT /*+ BROADCAST(y) */ x FROM tbl'
Arguments:
  • hints: The SQL code strings to parse as the hints. If an Expression instance is passed, it will be used as-is.
  • dialect: The dialect used to parse the hints.
  • copy: If False, modify this expression instance in-place.
Returns:

The modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

selects: List[Expression]
key = 'select'
class Subquery(DerivedTable, Unionable):
3313class Subquery(DerivedTable, Unionable):
3314    arg_types = {
3315        "this": True,
3316        "alias": False,
3317        "with": False,
3318        **QUERY_MODIFIERS,
3319    }
3320
3321    def unnest(self):
3322        """
3323        Returns the first non subquery.
3324        """
3325        expression = self
3326        while isinstance(expression, Subquery):
3327            expression = expression.this
3328        return expression
3329
3330    def unwrap(self) -> Subquery:
3331        expression = self
3332        while expression.same_parent and expression.is_wrapper:
3333            expression = t.cast(Subquery, expression.parent)
3334        return expression
3335
3336    @property
3337    def is_wrapper(self) -> bool:
3338        """
3339        Whether this Subquery acts as a simple wrapper around another expression.
3340
3341        SELECT * FROM (((SELECT * FROM t)))
3342                      ^
3343                      This corresponds to a "wrapper" Subquery node
3344        """
3345        return all(v is None for k, v in self.args.items() if k != "this")
3346
3347    @property
3348    def is_star(self) -> bool:
3349        return self.this.is_star
3350
3351    @property
3352    def output_name(self) -> str:
3353        return self.alias
arg_types = {'this': True, 'alias': False, 'with': False, 'match': False, 'laterals': False, 'joins': False, 'connect': False, 'pivots': 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}
def unnest(self):
3321    def unnest(self):
3322        """
3323        Returns the first non subquery.
3324        """
3325        expression = self
3326        while isinstance(expression, Subquery):
3327            expression = expression.this
3328        return expression

Returns the first non subquery.

def unwrap(self) -> Subquery:
3330    def unwrap(self) -> Subquery:
3331        expression = self
3332        while expression.same_parent and expression.is_wrapper:
3333            expression = t.cast(Subquery, expression.parent)
3334        return expression
is_wrapper: bool

Whether this Subquery acts as a simple wrapper around another expression.

SELECT * FROM (((SELECT * FROM t))) ^ This corresponds to a "wrapper" Subquery node

is_star: bool

Checks whether an expression is a star.

output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'subquery'
class TableSample(Expression):
3356class TableSample(Expression):
3357    arg_types = {
3358        "this": False,
3359        "expressions": False,
3360        "method": False,
3361        "bucket_numerator": False,
3362        "bucket_denominator": False,
3363        "bucket_field": False,
3364        "percent": False,
3365        "rows": False,
3366        "size": False,
3367        "seed": False,
3368        "kind": False,
3369    }
arg_types = {'this': False, 'expressions': False, 'method': False, 'bucket_numerator': False, 'bucket_denominator': False, 'bucket_field': False, 'percent': False, 'rows': False, 'size': False, 'seed': False, 'kind': False}
key = 'tablesample'
class Tag(Expression):
3372class Tag(Expression):
3373    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3374
3375    arg_types = {
3376        "this": False,
3377        "prefix": False,
3378        "postfix": False,
3379    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3384class Pivot(Expression):
3385    arg_types = {
3386        "this": False,
3387        "alias": False,
3388        "expressions": True,
3389        "field": False,
3390        "unpivot": False,
3391        "using": False,
3392        "group": False,
3393        "columns": False,
3394        "include_nulls": False,
3395    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False, 'include_nulls': False}
key = 'pivot'
class Window(Condition):
3398class Window(Condition):
3399    arg_types = {
3400        "this": True,
3401        "partition_by": False,
3402        "order": False,
3403        "spec": False,
3404        "alias": False,
3405        "over": False,
3406        "first": False,
3407    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3410class WindowSpec(Expression):
3411    arg_types = {
3412        "kind": False,
3413        "start": False,
3414        "start_side": False,
3415        "end": False,
3416        "end_side": False,
3417    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3420class Where(Expression):
3421    pass
key = 'where'
class Star(Expression):
3424class Star(Expression):
3425    arg_types = {"except": False, "replace": False}
3426
3427    @property
3428    def name(self) -> str:
3429        return "*"
3430
3431    @property
3432    def output_name(self) -> str:
3433        return self.name
arg_types = {'except': False, 'replace': False}
name: str
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'star'
class Parameter(Condition):
3436class Parameter(Condition):
3437    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3440class SessionParameter(Condition):
3441    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3444class Placeholder(Condition):
3445    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3448class Null(Condition):
3449    arg_types: t.Dict[str, t.Any] = {}
3450
3451    @property
3452    def name(self) -> str:
3453        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3456class Boolean(Condition):
3457    pass
key = 'boolean'
class DataTypeParam(Expression):
3460class DataTypeParam(Expression):
3461    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypeparam'
class DataType(Expression):
3464class DataType(Expression):
3465    arg_types = {
3466        "this": True,
3467        "expressions": False,
3468        "nested": False,
3469        "values": False,
3470        "prefix": False,
3471        "kind": False,
3472    }
3473
3474    class Type(AutoName):
3475        ARRAY = auto()
3476        BIGDECIMAL = auto()
3477        BIGINT = auto()
3478        BIGSERIAL = auto()
3479        BINARY = auto()
3480        BIT = auto()
3481        BOOLEAN = auto()
3482        CHAR = auto()
3483        DATE = auto()
3484        DATEMULTIRANGE = auto()
3485        DATERANGE = auto()
3486        DATETIME = auto()
3487        DATETIME64 = auto()
3488        DECIMAL = auto()
3489        DOUBLE = auto()
3490        ENUM = auto()
3491        ENUM8 = auto()
3492        ENUM16 = auto()
3493        FIXEDSTRING = auto()
3494        FLOAT = auto()
3495        GEOGRAPHY = auto()
3496        GEOMETRY = auto()
3497        HLLSKETCH = auto()
3498        HSTORE = auto()
3499        IMAGE = auto()
3500        INET = auto()
3501        INT = auto()
3502        INT128 = auto()
3503        INT256 = auto()
3504        INT4MULTIRANGE = auto()
3505        INT4RANGE = auto()
3506        INT8MULTIRANGE = auto()
3507        INT8RANGE = auto()
3508        INTERVAL = auto()
3509        IPADDRESS = auto()
3510        IPPREFIX = auto()
3511        JSON = auto()
3512        JSONB = auto()
3513        LONGBLOB = auto()
3514        LONGTEXT = auto()
3515        LOWCARDINALITY = auto()
3516        MAP = auto()
3517        MEDIUMBLOB = auto()
3518        MEDIUMINT = auto()
3519        MEDIUMTEXT = auto()
3520        MONEY = auto()
3521        NCHAR = auto()
3522        NESTED = auto()
3523        NULL = auto()
3524        NULLABLE = auto()
3525        NUMMULTIRANGE = auto()
3526        NUMRANGE = auto()
3527        NVARCHAR = auto()
3528        OBJECT = auto()
3529        ROWVERSION = auto()
3530        SERIAL = auto()
3531        SET = auto()
3532        SMALLINT = auto()
3533        SMALLMONEY = auto()
3534        SMALLSERIAL = auto()
3535        STRUCT = auto()
3536        SUPER = auto()
3537        TEXT = auto()
3538        TINYBLOB = auto()
3539        TINYTEXT = auto()
3540        TIME = auto()
3541        TIMETZ = auto()
3542        TIMESTAMP = auto()
3543        TIMESTAMPLTZ = auto()
3544        TIMESTAMPTZ = auto()
3545        TINYINT = auto()
3546        TSMULTIRANGE = auto()
3547        TSRANGE = auto()
3548        TSTZMULTIRANGE = auto()
3549        TSTZRANGE = auto()
3550        UBIGINT = auto()
3551        UINT = auto()
3552        UINT128 = auto()
3553        UINT256 = auto()
3554        UMEDIUMINT = auto()
3555        UNIQUEIDENTIFIER = auto()
3556        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3557        USERDEFINED = "USER-DEFINED"
3558        USMALLINT = auto()
3559        UTINYINT = auto()
3560        UUID = auto()
3561        VARBINARY = auto()
3562        VARCHAR = auto()
3563        VARIANT = auto()
3564        XML = auto()
3565        YEAR = auto()
3566
3567    TEXT_TYPES = {
3568        Type.CHAR,
3569        Type.NCHAR,
3570        Type.VARCHAR,
3571        Type.NVARCHAR,
3572        Type.TEXT,
3573    }
3574
3575    INTEGER_TYPES = {
3576        Type.INT,
3577        Type.TINYINT,
3578        Type.SMALLINT,
3579        Type.BIGINT,
3580        Type.INT128,
3581        Type.INT256,
3582    }
3583
3584    FLOAT_TYPES = {
3585        Type.FLOAT,
3586        Type.DOUBLE,
3587    }
3588
3589    NUMERIC_TYPES = {
3590        *INTEGER_TYPES,
3591        *FLOAT_TYPES,
3592    }
3593
3594    TEMPORAL_TYPES = {
3595        Type.TIME,
3596        Type.TIMETZ,
3597        Type.TIMESTAMP,
3598        Type.TIMESTAMPTZ,
3599        Type.TIMESTAMPLTZ,
3600        Type.DATE,
3601        Type.DATETIME,
3602        Type.DATETIME64,
3603    }
3604
3605    @classmethod
3606    def build(
3607        cls,
3608        dtype: str | DataType | DataType.Type,
3609        dialect: DialectType = None,
3610        udt: bool = False,
3611        **kwargs,
3612    ) -> DataType:
3613        """
3614        Constructs a DataType object.
3615
3616        Args:
3617            dtype: the data type of interest.
3618            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3619            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3620                DataType, thus creating a user-defined type.
3621            kawrgs: additional arguments to pass in the constructor of DataType.
3622
3623        Returns:
3624            The constructed DataType object.
3625        """
3626        from sqlglot import parse_one
3627
3628        if isinstance(dtype, str):
3629            if dtype.upper() == "UNKNOWN":
3630                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3631
3632            try:
3633                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3634            except ParseError:
3635                if udt:
3636                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3637                raise
3638        elif isinstance(dtype, DataType.Type):
3639            data_type_exp = DataType(this=dtype)
3640        elif isinstance(dtype, DataType):
3641            return dtype
3642        else:
3643            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3644
3645        return DataType(**{**data_type_exp.args, **kwargs})
3646
3647    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3648        """
3649        Checks whether this DataType matches one of the provided data types. Nested types or precision
3650        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3651
3652        Args:
3653            dtypes: the data types to compare this DataType to.
3654
3655        Returns:
3656            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3657        """
3658        for dtype in dtypes:
3659            other = DataType.build(dtype, udt=True)
3660
3661            if (
3662                other.expressions
3663                or self.this == DataType.Type.USERDEFINED
3664                or other.this == DataType.Type.USERDEFINED
3665            ):
3666                matches = self == other
3667            else:
3668                matches = self.this == other.this
3669
3670            if matches:
3671                return True
3672        return False
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False, 'kind': False}
TEXT_TYPES = {<Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.TEXT: 'TEXT'>}
INTEGER_TYPES = {<Type.INT256: 'INT256'>, <Type.BIGINT: 'BIGINT'>, <Type.INT: 'INT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT128: 'INT128'>, <Type.SMALLINT: 'SMALLINT'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.INT: 'INT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT256: 'INT256'>, <Type.INT128: 'INT128'>, <Type.BIGINT: 'BIGINT'>, <Type.SMALLINT: 'SMALLINT'>}
TEMPORAL_TYPES = {<Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.DATETIME: 'DATETIME'>, <Type.DATETIME64: 'DATETIME64'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIME: 'TIME'>, <Type.TIMETZ: 'TIMETZ'>, <Type.DATE: 'DATE'>}
@classmethod
def build( cls, dtype: str | DataType | DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, udt: bool = False, **kwargs) -> DataType:
3605    @classmethod
3606    def build(
3607        cls,
3608        dtype: str | DataType | DataType.Type,
3609        dialect: DialectType = None,
3610        udt: bool = False,
3611        **kwargs,
3612    ) -> DataType:
3613        """
3614        Constructs a DataType object.
3615
3616        Args:
3617            dtype: the data type of interest.
3618            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3619            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3620                DataType, thus creating a user-defined type.
3621            kawrgs: additional arguments to pass in the constructor of DataType.
3622
3623        Returns:
3624            The constructed DataType object.
3625        """
3626        from sqlglot import parse_one
3627
3628        if isinstance(dtype, str):
3629            if dtype.upper() == "UNKNOWN":
3630                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3631
3632            try:
3633                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3634            except ParseError:
3635                if udt:
3636                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3637                raise
3638        elif isinstance(dtype, DataType.Type):
3639            data_type_exp = DataType(this=dtype)
3640        elif isinstance(dtype, DataType):
3641            return dtype
3642        else:
3643            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3644
3645        return DataType(**{**data_type_exp.args, **kwargs})

Constructs a DataType object.

Arguments:
  • dtype: the data type of interest.
  • dialect: the dialect to use for parsing dtype, in case it's a string.
  • udt: when set to True, dtype will be used as-is if it can't be parsed into a DataType, thus creating a user-defined type.
  • kawrgs: additional arguments to pass in the constructor of DataType.
Returns:

The constructed DataType object.

def is_type( self, *dtypes: str | DataType | DataType.Type) -> bool:
3647    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3648        """
3649        Checks whether this DataType matches one of the provided data types. Nested types or precision
3650        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3651
3652        Args:
3653            dtypes: the data types to compare this DataType to.
3654
3655        Returns:
3656            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3657        """
3658        for dtype in dtypes:
3659            other = DataType.build(dtype, udt=True)
3660
3661            if (
3662                other.expressions
3663                or self.this == DataType.Type.USERDEFINED
3664                or other.this == DataType.Type.USERDEFINED
3665            ):
3666                matches = self == other
3667            else:
3668                matches = self.this == other.this
3669
3670            if matches:
3671                return True
3672        return False

Checks whether this DataType matches one of the provided data types. Nested types or precision will be compared using "structural equivalence" semantics, so e.g. array != array.

Arguments:
  • dtypes: the data types to compare this DataType to.
Returns:

True, if and only if there is a type in dtypes which is equal to this DataType.

key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3474    class Type(AutoName):
3475        ARRAY = auto()
3476        BIGDECIMAL = auto()
3477        BIGINT = auto()
3478        BIGSERIAL = auto()
3479        BINARY = auto()
3480        BIT = auto()
3481        BOOLEAN = auto()
3482        CHAR = auto()
3483        DATE = auto()
3484        DATEMULTIRANGE = auto()
3485        DATERANGE = auto()
3486        DATETIME = auto()
3487        DATETIME64 = auto()
3488        DECIMAL = auto()
3489        DOUBLE = auto()
3490        ENUM = auto()
3491        ENUM8 = auto()
3492        ENUM16 = auto()
3493        FIXEDSTRING = auto()
3494        FLOAT = auto()
3495        GEOGRAPHY = auto()
3496        GEOMETRY = auto()
3497        HLLSKETCH = auto()
3498        HSTORE = auto()
3499        IMAGE = auto()
3500        INET = auto()
3501        INT = auto()
3502        INT128 = auto()
3503        INT256 = auto()
3504        INT4MULTIRANGE = auto()
3505        INT4RANGE = auto()
3506        INT8MULTIRANGE = auto()
3507        INT8RANGE = auto()
3508        INTERVAL = auto()
3509        IPADDRESS = auto()
3510        IPPREFIX = auto()
3511        JSON = auto()
3512        JSONB = auto()
3513        LONGBLOB = auto()
3514        LONGTEXT = auto()
3515        LOWCARDINALITY = auto()
3516        MAP = auto()
3517        MEDIUMBLOB = auto()
3518        MEDIUMINT = auto()
3519        MEDIUMTEXT = auto()
3520        MONEY = auto()
3521        NCHAR = auto()
3522        NESTED = auto()
3523        NULL = auto()
3524        NULLABLE = auto()
3525        NUMMULTIRANGE = auto()
3526        NUMRANGE = auto()
3527        NVARCHAR = auto()
3528        OBJECT = auto()
3529        ROWVERSION = auto()
3530        SERIAL = auto()
3531        SET = auto()
3532        SMALLINT = auto()
3533        SMALLMONEY = auto()
3534        SMALLSERIAL = auto()
3535        STRUCT = auto()
3536        SUPER = auto()
3537        TEXT = auto()
3538        TINYBLOB = auto()
3539        TINYTEXT = auto()
3540        TIME = auto()
3541        TIMETZ = auto()
3542        TIMESTAMP = auto()
3543        TIMESTAMPLTZ = auto()
3544        TIMESTAMPTZ = auto()
3545        TINYINT = auto()
3546        TSMULTIRANGE = auto()
3547        TSRANGE = auto()
3548        TSTZMULTIRANGE = auto()
3549        TSTZRANGE = auto()
3550        UBIGINT = auto()
3551        UINT = auto()
3552        UINT128 = auto()
3553        UINT256 = auto()
3554        UMEDIUMINT = auto()
3555        UNIQUEIDENTIFIER = auto()
3556        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3557        USERDEFINED = "USER-DEFINED"
3558        USMALLINT = auto()
3559        UTINYINT = auto()
3560        UUID = auto()
3561        VARBINARY = auto()
3562        VARCHAR = auto()
3563        VARIANT = auto()
3564        XML = auto()
3565        YEAR = auto()

An enumeration.

ARRAY = <Type.ARRAY: 'ARRAY'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <Type.BIGINT: 'BIGINT'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
BINARY = <Type.BINARY: 'BINARY'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
CHAR = <Type.CHAR: 'CHAR'>
DATE = <Type.DATE: 'DATE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
ENUM = <Type.ENUM: 'ENUM'>
ENUM8 = <Type.ENUM8: 'ENUM8'>
ENUM16 = <Type.ENUM16: 'ENUM16'>
FIXEDSTRING = <Type.FIXEDSTRING: 'FIXEDSTRING'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
IPADDRESS = <Type.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <Type.IPPREFIX: 'IPPREFIX'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
LOWCARDINALITY = <Type.LOWCARDINALITY: 'LOWCARDINALITY'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMINT = <Type.MEDIUMINT: 'MEDIUMINT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NESTED = <Type.NESTED: 'NESTED'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TINYBLOB = <Type.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <Type.TINYTEXT: 'TINYTEXT'>
TIME = <Type.TIME: 'TIME'>
TIMETZ = <Type.TIMETZ: 'TIMETZ'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UMEDIUMINT = <Type.UMEDIUMINT: 'UMEDIUMINT'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
YEAR = <Type.YEAR: 'YEAR'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3676class PseudoType(Expression):
3677    pass
key = 'pseudotype'
class ObjectIdentifier(Expression):
3681class ObjectIdentifier(Expression):
3682    pass
key = 'objectidentifier'
class SubqueryPredicate(Predicate):
3686class SubqueryPredicate(Predicate):
3687    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3690class All(SubqueryPredicate):
3691    pass
key = 'all'
class Any(SubqueryPredicate):
3694class Any(SubqueryPredicate):
3695    pass
key = 'any'
class Exists(SubqueryPredicate):
3698class Exists(SubqueryPredicate):
3699    pass
key = 'exists'
class Command(Expression):
3704class Command(Expression):
3705    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3708class Transaction(Expression):
3709    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3712class Commit(Expression):
3713    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3716class Rollback(Expression):
3717    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3720class AlterTable(Expression):
3721    arg_types = {"this": True, "actions": True, "exists": False, "only": False}
arg_types = {'this': True, 'actions': True, 'exists': False, 'only': False}
key = 'altertable'
class AddConstraint(Expression):
3724class AddConstraint(Expression):
3725    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3728class DropPartition(Expression):
3729    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3733class Binary(Condition):
3734    arg_types = {"this": True, "expression": True}
3735
3736    @property
3737    def left(self):
3738        return self.this
3739
3740    @property
3741    def right(self):
3742        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3745class Add(Binary):
3746    pass
key = 'add'
class Connector(Binary):
3749class Connector(Binary):
3750    pass
key = 'connector'
class And(Connector):
3753class And(Connector):
3754    pass
key = 'and'
class Or(Connector):
3757class Or(Connector):
3758    pass
key = 'or'
class BitwiseAnd(Binary):
3761class BitwiseAnd(Binary):
3762    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3765class BitwiseLeftShift(Binary):
3766    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3769class BitwiseOr(Binary):
3770    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3773class BitwiseRightShift(Binary):
3774    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3777class BitwiseXor(Binary):
3778    pass
key = 'bitwisexor'
class Div(Binary):
3781class Div(Binary):
3782    pass
key = 'div'
class Overlaps(Binary):
3785class Overlaps(Binary):
3786    pass
key = 'overlaps'
class Dot(Binary):
3789class Dot(Binary):
3790    @property
3791    def name(self) -> str:
3792        return self.expression.name
3793
3794    @property
3795    def output_name(self) -> str:
3796        return self.name
3797
3798    @classmethod
3799    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3800        """Build a Dot object with a sequence of expressions."""
3801        if len(expressions) < 2:
3802            raise ValueError(f"Dot requires >= 2 expressions.")
3803
3804        return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))
name: str
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
@classmethod
def build( self, expressions: Sequence[Expression]) -> Dot:
3798    @classmethod
3799    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3800        """Build a Dot object with a sequence of expressions."""
3801        if len(expressions) < 2:
3802            raise ValueError(f"Dot requires >= 2 expressions.")
3803
3804        return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3807class DPipe(Binary):
3808    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3811class SafeDPipe(DPipe):
3812    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3815class EQ(Binary, Predicate):
3816    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3819class NullSafeEQ(Binary, Predicate):
3820    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3823class NullSafeNEQ(Binary, Predicate):
3824    pass
key = 'nullsafeneq'
class Distance(Binary):
3827class Distance(Binary):
3828    pass
key = 'distance'
class Escape(Binary):
3831class Escape(Binary):
3832    pass
key = 'escape'
class Glob(Binary, Predicate):
3835class Glob(Binary, Predicate):
3836    pass
key = 'glob'
class GT(Binary, Predicate):
3839class GT(Binary, Predicate):
3840    pass
key = 'gt'
class GTE(Binary, Predicate):
3843class GTE(Binary, Predicate):
3844    pass
key = 'gte'
class ILike(Binary, Predicate):
3847class ILike(Binary, Predicate):
3848    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3851class ILikeAny(Binary, Predicate):
3852    pass
key = 'ilikeany'
class IntDiv(Binary):
3855class IntDiv(Binary):
3856    pass
key = 'intdiv'
class Is(Binary, Predicate):
3859class Is(Binary, Predicate):
3860    pass
key = 'is'
class Kwarg(Binary):
3863class Kwarg(Binary):
3864    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3867class Like(Binary, Predicate):
3868    pass
key = 'like'
class LikeAny(Binary, Predicate):
3871class LikeAny(Binary, Predicate):
3872    pass
key = 'likeany'
class LT(Binary, Predicate):
3875class LT(Binary, Predicate):
3876    pass
key = 'lt'
class LTE(Binary, Predicate):
3879class LTE(Binary, Predicate):
3880    pass
key = 'lte'
class Mod(Binary):
3883class Mod(Binary):
3884    pass
key = 'mod'
class Mul(Binary):
3887class Mul(Binary):
3888    pass
key = 'mul'
class NEQ(Binary, Predicate):
3891class NEQ(Binary, Predicate):
3892    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3895class SimilarTo(Binary, Predicate):
3896    pass
key = 'similarto'
class Slice(Binary):
3899class Slice(Binary):
3900    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3903class Sub(Binary):
3904    pass
key = 'sub'
class ArrayOverlaps(Binary):
3907class ArrayOverlaps(Binary):
3908    pass
key = 'arrayoverlaps'
class Unary(Condition):
3913class Unary(Condition):
3914    pass
key = 'unary'
class BitwiseNot(Unary):
3917class BitwiseNot(Unary):
3918    pass
key = 'bitwisenot'
class Not(Unary):
3921class Not(Unary):
3922    pass
key = 'not'
class Paren(Unary):
3925class Paren(Unary):
3926    arg_types = {"this": True, "with": False}
3927
3928    @property
3929    def output_name(self) -> str:
3930        return self.this.name
arg_types = {'this': True, 'with': False}
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'paren'
class Neg(Unary):
3933class Neg(Unary):
3934    pass
key = 'neg'
class Alias(Expression):
3937class Alias(Expression):
3938    arg_types = {"this": True, "alias": False}
3939
3940    @property
3941    def output_name(self) -> str:
3942        return self.alias
arg_types = {'this': True, 'alias': False}
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'alias'
class Aliases(Expression):
3945class Aliases(Expression):
3946    arg_types = {"this": True, "expressions": True}
3947
3948    @property
3949    def aliases(self):
3950        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3953class AtTimeZone(Expression):
3954    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3957class Between(Predicate):
3958    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3961class Bracket(Condition):
3962    arg_types = {"this": True, "expressions": True}
3963
3964    @property
3965    def output_name(self) -> str:
3966        if len(self.expressions) == 1:
3967            return self.expressions[0].output_name
3968
3969        return super().output_name
arg_types = {'this': True, 'expressions': True}
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'bracket'
class SafeBracket(Bracket):
3972class SafeBracket(Bracket):
3973    """Represents array lookup where OOB index yields NULL instead of causing a failure."""

Represents array lookup where OOB index yields NULL instead of causing a failure.

key = 'safebracket'
class Distinct(Expression):
3976class Distinct(Expression):
3977    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3980class In(Predicate):
3981    arg_types = {
3982        "this": True,
3983        "expressions": False,
3984        "query": False,
3985        "unnest": False,
3986        "field": False,
3987        "is_global": False,
3988    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3991class TimeUnit(Expression):
3992    """Automatically converts unit arg into a var."""
3993
3994    arg_types = {"unit": False}
3995
3996    def __init__(self, **args):
3997        unit = args.get("unit")
3998        if isinstance(unit, (Column, Literal)):
3999            args["unit"] = Var(this=unit.name)
4000        elif isinstance(unit, Week):
4001            unit.set("this", Var(this=unit.this.name))
4002
4003        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3996    def __init__(self, **args):
3997        unit = args.get("unit")
3998        if isinstance(unit, (Column, Literal)):
3999            args["unit"] = Var(this=unit.name)
4000        elif isinstance(unit, Week):
4001            unit.set("this", Var(this=unit.this.name))
4002
4003        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class IntervalSpan(Expression):
4009class IntervalSpan(Expression):
4010    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'intervalspan'
class Interval(TimeUnit):
4013class Interval(TimeUnit):
4014    arg_types = {"this": False, "unit": False}
4015
4016    @property
4017    def unit(self) -> t.Optional[Var]:
4018        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[Var]
key = 'interval'
class IgnoreNulls(Expression):
4021class IgnoreNulls(Expression):
4022    pass
key = 'ignorenulls'
class RespectNulls(Expression):
4025class RespectNulls(Expression):
4026    pass
key = 'respectnulls'
class Func(Condition):
4030class Func(Condition):
4031    """
4032    The base class for all function expressions.
4033
4034    Attributes:
4035        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
4036            treated as a variable length argument and the argument's value will be stored as a list.
4037        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
4038            for this function expression. These values are used to map this node to a name during parsing
4039            as well as to provide the function's name during SQL string generation. By default the SQL
4040            name is set to the expression's class name transformed to snake case.
4041    """
4042
4043    is_var_len_args = False
4044
4045    @classmethod
4046    def from_arg_list(cls, args):
4047        if cls.is_var_len_args:
4048            all_arg_keys = list(cls.arg_types)
4049            # If this function supports variable length argument treat the last argument as such.
4050            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4051            num_non_var = len(non_var_len_arg_keys)
4052
4053            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4054            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4055        else:
4056            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4057
4058        return cls(**args_dict)
4059
4060    @classmethod
4061    def sql_names(cls):
4062        if cls is Func:
4063            raise NotImplementedError(
4064                "SQL name is only supported by concrete function implementations"
4065            )
4066        if "_sql_names" not in cls.__dict__:
4067            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4068        return cls._sql_names
4069
4070    @classmethod
4071    def sql_name(cls):
4072        return cls.sql_names()[0]
4073
4074    @classmethod
4075    def default_parser_mappings(cls):
4076        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 last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines 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 = False
@classmethod
def from_arg_list(cls, args):
4045    @classmethod
4046    def from_arg_list(cls, args):
4047        if cls.is_var_len_args:
4048            all_arg_keys = list(cls.arg_types)
4049            # If this function supports variable length argument treat the last argument as such.
4050            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4051            num_non_var = len(non_var_len_arg_keys)
4052
4053            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4054            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4055        else:
4056            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4057
4058        return cls(**args_dict)
@classmethod
def sql_names(cls):
4060    @classmethod
4061    def sql_names(cls):
4062        if cls is Func:
4063            raise NotImplementedError(
4064                "SQL name is only supported by concrete function implementations"
4065            )
4066        if "_sql_names" not in cls.__dict__:
4067            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4068        return cls._sql_names
@classmethod
def sql_name(cls):
4070    @classmethod
4071    def sql_name(cls):
4072        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
4074    @classmethod
4075    def default_parser_mappings(cls):
4076        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
4079class AggFunc(Func):
4080    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
4083class ParameterizedAgg(AggFunc):
4084    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
4087class Abs(Func):
4088    pass
key = 'abs'
class Transform(Func):
4092class Transform(Func):
4093    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
4096class Anonymous(Func):
4097    arg_types = {"this": True, "expressions": False}
4098    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
4103class Hll(AggFunc):
4104    arg_types = {"this": True, "expressions": False}
4105    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
4108class ApproxDistinct(AggFunc):
4109    arg_types = {"this": True, "accuracy": False}
4110    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
4113class Array(Func):
4114    arg_types = {"expressions": False}
4115    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
4119class ToChar(Func):
4120    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
4123class GenerateSeries(Func):
4124    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
4127class ArrayAgg(AggFunc):
4128    pass
key = 'arrayagg'
class ArrayAll(Func):
4131class ArrayAll(Func):
4132    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4135class ArrayAny(Func):
4136    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4139class ArrayConcat(Func):
4140    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4141    arg_types = {"this": True, "expressions": False}
4142    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4145class ArrayContains(Binary, Func):
4146    pass
key = 'arraycontains'
class ArrayContained(Binary):
4149class ArrayContained(Binary):
4150    pass
key = 'arraycontained'
class ArrayFilter(Func):
4153class ArrayFilter(Func):
4154    arg_types = {"this": True, "expression": True}
4155    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4158class ArrayJoin(Func):
4159    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4162class ArraySize(Func):
4163    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4166class ArraySort(Func):
4167    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4170class ArraySum(Func):
4171    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4174class ArrayUnionAgg(AggFunc):
4175    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4178class Avg(AggFunc):
4179    pass
key = 'avg'
class AnyValue(AggFunc):
4182class AnyValue(AggFunc):
4183    arg_types = {"this": True, "having": False, "max": False, "ignore_nulls": False}
arg_types = {'this': True, 'having': False, 'max': False, 'ignore_nulls': False}
key = 'anyvalue'
class First(Func):
4186class First(Func):
4187    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4190class Last(Func):
4191    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4194class Case(Func):
4195    arg_types = {"this": False, "ifs": True, "default": False}
4196
4197    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4198        instance = maybe_copy(self, copy)
4199        instance.append(
4200            "ifs",
4201            If(
4202                this=maybe_parse(condition, copy=copy, **opts),
4203                true=maybe_parse(then, copy=copy, **opts),
4204            ),
4205        )
4206        return instance
4207
4208    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4209        instance = maybe_copy(self, copy)
4210        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4211        return instance
arg_types = {'this': False, 'ifs': True, 'default': False}
def when( self, condition: Union[str, Expression], then: Union[str, Expression], copy: bool = True, **opts) -> Case:
4197    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4198        instance = maybe_copy(self, copy)
4199        instance.append(
4200            "ifs",
4201            If(
4202                this=maybe_parse(condition, copy=copy, **opts),
4203                true=maybe_parse(then, copy=copy, **opts),
4204            ),
4205        )
4206        return instance
def else_( self, condition: Union[str, Expression], copy: bool = True, **opts) -> Case:
4208    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4209        instance = maybe_copy(self, copy)
4210        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4211        return instance
key = 'case'
class Cast(Func):
4214class Cast(Func):
4215    arg_types = {"this": True, "to": True, "format": False}
4216
4217    @property
4218    def name(self) -> str:
4219        return self.this.name
4220
4221    @property
4222    def to(self) -> DataType:
4223        return self.args["to"]
4224
4225    @property
4226    def output_name(self) -> str:
4227        return self.name
4228
4229    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4230        """
4231        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4232        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4233        array<int> != array<float>.
4234
4235        Args:
4236            dtypes: the data types to compare this Cast's DataType to.
4237
4238        Returns:
4239            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4240        """
4241        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True, 'format': False}
name: str
to: DataType
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
def is_type( self, *dtypes: str | DataType | DataType.Type) -> bool:
4229    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4230        """
4231        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4232        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4233        array<int> != array<float>.
4234
4235        Args:
4236            dtypes: the data types to compare this Cast's DataType to.
4237
4238        Returns:
4239            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4240        """
4241        return self.to.is_type(*dtypes)

Checks whether this Cast's DataType matches one of the provided data types. Nested types like arrays or structs will be compared using "structural equivalence" semantics, so e.g. array != array.

Arguments:
  • dtypes: the data types to compare this Cast's DataType to.
Returns:

True, if and only if there is a type in dtypes which is equal to this Cast's DataType.

key = 'cast'
class TryCast(Cast):
4244class TryCast(Cast):
4245    pass
key = 'trycast'
class CastToStrType(Func):
4248class CastToStrType(Func):
4249    arg_types = {"this": True, "to": True}
arg_types = {'this': True, 'to': True}
key = 'casttostrtype'
class Collate(Binary):
4252class Collate(Binary):
4253    pass
key = 'collate'
class Ceil(Func):
4256class Ceil(Func):
4257    arg_types = {"this": True, "decimals": False}
4258    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4261class Coalesce(Func):
4262    arg_types = {"this": True, "expressions": False}
4263    is_var_len_args = True
4264    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4267class Concat(Func):
4268    arg_types = {"expressions": True}
4269    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4272class SafeConcat(Concat):
4273    pass
key = 'safeconcat'
class ConcatWs(Concat):
4276class ConcatWs(Concat):
4277    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4280class Count(AggFunc):
4281    arg_types = {"this": False, "expressions": False}
4282    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4285class CountIf(AggFunc):
4286    pass
key = 'countif'
class CurrentDate(Func):
4289class CurrentDate(Func):
4290    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4293class CurrentDatetime(Func):
4294    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4297class CurrentTime(Func):
4298    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4301class CurrentTimestamp(Func):
4302    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4305class CurrentUser(Func):
4306    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4309class DateAdd(Func, TimeUnit):
4310    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4313class DateSub(Func, TimeUnit):
4314    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4317class DateDiff(Func, TimeUnit):
4318    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4319    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4322class DateTrunc(Func):
4323    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4326class DatetimeAdd(Func, TimeUnit):
4327    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4330class DatetimeSub(Func, TimeUnit):
4331    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4334class DatetimeDiff(Func, TimeUnit):
4335    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4338class DatetimeTrunc(Func, TimeUnit):
4339    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4342class DayOfWeek(Func):
4343    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4346class DayOfMonth(Func):
4347    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4350class DayOfYear(Func):
4351    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4354class WeekOfYear(Func):
4355    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4358class MonthsBetween(Func):
4359    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4362class LastDateOfMonth(Func):
4363    pass
key = 'lastdateofmonth'
class Extract(Func):
4366class Extract(Func):
4367    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4370class TimestampAdd(Func, TimeUnit):
4371    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4374class TimestampSub(Func, TimeUnit):
4375    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4378class TimestampDiff(Func, TimeUnit):
4379    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4382class TimestampTrunc(Func, TimeUnit):
4383    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4386class TimeAdd(Func, TimeUnit):
4387    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4390class TimeSub(Func, TimeUnit):
4391    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4394class TimeDiff(Func, TimeUnit):
4395    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4398class TimeTrunc(Func, TimeUnit):
4399    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4402class DateFromParts(Func):
4403    _sql_names = ["DATEFROMPARTS"]
4404    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4407class DateStrToDate(Func):
4408    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4411class DateToDateStr(Func):
4412    pass
key = 'datetodatestr'
class DateToDi(Func):
4415class DateToDi(Func):
4416    pass
key = 'datetodi'
class Date(Func):
4420class Date(Func):
4421    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4424class Day(Func):
4425    pass
key = 'day'
class Decode(Func):
4428class Decode(Func):
4429    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4432class DiToDate(Func):
4433    pass
key = 'ditodate'
class Encode(Func):
4436class Encode(Func):
4437    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4440class Exp(Func):
4441    pass
key = 'exp'
class Explode(Func):
4444class Explode(Func):
4445    pass
key = 'explode'
class Floor(Func):
4448class Floor(Func):
4449    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4452class FromBase64(Func):
4453    pass
key = 'frombase64'
class ToBase64(Func):
4456class ToBase64(Func):
4457    pass
key = 'tobase64'
class Greatest(Func):
4460class Greatest(Func):
4461    arg_types = {"this": True, "expressions": False}
4462    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(AggFunc):
4465class GroupConcat(AggFunc):
4466    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4469class Hex(Func):
4470    pass
key = 'hex'
class Xor(Connector, Func):
4473class Xor(Connector, Func):
4474    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4477class If(Func):
4478    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4481class Initcap(Func):
4482    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4485class IsNan(Func):
4486    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class FormatJson(Expression):
4489class FormatJson(Expression):
4490    pass
key = 'formatjson'
class JSONKeyValue(Expression):
4493class JSONKeyValue(Expression):
4494    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4497class JSONObject(Func):
4498    arg_types = {
4499        "expressions": False,
4500        "null_handling": False,
4501        "unique_keys": False,
4502        "return_type": False,
4503        "encoding": False,
4504    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'encoding': False}
key = 'jsonobject'
class JSONArray(Func):
4508class JSONArray(Func):
4509    arg_types = {
4510        "expressions": True,
4511        "null_handling": False,
4512        "return_type": False,
4513        "strict": False,
4514    }
arg_types = {'expressions': True, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarray'
class JSONArrayAgg(Func):
4518class JSONArrayAgg(Func):
4519    arg_types = {
4520        "this": True,
4521        "order": False,
4522        "null_handling": False,
4523        "return_type": False,
4524        "strict": False,
4525    }
arg_types = {'this': True, 'order': False, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarrayagg'
class JSONColumnDef(Expression):
4530class JSONColumnDef(Expression):
4531    arg_types = {"this": True, "kind": False, "path": False}
arg_types = {'this': True, 'kind': False, 'path': False}
key = 'jsoncolumndef'
class JSONTable(Func):
4535class JSONTable(Func):
4536    arg_types = {
4537        "this": True,
4538        "expressions": True,
4539        "path": False,
4540        "error_handling": False,
4541        "empty_handling": False,
4542    }
arg_types = {'this': True, 'expressions': True, 'path': False, 'error_handling': False, 'empty_handling': False}
key = 'jsontable'
class OpenJSONColumnDef(Expression):
4545class OpenJSONColumnDef(Expression):
4546    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
arg_types = {'this': True, 'kind': True, 'path': False, 'as_json': False}
key = 'openjsoncolumndef'
class OpenJSON(Func):
4549class OpenJSON(Func):
4550    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4553class JSONBContains(Binary):
4554    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4557class JSONExtract(Binary, Func):
4558    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4561class JSONExtractScalar(JSONExtract):
4562    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4565class JSONBExtract(JSONExtract):
4566    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4569class JSONBExtractScalar(JSONExtract):
4570    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4573class JSONFormat(Func):
4574    arg_types = {"this": False, "options": False}
4575    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4579class JSONArrayContains(Binary, Predicate, Func):
4580    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4583class Least(Func):
4584    arg_types = {"this": True, "expressions": False}
4585    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4588class Left(Func):
4589    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4596class Length(Func):
4597    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4600class Levenshtein(Func):
4601    arg_types = {
4602        "this": True,
4603        "expression": False,
4604        "ins_cost": False,
4605        "del_cost": False,
4606        "sub_cost": False,
4607    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4610class Ln(Func):
4611    pass
key = 'ln'
class Log(Func):
4614class Log(Func):
4615    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4618class Log2(Func):
4619    pass
key = 'log2'
class Log10(Func):
4622class Log10(Func):
4623    pass
key = 'log10'
class LogicalOr(AggFunc):
4626class LogicalOr(AggFunc):
4627    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4630class LogicalAnd(AggFunc):
4631    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4634class Lower(Func):
4635    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4638class Map(Func):
4639    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4642class MapFromEntries(Func):
4643    pass
key = 'mapfromentries'
class StarMap(Func):
4646class StarMap(Func):
4647    pass
key = 'starmap'
class VarMap(Func):
4650class VarMap(Func):
4651    arg_types = {"keys": True, "values": True}
4652    is_var_len_args = True
4653
4654    @property
4655    def keys(self) -> t.List[Expression]:
4656        return self.args["keys"].expressions
4657
4658    @property
4659    def values(self) -> t.List[Expression]:
4660        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
keys: List[Expression]
values: List[Expression]
key = 'varmap'
class MatchAgainst(Func):
4664class MatchAgainst(Func):
4665    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4668class Max(AggFunc):
4669    arg_types = {"this": True, "expressions": False}
4670    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4673class MD5(Func):
4674    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4678class MD5Digest(Func):
4679    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4682class Min(AggFunc):
4683    arg_types = {"this": True, "expressions": False}
4684    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4687class Month(Func):
4688    pass
key = 'month'
class Nvl2(Func):
4691class Nvl2(Func):
4692    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4695class Posexplode(Func):
4696    pass
key = 'posexplode'
class Pow(Binary, Func):
4699class Pow(Binary, Func):
4700    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4703class PercentileCont(AggFunc):
4704    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4707class PercentileDisc(AggFunc):
4708    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4711class Quantile(AggFunc):
4712    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4715class ApproxQuantile(Quantile):
4716    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
arg_types = {'this': True, 'quantile': True, 'accuracy': False, 'weight': False}
key = 'approxquantile'
class RangeN(Func):
4719class RangeN(Func):
4720    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4723class ReadCSV(Func):
4724    _sql_names = ["READ_CSV"]
4725    is_var_len_args = True
4726    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4729class Reduce(Func):
4730    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
arg_types = {'this': True, 'initial': True, 'merge': True, 'finish': False}
key = 'reduce'
class RegexpExtract(Func):
4733class RegexpExtract(Func):
4734    arg_types = {
4735        "this": True,
4736        "expression": True,
4737        "position": False,
4738        "occurrence": False,
4739        "parameters": False,
4740        "group": False,
4741    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4744class RegexpReplace(Func):
4745    arg_types = {
4746        "this": True,
4747        "expression": True,
4748        "replacement": True,
4749        "position": False,
4750        "occurrence": False,
4751        "parameters": False,
4752    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4755class RegexpLike(Binary, Func):
4756    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4759class RegexpILike(Func):
4760    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4765class RegexpSplit(Func):
4766    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4769class Repeat(Func):
4770    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4773class Round(Func):
4774    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4777class RowNumber(Func):
4778    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4781class SafeDivide(Func):
4782    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4785class SetAgg(AggFunc):
4786    pass
key = 'setagg'
class SHA(Func):
4789class SHA(Func):
4790    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4793class SHA2(Func):
4794    _sql_names = ["SHA2"]
4795    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4798class SortArray(Func):
4799    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4802class Split(Func):
4803    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4808class Substring(Func):
4809    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4812class StandardHash(Func):
4813    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4816class StartsWith(Func):
4817    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4818    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4821class StrPosition(Func):
4822    arg_types = {
4823        "this": True,
4824        "substr": True,
4825        "position": False,
4826        "instance": False,
4827    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4830class StrToDate(Func):
4831    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4834class StrToTime(Func):
4835    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4840class StrToUnix(Func):
4841    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
4846class StrToMap(Func):
4847    arg_types = {
4848        "this": True,
4849        "pair_delim": False,
4850        "key_value_delim": False,
4851        "duplicate_resolution_callback": False,
4852    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
4855class NumberToStr(Func):
4856    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
4859class FromBase(Func):
4860    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4863class Struct(Func):
4864    arg_types = {"expressions": True}
4865    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4868class StructExtract(Func):
4869    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Stuff(Func):
4874class Stuff(Func):
4875    _sql_names = ["STUFF", "INSERT"]
4876    arg_types = {"this": True, "start": True, "length": True, "expression": True}
arg_types = {'this': True, 'start': True, 'length': True, 'expression': True}
key = 'stuff'
class Sum(AggFunc):
4879class Sum(AggFunc):
4880    pass
key = 'sum'
class Sqrt(Func):
4883class Sqrt(Func):
4884    pass
key = 'sqrt'
class Stddev(AggFunc):
4887class Stddev(AggFunc):
4888    pass
key = 'stddev'
class StddevPop(AggFunc):
4891class StddevPop(AggFunc):
4892    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4895class StddevSamp(AggFunc):
4896    pass
key = 'stddevsamp'
class TimeToStr(Func):
4899class TimeToStr(Func):
4900    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
4903class TimeToTimeStr(Func):
4904    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4907class TimeToUnix(Func):
4908    pass
key = 'timetounix'
class TimeStrToDate(Func):
4911class TimeStrToDate(Func):
4912    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4915class TimeStrToTime(Func):
4916    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4919class TimeStrToUnix(Func):
4920    pass
key = 'timestrtounix'
class Trim(Func):
4923class Trim(Func):
4924    arg_types = {
4925        "this": True,
4926        "expression": False,
4927        "position": False,
4928        "collation": False,
4929    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4932class TsOrDsAdd(Func, TimeUnit):
4933    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4936class TsOrDsToDateStr(Func):
4937    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4940class TsOrDsToDate(Func):
4941    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4944class TsOrDiToDi(Func):
4945    pass
key = 'tsorditodi'
class Unhex(Func):
4948class Unhex(Func):
4949    pass
key = 'unhex'
class UnixToStr(Func):
4952class UnixToStr(Func):
4953    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4958class UnixToTime(Func):
4959    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4960
4961    SECONDS = Literal.string("seconds")
4962    MILLIS = Literal.string("millis")
4963    MICROS = Literal.string("micros")
arg_types = {'this': True, 'scale': False, 'zone': False, 'hours': False, 'minutes': False}
SECONDS = (LITERAL this: seconds, is_string: True)
MILLIS = (LITERAL this: millis, is_string: True)
MICROS = (LITERAL this: micros, is_string: True)
key = 'unixtotime'
class UnixToTimeStr(Func):
4966class UnixToTimeStr(Func):
4967    pass
key = 'unixtotimestr'
class Upper(Func):
4970class Upper(Func):
4971    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4974class Variance(AggFunc):
4975    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4978class VariancePop(AggFunc):
4979    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4982class Week(Func):
4983    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4986class XMLTable(Func):
4987    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
arg_types = {'this': True, 'passing': False, 'columns': False, 'by_ref': False}
key = 'xmltable'
class Year(Func):
4990class Year(Func):
4991    pass
key = 'year'
class Use(Expression):
4994class Use(Expression):
4995    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4998class Merge(Expression):
4999    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
arg_types = {'this': True, 'using': True, 'on': True, 'expressions': True}
key = 'merge'
class When(Func):
5002class When(Func):
5003    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
arg_types = {'matched': True, 'source': False, 'condition': False, 'then': True}
key = 'when'
class NextValueFor(Func):
5008class NextValueFor(Func):
5009    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'Abs'>, <class 'AnyValue'>, <class 'ApproxDistinct'>, <class 'ApproxQuantile'>, <class 'Array'>, <class 'ArrayAgg'>, <class 'ArrayAll'>, <class 'ArrayAny'>, <class 'ArrayConcat'>, <class 'ArrayContains'>, <class 'ArrayFilter'>, <class 'ArrayJoin'>, <class 'ArraySize'>, <class 'ArraySort'>, <class 'ArraySum'>, <class 'ArrayUnionAgg'>, <class 'Avg'>, <class 'Case'>, <class 'Cast'>, <class 'CastToStrType'>, <class 'Ceil'>, <class 'Coalesce'>, <class 'Concat'>, <class 'ConcatWs'>, <class 'Count'>, <class 'CountIf'>, <class 'CurrentDate'>, <class 'CurrentDatetime'>, <class 'CurrentTime'>, <class 'CurrentTimestamp'>, <class 'CurrentUser'>, <class 'Date'>, <class 'DateAdd'>, <class 'DateDiff'>, <class 'DateFromParts'>, <class 'DateStrToDate'>, <class 'DateSub'>, <class 'DateToDateStr'>, <class 'DateToDi'>, <class 'DateTrunc'>, <class 'DatetimeAdd'>, <class 'DatetimeDiff'>, <class 'DatetimeSub'>, <class 'DatetimeTrunc'>, <class 'Day'>, <class 'DayOfMonth'>, <class 'DayOfWeek'>, <class 'DayOfYear'>, <class 'Decode'>, <class 'DiToDate'>, <class 'Encode'>, <class 'Exp'>, <class 'Explode'>, <class 'Extract'>, <class 'First'>, <class 'Floor'>, <class 'FromBase'>, <class 'FromBase64'>, <class 'GenerateSeries'>, <class 'Greatest'>, <class 'GroupConcat'>, <class 'Hex'>, <class 'Hll'>, <class 'If'>, <class 'Initcap'>, <class 'IsNan'>, <class 'JSONArray'>, <class 'JSONArrayAgg'>, <class 'JSONArrayContains'>, <class 'JSONBExtract'>, <class 'JSONBExtractScalar'>, <class 'JSONExtract'>, <class 'JSONExtractScalar'>, <class 'JSONFormat'>, <class 'JSONObject'>, <class 'JSONTable'>, <class 'Last'>, <class 'LastDateOfMonth'>, <class 'Least'>, <class 'Left'>, <class 'Length'>, <class 'Levenshtein'>, <class 'Ln'>, <class 'Log'>, <class 'Log10'>, <class 'Log2'>, <class 'LogicalAnd'>, <class 'LogicalOr'>, <class 'Lower'>, <class 'MD5'>, <class 'MD5Digest'>, <class 'Map'>, <class 'MapFromEntries'>, <class 'MatchAgainst'>, <class 'Max'>, <class 'Min'>, <class 'Month'>, <class 'MonthsBetween'>, <class 'NextValueFor'>, <class 'NumberToStr'>, <class 'Nvl2'>, <class 'OpenJSON'>, <class 'ParameterizedAgg'>, <class 'PercentileCont'>, <class 'PercentileDisc'>, <class 'Posexplode'>, <class 'Pow'>, <class 'Quantile'>, <class 'RangeN'>, <class 'ReadCSV'>, <class 'Reduce'>, <class 'RegexpExtract'>, <class 'RegexpILike'>, <class 'RegexpLike'>, <class 'RegexpReplace'>, <class 'RegexpSplit'>, <class 'Repeat'>, <class 'Right'>, <class 'Round'>, <class 'RowNumber'>, <class 'SHA'>, <class 'SHA2'>, <class 'SafeConcat'>, <class 'SafeDivide'>, <class 'SetAgg'>, <class 'SortArray'>, <class 'Split'>, <class 'Sqrt'>, <class 'StandardHash'>, <class 'StarMap'>, <class 'StartsWith'>, <class 'Stddev'>, <class 'StddevPop'>, <class 'StddevSamp'>, <class 'StrPosition'>, <class 'StrToDate'>, <class 'StrToMap'>, <class 'StrToTime'>, <class 'StrToUnix'>, <class 'Struct'>, <class 'StructExtract'>, <class 'Stuff'>, <class 'Substring'>, <class 'Sum'>, <class 'TimeAdd'>, <class 'TimeDiff'>, <class 'TimeStrToDate'>, <class 'TimeStrToTime'>, <class 'TimeStrToUnix'>, <class 'TimeSub'>, <class 'TimeToStr'>, <class 'TimeToTimeStr'>, <class 'TimeToUnix'>, <class 'TimeTrunc'>, <class 'TimestampAdd'>, <class 'TimestampDiff'>, <class 'TimestampSub'>, <class 'TimestampTrunc'>, <class 'ToBase64'>, <class 'ToChar'>, <class 'Transform'>, <class 'Trim'>, <class 'TryCast'>, <class 'TsOrDiToDi'>, <class 'TsOrDsAdd'>, <class 'TsOrDsToDate'>, <class 'TsOrDsToDateStr'>, <class 'Unhex'>, <class 'UnixToStr'>, <class 'UnixToTime'>, <class 'UnixToTimeStr'>, <class 'Upper'>, <class 'VarMap'>, <class 'Variance'>, <class 'VariancePop'>, <class 'Week'>, <class 'WeekOfYear'>, <class 'When'>, <class 'XMLTable'>, <class 'Xor'>, <class 'Year'>]
def maybe_parse( sql_or_expression: Union[str, Expression], *, into: Union[str, Type[Expression], Collection[Union[str, Type[Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> Expression:
5046def maybe_parse(
5047    sql_or_expression: ExpOrStr,
5048    *,
5049    into: t.Optional[IntoType] = None,
5050    dialect: DialectType = None,
5051    prefix: t.Optional[str] = None,
5052    copy: bool = False,
5053    **opts,
5054) -> Expression:
5055    """Gracefully handle a possible string or expression.
5056
5057    Example:
5058        >>> maybe_parse("1")
5059        (LITERAL this: 1, is_string: False)
5060        >>> maybe_parse(to_identifier("x"))
5061        (IDENTIFIER this: x, quoted: False)
5062
5063    Args:
5064        sql_or_expression: the SQL code string or an expression
5065        into: the SQLGlot Expression to parse into
5066        dialect: the dialect used to parse the input expressions (in the case that an
5067            input expression is a SQL string).
5068        prefix: a string to prefix the sql with before it gets parsed
5069            (automatically includes a space)
5070        copy: whether or not to copy the expression.
5071        **opts: other options to use to parse the input expressions (again, in the case
5072            that an input expression is a SQL string).
5073
5074    Returns:
5075        Expression: the parsed or given expression.
5076    """
5077    if isinstance(sql_or_expression, Expression):
5078        if copy:
5079            return sql_or_expression.copy()
5080        return sql_or_expression
5081
5082    if sql_or_expression is None:
5083        raise ParseError(f"SQL cannot be None")
5084
5085    import sqlglot
5086
5087    sql = str(sql_or_expression)
5088    if prefix:
5089        sql = f"{prefix} {sql}"
5090
5091    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 Expression 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 or not 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:

Expression: the parsed or given expression.

def maybe_copy(instance, copy=True):
5104def maybe_copy(instance, copy=True):
5105    return instance.copy() if copy and instance else instance
def union( left: Union[str, Expression], right: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Union:
5285def union(
5286    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5287) -> Union:
5288    """
5289    Initializes a syntax tree from one UNION expression.
5290
5291    Example:
5292        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5293        'SELECT * FROM foo UNION SELECT * FROM bla'
5294
5295    Args:
5296        left: the SQL code string corresponding to the left-hand side.
5297            If an `Expression` instance is passed, it will be used as-is.
5298        right: the SQL code string corresponding to the right-hand side.
5299            If an `Expression` instance is passed, it will be used as-is.
5300        distinct: set the DISTINCT flag if and only if this is true.
5301        dialect: the dialect used to parse the input expression.
5302        opts: other options to use to parse the input expressions.
5303
5304    Returns:
5305        The new Union instance.
5306    """
5307    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5308    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5309
5310    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union instance.

def intersect( left: Union[str, Expression], right: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Intersect:
5313def intersect(
5314    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5315) -> Intersect:
5316    """
5317    Initializes a syntax tree from one INTERSECT expression.
5318
5319    Example:
5320        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5321        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5322
5323    Args:
5324        left: the SQL code string corresponding to the left-hand side.
5325            If an `Expression` instance is passed, it will be used as-is.
5326        right: the SQL code string corresponding to the right-hand side.
5327            If an `Expression` instance is passed, it will be used as-is.
5328        distinct: set the DISTINCT flag if and only if this is true.
5329        dialect: the dialect used to parse the input expression.
5330        opts: other options to use to parse the input expressions.
5331
5332    Returns:
5333        The new Intersect instance.
5334    """
5335    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5336    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5337
5338    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect instance.

def except_( left: Union[str, Expression], right: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Except:
5341def except_(
5342    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5343) -> Except:
5344    """
5345    Initializes a syntax tree from one EXCEPT expression.
5346
5347    Example:
5348        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5349        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5350
5351    Args:
5352        left: the SQL code string corresponding to the left-hand side.
5353            If an `Expression` instance is passed, it will be used as-is.
5354        right: the SQL code string corresponding to the right-hand side.
5355            If an `Expression` instance is passed, it will be used as-is.
5356        distinct: set the DISTINCT flag if and only if this is true.
5357        dialect: the dialect used to parse the input expression.
5358        opts: other options to use to parse the input expressions.
5359
5360    Returns:
5361        The new Except instance.
5362    """
5363    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5364    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5365
5366    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except instance.

def select( *expressions: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Select:
5369def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5370    """
5371    Initializes a syntax tree from one or multiple SELECT expressions.
5372
5373    Example:
5374        >>> select("col1", "col2").from_("tbl").sql()
5375        'SELECT col1, col2 FROM tbl'
5376
5377    Args:
5378        *expressions: the SQL code string to parse as the expressions of a
5379            SELECT statement. If an Expression instance is passed, this is used as-is.
5380        dialect: the dialect used to parse the input expressions (in the case that an
5381            input expression is a SQL string).
5382        **opts: other options to use to parse the input expressions (again, in the case
5383            that an input expression is a SQL string).
5384
5385    Returns:
5386        Select: the syntax tree for the SELECT statement.
5387    """
5388    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_( expression: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Select:
5391def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5392    """
5393    Initializes a syntax tree from a FROM expression.
5394
5395    Example:
5396        >>> from_("tbl").select("col1", "col2").sql()
5397        'SELECT col1, col2 FROM tbl'
5398
5399    Args:
5400        *expression: the SQL code string to parse as the FROM expressions of a
5401            SELECT statement. If an Expression instance is passed, this is used as-is.
5402        dialect: the dialect used to parse the input expression (in the case that the
5403            input expression is a SQL string).
5404        **opts: other options to use to parse the input expressions (again, in the case
5405            that the input expression is a SQL string).
5406
5407    Returns:
5408        Select: the syntax tree for the SELECT statement.
5409    """
5410    return Select().from_(expression, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expression: the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression 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).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | Table, properties: dict, where: Union[str, Expression, NoneType] = None, from_: Union[str, Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Update:
5413def update(
5414    table: str | Table,
5415    properties: dict,
5416    where: t.Optional[ExpOrStr] = None,
5417    from_: t.Optional[ExpOrStr] = None,
5418    dialect: DialectType = None,
5419    **opts,
5420) -> Update:
5421    """
5422    Creates an update statement.
5423
5424    Example:
5425        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5426        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5427
5428    Args:
5429        *properties: dictionary of properties to set which are
5430            auto converted to sql objects eg None -> NULL
5431        where: sql conditional parsed into a WHERE statement
5432        from_: sql statement parsed into a FROM statement
5433        dialect: the dialect used to parse the input expressions.
5434        **opts: other options to use to parse the input expressions.
5435
5436    Returns:
5437        Update: the syntax tree for the UPDATE statement.
5438    """
5439    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5440    update_expr.set(
5441        "expressions",
5442        [
5443            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5444            for k, v in properties.items()
5445        ],
5446    )
5447    if from_:
5448        update_expr.set(
5449            "from",
5450            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5451        )
5452    if isinstance(where, Condition):
5453        where = Where(this=where)
5454    if where:
5455        update_expr.set(
5456            "where",
5457            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5458        )
5459    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, Expression], where: Union[str, Expression, NoneType] = None, returning: Union[str, Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Delete:
5462def delete(
5463    table: ExpOrStr,
5464    where: t.Optional[ExpOrStr] = None,
5465    returning: t.Optional[ExpOrStr] = None,
5466    dialect: DialectType = None,
5467    **opts,
5468) -> Delete:
5469    """
5470    Builds a delete statement.
5471
5472    Example:
5473        >>> delete("my_table", where="id > 1").sql()
5474        'DELETE FROM my_table WHERE id > 1'
5475
5476    Args:
5477        where: sql conditional parsed into a WHERE statement
5478        returning: sql conditional parsed into a RETURNING statement
5479        dialect: the dialect used to parse the input expressions.
5480        **opts: other options to use to parse the input expressions.
5481
5482    Returns:
5483        Delete: the syntax tree for the DELETE statement.
5484    """
5485    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5486    if where:
5487        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5488    if returning:
5489        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5490    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def insert( expression: Union[str, Expression], into: Union[str, Expression], columns: Optional[Sequence[Union[str, Expression]]] = None, overwrite: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Insert:
5493def insert(
5494    expression: ExpOrStr,
5495    into: ExpOrStr,
5496    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5497    overwrite: t.Optional[bool] = None,
5498    dialect: DialectType = None,
5499    copy: bool = True,
5500    **opts,
5501) -> Insert:
5502    """
5503    Builds an INSERT statement.
5504
5505    Example:
5506        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5507        'INSERT INTO tbl VALUES (1, 2, 3)'
5508
5509    Args:
5510        expression: the sql string or expression of the INSERT statement
5511        into: the tbl to insert data to.
5512        columns: optionally the table's column names.
5513        overwrite: whether to INSERT OVERWRITE or not.
5514        dialect: the dialect used to parse the input expressions.
5515        copy: whether or not to copy the expression.
5516        **opts: other options to use to parse the input expressions.
5517
5518    Returns:
5519        Insert: the syntax tree for the INSERT statement.
5520    """
5521    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5522    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5523
5524    if columns:
5525        this = _apply_list_builder(
5526            *columns,
5527            instance=Schema(this=this),
5528            arg="expressions",
5529            into=Identifier,
5530            copy=False,
5531            dialect=dialect,
5532            **opts,
5533        )
5534
5535    return Insert(this=this, expression=expr, overwrite=overwrite)

Builds an INSERT statement.

Example:
>>> insert("VALUES (1, 2, 3)", "tbl").sql()
'INSERT INTO tbl VALUES (1, 2, 3)'
Arguments:
  • expression: the sql string or expression of the INSERT statement
  • into: the tbl to insert data to.
  • columns: optionally the table's column names.
  • overwrite: whether to INSERT OVERWRITE or not.
  • dialect: the dialect used to parse the input expressions.
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Insert: the syntax tree for the INSERT statement.

def condition( expression: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
5538def condition(
5539    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5540) -> Condition:
5541    """
5542    Initialize a logical condition expression.
5543
5544    Example:
5545        >>> condition("x=1").sql()
5546        'x = 1'
5547
5548        This is helpful for composing larger logical syntax trees:
5549        >>> where = condition("x=1")
5550        >>> where = where.and_("y=1")
5551        >>> Select().from_("tbl").select("*").where(where).sql()
5552        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5553
5554    Args:
5555        *expression: the SQL code string to parse.
5556            If an Expression instance is passed, this is used as-is.
5557        dialect: the dialect used to parse the input expression (in the case that the
5558            input expression is a SQL string).
5559        copy: Whether or not to copy `expression` (only applies to expressions).
5560        **opts: other options to use to parse the input expressions (again, in the case
5561            that the input expression is a SQL string).
5562
5563    Returns:
5564        The new Condition instance
5565    """
5566    return maybe_parse(
5567        expression,
5568        into=Condition,
5569        dialect=dialect,
5570        copy=copy,
5571        **opts,
5572    )

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")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression: the SQL code string to parse. If an Expression 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 or not 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[str, Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
5575def and_(
5576    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5577) -> Condition:
5578    """
5579    Combine multiple conditions with an AND logical operator.
5580
5581    Example:
5582        >>> and_("x=1", and_("y=1", "z=1")).sql()
5583        'x = 1 AND (y = 1 AND z = 1)'
5584
5585    Args:
5586        *expressions: the SQL code strings to parse.
5587            If an Expression instance is passed, this is used as-is.
5588        dialect: the dialect used to parse the input expression.
5589        copy: whether or not to copy `expressions` (only applies to Expressions).
5590        **opts: other options to use to parse the input expressions.
5591
5592    Returns:
5593        And: the new condition
5594    """
5595    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **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 Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_( *expressions: Union[str, Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
5598def or_(
5599    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5600) -> Condition:
5601    """
5602    Combine multiple conditions with an OR logical operator.
5603
5604    Example:
5605        >>> or_("x=1", or_("y=1", "z=1")).sql()
5606        'x = 1 OR (y = 1 OR z = 1)'
5607
5608    Args:
5609        *expressions: the SQL code strings to parse.
5610            If an Expression instance is passed, this is used as-is.
5611        dialect: the dialect used to parse the input expression.
5612        copy: whether or not to copy `expressions` (only applies to Expressions).
5613        **opts: other options to use to parse the input expressions.
5614
5615    Returns:
5616        Or: the new condition
5617    """
5618    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **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 Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_( expression: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Not:
5621def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5622    """
5623    Wrap a condition with a NOT operator.
5624
5625    Example:
5626        >>> not_("this_suit='black'").sql()
5627        "NOT this_suit = 'black'"
5628
5629    Args:
5630        expression: the SQL code string to parse.
5631            If an Expression instance is passed, this is used as-is.
5632        dialect: the dialect used to parse the input expression.
5633        copy: whether to copy the expression or not.
5634        **opts: other options to use to parse the input expressions.
5635
5636    Returns:
5637        The new condition.
5638    """
5639    this = condition(
5640        expression,
5641        dialect=dialect,
5642        copy=copy,
5643        **opts,
5644    )
5645    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 Expression 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 paren( expression: Union[str, Expression], copy: bool = True) -> Paren:
5648def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5649    """
5650    Wrap an expression in parentheses.
5651
5652    Example:
5653        >>> paren("5 + 3").sql()
5654        '(5 + 3)'
5655
5656    Args:
5657        expression: the SQL code string to parse.
5658            If an Expression instance is passed, this is used as-is.
5659        copy: whether to copy the expression or not.
5660
5661    Returns:
5662        The wrapped expression.
5663    """
5664    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 Expression instance is passed, this is used as-is.
  • copy: whether to copy the expression or not.
Returns:

The wrapped expression.

SAFE_IDENTIFIER_RE = re.compile('^[_a-zA-Z][\\w]*$')
def to_identifier(name, quoted=None, copy=True):
5682def to_identifier(name, quoted=None, copy=True):
5683    """Builds an identifier.
5684
5685    Args:
5686        name: The name to turn into an identifier.
5687        quoted: Whether or not force quote the identifier.
5688        copy: Whether or not to copy a passed in Identefier node.
5689
5690    Returns:
5691        The identifier ast node.
5692    """
5693
5694    if name is None:
5695        return None
5696
5697    if isinstance(name, Identifier):
5698        identifier = maybe_copy(name, copy)
5699    elif isinstance(name, str):
5700        identifier = Identifier(
5701            this=name,
5702            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5703        )
5704    else:
5705        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5706    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
  • copy: Whether or not to copy a passed in Identefier node.
Returns:

The identifier ast node.

INTERVAL_STRING_RE = re.compile('\\s*([0-9]+)\\s*([a-zA-Z]+)\\s*')
def to_interval( interval: str | Literal) -> Interval:
5712def to_interval(interval: str | Literal) -> Interval:
5713    """Builds an interval expression from a string like '1 day' or '5 months'."""
5714    if isinstance(interval, Literal):
5715        if not interval.is_string:
5716            raise ValueError("Invalid interval string.")
5717
5718        interval = interval.this
5719
5720    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5721
5722    if not interval_parts:
5723        raise ValueError("Invalid interval string.")
5724
5725    return Interval(
5726        this=Literal.string(interval_parts.group(1)),
5727        unit=Var(this=interval_parts.group(2)),
5728    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, Table, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Optional[Table]:
5741def to_table(
5742    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5743) -> t.Optional[Table]:
5744    """
5745    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5746    If a table is passed in then that table is returned.
5747
5748    Args:
5749        sql_path: a `[catalog].[schema].[table]` string.
5750        dialect: the source dialect according to which the table name will be parsed.
5751        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5752
5753    Returns:
5754        A table expression.
5755    """
5756    if sql_path is None or isinstance(sql_path, Table):
5757        return sql_path
5758    if not isinstance(sql_path, str):
5759        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5760
5761    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5762    if table:
5763        for k, v in kwargs.items():
5764            table.set(k, v)
5765
5766    return table

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
  • dialect: the source dialect according to which the table name will be parsed.
  • kwargs: the kwargs to instantiate the resulting Table expression with.
Returns:

A table expression.

def to_column( sql_path: str | Column, **kwargs) -> Column:
5769def to_column(sql_path: str | Column, **kwargs) -> Column:
5770    """
5771    Create a column from a `[table].[column]` sql path. Schema is optional.
5772
5773    If a column is passed in then that column is returned.
5774
5775    Args:
5776        sql_path: `[table].[column]` string
5777    Returns:
5778        Table: A column expression
5779    """
5780    if sql_path is None or isinstance(sql_path, Column):
5781        return sql_path
5782    if not isinstance(sql_path, str):
5783        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5784    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, Expression], alias: str | Identifier, table: Union[bool, Sequence[str | Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts):
5787def alias_(
5788    expression: ExpOrStr,
5789    alias: str | Identifier,
5790    table: bool | t.Sequence[str | Identifier] = False,
5791    quoted: t.Optional[bool] = None,
5792    dialect: DialectType = None,
5793    copy: bool = True,
5794    **opts,
5795):
5796    """Create an Alias expression.
5797
5798    Example:
5799        >>> alias_('foo', 'bar').sql()
5800        'foo AS bar'
5801
5802        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5803        '(SELECT 1, 2) AS bar(a, b)'
5804
5805    Args:
5806        expression: the SQL code strings to parse.
5807            If an Expression instance is passed, this is used as-is.
5808        alias: the alias name to use. If the name has
5809            special characters it is quoted.
5810        table: Whether or not to create a table alias, can also be a list of columns.
5811        quoted: whether or not to quote the alias
5812        dialect: the dialect used to parse the input expression.
5813        copy: Whether or not to copy the expression.
5814        **opts: other options to use to parse the input expressions.
5815
5816    Returns:
5817        Alias: the aliased expression
5818    """
5819    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5820    alias = to_identifier(alias, quoted=quoted)
5821
5822    if table:
5823        table_alias = TableAlias(this=alias)
5824        exp.set("alias", table_alias)
5825
5826        if not isinstance(table, bool):
5827            for column in table:
5828                table_alias.append("columns", to_identifier(column, quoted=quoted))
5829
5830        return exp
5831
5832    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5833    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5834    # for the complete Window expression.
5835    #
5836    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5837
5838    if "alias" in exp.arg_types and not isinstance(exp, Window):
5839        exp.set("alias", alias)
5840        return exp
5841    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 Expression 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 or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • copy: Whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery( expression: Union[str, Expression], alias: Union[Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Select:
5844def subquery(
5845    expression: ExpOrStr,
5846    alias: t.Optional[Identifier | str] = None,
5847    dialect: DialectType = None,
5848    **opts,
5849) -> Select:
5850    """
5851    Build a subquery expression.
5852
5853    Example:
5854        >>> subquery('select x from tbl', 'bar').select('x').sql()
5855        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5856
5857    Args:
5858        expression: the SQL code strings to parse.
5859            If an Expression instance is passed, this is used as-is.
5860        alias: the alias name to use.
5861        dialect: the dialect used to parse the input expression.
5862        **opts: other options to use to parse the input expressions.
5863
5864    Returns:
5865        A new Select instance with the subquery expression included.
5866    """
5867
5868    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5869    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use.
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

A new Select instance with the subquery expression included.

def column( col: str | Identifier, table: Union[Identifier, str, NoneType] = None, db: Union[Identifier, str, NoneType] = None, catalog: Union[Identifier, str, NoneType] = None, quoted: Optional[bool] = None) -> Column:
5872def column(
5873    col: str | Identifier,
5874    table: t.Optional[str | Identifier] = None,
5875    db: t.Optional[str | Identifier] = None,
5876    catalog: t.Optional[str | Identifier] = None,
5877    quoted: t.Optional[bool] = None,
5878) -> Column:
5879    """
5880    Build a Column.
5881
5882    Args:
5883        col: Column name.
5884        table: Table name.
5885        db: Database name.
5886        catalog: Catalog name.
5887        quoted: Whether to force quotes on the column's identifiers.
5888
5889    Returns:
5890        The new Column instance.
5891    """
5892    return Column(
5893        this=to_identifier(col, quoted=quoted),
5894        table=to_identifier(table, quoted=quoted),
5895        db=to_identifier(db, quoted=quoted),
5896        catalog=to_identifier(catalog, quoted=quoted),
5897    )

Build a Column.

Arguments:
  • col: Column name.
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quoted: Whether to force quotes on the column's identifiers.
Returns:

The new Column instance.

def cast( expression: Union[str, Expression], to: str | DataType | DataType.Type, **opts) -> Cast:
5900def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5901    """Cast an expression to a data type.
5902
5903    Example:
5904        >>> cast('x + 1', 'int').sql()
5905        'CAST(x + 1 AS INT)'
5906
5907    Args:
5908        expression: The expression to cast.
5909        to: The datatype to cast to.
5910
5911    Returns:
5912        The new Cast instance.
5913    """
5914    expression = maybe_parse(expression, **opts)
5915    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

The new Cast instance.

def table_( table: Identifier | str, db: Union[Identifier, str, NoneType] = None, catalog: Union[Identifier, str, NoneType] = None, quoted: Optional[bool] = None, alias: Union[Identifier, str, NoneType] = None) -> Table:
5918def table_(
5919    table: Identifier | str,
5920    db: t.Optional[Identifier | str] = None,
5921    catalog: t.Optional[Identifier | str] = None,
5922    quoted: t.Optional[bool] = None,
5923    alias: t.Optional[Identifier | str] = None,
5924) -> Table:
5925    """Build a Table.
5926
5927    Args:
5928        table: Table name.
5929        db: Database name.
5930        catalog: Catalog name.
5931        quote: Whether to force quotes on the table's identifiers.
5932        alias: Table's alias.
5933
5934    Returns:
5935        The new Table instance.
5936    """
5937    return Table(
5938        this=to_identifier(table, quoted=quoted) if table else None,
5939        db=to_identifier(db, quoted=quoted) if db else None,
5940        catalog=to_identifier(catalog, quoted=quoted) if catalog else None,
5941        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5942    )

Build a Table.

Arguments:
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quote: Whether to force quotes on the table's identifiers.
  • alias: Table's alias.
Returns:

The new Table instance.

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, DataType], NoneType] = None) -> Values:
5945def values(
5946    values: t.Iterable[t.Tuple[t.Any, ...]],
5947    alias: t.Optional[str] = None,
5948    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5949) -> Values:
5950    """Build VALUES statement.
5951
5952    Example:
5953        >>> values([(1, '2')]).sql()
5954        "VALUES (1, '2')"
5955
5956    Args:
5957        values: values statements that will be converted to SQL
5958        alias: optional alias
5959        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5960         If either are provided then an alias is also required.
5961
5962    Returns:
5963        Values: the Values expression object
5964    """
5965    if columns and not alias:
5966        raise ValueError("Alias is required when providing columns")
5967
5968    return Values(
5969        expressions=[convert(tup) for tup in values],
5970        alias=(
5971            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5972            if columns
5973            else (TableAlias(this=to_identifier(alias)) if alias else None)
5974        ),
5975    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns:

Values: the Values expression object

def var( name: Union[str, Expression, NoneType]) -> Var:
5978def var(name: t.Optional[ExpOrStr]) -> Var:
5979    """Build a SQL variable.
5980
5981    Example:
5982        >>> repr(var('x'))
5983        '(VAR this: x)'
5984
5985        >>> repr(var(column('x', table='y')))
5986        '(VAR this: x)'
5987
5988    Args:
5989        name: The name of the var or an expression who's name will become the var.
5990
5991    Returns:
5992        The new variable node.
5993    """
5994    if not name:
5995        raise ValueError("Cannot convert empty name into var.")
5996
5997    if isinstance(name, Expression):
5998        name = name.name
5999    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | Table, new_name: str | Table) -> AlterTable:
6002def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
6003    """Build ALTER TABLE... RENAME... expression
6004
6005    Args:
6006        old_name: The old name of the table
6007        new_name: The new name of the table
6008
6009    Returns:
6010        Alter table expression
6011    """
6012    old_table = to_table(old_name)
6013    new_table = to_table(new_name)
6014    return AlterTable(
6015        this=old_table,
6016        actions=[
6017            RenameTable(this=new_table),
6018        ],
6019    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value: Any, copy: bool = False) -> Expression:
6022def convert(value: t.Any, copy: bool = False) -> Expression:
6023    """Convert a python value into an expression object.
6024
6025    Raises an error if a conversion is not possible.
6026
6027    Args:
6028        value: A python object.
6029        copy: Whether or not to copy `value` (only applies to Expressions and collections).
6030
6031    Returns:
6032        Expression: the equivalent expression object.
6033    """
6034    if isinstance(value, Expression):
6035        return maybe_copy(value, copy)
6036    if isinstance(value, str):
6037        return Literal.string(value)
6038    if isinstance(value, bool):
6039        return Boolean(this=value)
6040    if value is None or (isinstance(value, float) and math.isnan(value)):
6041        return NULL
6042    if isinstance(value, numbers.Number):
6043        return Literal.number(value)
6044    if isinstance(value, datetime.datetime):
6045        datetime_literal = Literal.string(
6046            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
6047        )
6048        return TimeStrToTime(this=datetime_literal)
6049    if isinstance(value, datetime.date):
6050        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
6051        return DateStrToDate(this=date_literal)
6052    if isinstance(value, tuple):
6053        return Tuple(expressions=[convert(v, copy=copy) for v in value])
6054    if isinstance(value, list):
6055        return Array(expressions=[convert(v, copy=copy) for v in value])
6056    if isinstance(value, dict):
6057        return Map(
6058            keys=Array(expressions=[convert(k, copy=copy) for k in value]),
6059            values=Array(expressions=[convert(v, copy=copy) for v in value.values()]),
6060        )
6061    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 or not to copy value (only applies to Expressions and collections).
Returns:

Expression: the equivalent expression object.

def replace_children( expression: Expression, fun: Callable, *args, **kwargs) -> None:
6064def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
6065    """
6066    Replace children of an expression with the result of a lambda fun(child) -> exp.
6067    """
6068    for k, v in expression.args.items():
6069        is_list_arg = type(v) is list
6070
6071        child_nodes = v if is_list_arg else [v]
6072        new_child_nodes = []
6073
6074        for cn in child_nodes:
6075            if isinstance(cn, Expression):
6076                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
6077                    new_child_nodes.append(child_node)
6078                    child_node.parent = expression
6079                    child_node.arg_key = k
6080            else:
6081                new_child_nodes.append(cn)
6082
6083        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names( expression: Expression, exclude: str = '') -> Set[str]:
6086def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
6087    """
6088    Return all table names referenced through columns in an expression.
6089
6090    Example:
6091        >>> import sqlglot
6092        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
6093        ['a', 'c']
6094
6095    Args:
6096        expression: expression to find table names.
6097        exclude: a table name to exclude
6098
6099    Returns:
6100        A list of unique names.
6101    """
6102    return {
6103        table
6104        for table in (column.table for column in expression.find_all(Column))
6105        if table and table != exclude
6106    }

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
['a', 'c']
Arguments:
  • expression: expression to find table names.
  • exclude: a table name to exclude
Returns:

A list of unique names.

def table_name( table: Table | str, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) -> str:
6109def table_name(table: Table | str, dialect: DialectType = None) -> str:
6110    """Get the full name of a table as a string.
6111
6112    Args:
6113        table: Table expression node or string.
6114        dialect: The dialect to generate the table name for.
6115
6116    Examples:
6117        >>> from sqlglot import exp, parse_one
6118        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
6119        'a.b.c'
6120
6121    Returns:
6122        The table name.
6123    """
6124
6125    table = maybe_parse(table, into=Table)
6126
6127    if not table:
6128        raise ValueError(f"Cannot parse {table}")
6129
6130    return ".".join(
6131        part.sql(dialect=dialect, identify=True)
6132        if not SAFE_IDENTIFIER_RE.match(part.name)
6133        else part.name
6134        for part in table.parts
6135    )

Get the full name of a table as a string.

Arguments:
  • table: Table expression node or string.
  • dialect: The dialect to generate the table name for.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression: ~E, mapping: Dict[str, str], copy: bool = True) -> ~E:
6138def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
6139    """Replace all tables in expression according to the mapping.
6140
6141    Args:
6142        expression: expression node to be transformed and replaced.
6143        mapping: mapping of table names.
6144        copy: whether or not to copy the expression.
6145
6146    Examples:
6147        >>> from sqlglot import exp, parse_one
6148        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
6149        'SELECT * FROM c'
6150
6151    Returns:
6152        The mapped expression.
6153    """
6154
6155    def _replace_tables(node: Expression) -> Expression:
6156        if isinstance(node, Table):
6157            new_name = mapping.get(table_name(node))
6158            if new_name:
6159                return to_table(
6160                    new_name,
6161                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
6162                )
6163        return node
6164
6165    return expression.transform(_replace_tables, copy=copy)

Replace all tables in expression according to the mapping.

Arguments:
  • expression: expression node to be transformed and replaced.
  • mapping: mapping of table names.
  • copy: whether or not to copy the expression.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders( expression: Expression, *args, **kwargs) -> Expression:
6168def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
6169    """Replace placeholders in an expression.
6170
6171    Args:
6172        expression: expression node to be transformed and replaced.
6173        args: positional names that will substitute unnamed placeholders in the given order.
6174        kwargs: keyword arguments that will substitute named placeholders.
6175
6176    Examples:
6177        >>> from sqlglot import exp, parse_one
6178        >>> replace_placeholders(
6179        ...     parse_one("select * from :tbl where ? = ?"),
6180        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
6181        ... ).sql()
6182        "SELECT * FROM foo WHERE str_col = 'b'"
6183
6184    Returns:
6185        The mapped expression.
6186    """
6187
6188    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
6189        if isinstance(node, Placeholder):
6190            if node.name:
6191                new_name = kwargs.get(node.name)
6192                if new_name:
6193                    return convert(new_name)
6194            else:
6195                try:
6196                    return convert(next(args))
6197                except StopIteration:
6198                    pass
6199        return node
6200
6201    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression: expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: Expression, sources: Dict[str, Subqueryable], copy: bool = True) -> Expression:
6204def expand(
6205    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
6206) -> Expression:
6207    """Transforms an expression by expanding all referenced sources into subqueries.
6208
6209    Examples:
6210        >>> from sqlglot import parse_one
6211        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
6212        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
6213
6214        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
6215        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
6216
6217    Args:
6218        expression: The expression to expand.
6219        sources: A dictionary of name to Subqueryables.
6220        copy: Whether or not to copy the expression during transformation. Defaults to True.
6221
6222    Returns:
6223        The transformed expression.
6224    """
6225
6226    def _expand(node: Expression):
6227        if isinstance(node, Table):
6228            name = table_name(node)
6229            source = sources.get(name)
6230            if source:
6231                subquery = source.subquery(node.alias or name)
6232                subquery.comments = [f"source: {name}"]
6233                return subquery.transform(_expand, copy=False)
6234        return node
6235
6236    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Func:
6239def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6240    """
6241    Returns a Func expression.
6242
6243    Examples:
6244        >>> func("abs", 5).sql()
6245        'ABS(5)'
6246
6247        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6248        'CAST(5 AS DOUBLE)'
6249
6250    Args:
6251        name: the name of the function to build.
6252        args: the args used to instantiate the function of interest.
6253        dialect: the source dialect.
6254        kwargs: the kwargs used to instantiate the function of interest.
6255
6256    Note:
6257        The arguments `args` and `kwargs` are mutually exclusive.
6258
6259    Returns:
6260        An instance of the function of interest, or an anonymous function, if `name` doesn't
6261        correspond to an existing `sqlglot.expressions.Func` class.
6262    """
6263    if args and kwargs:
6264        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6265
6266    from sqlglot.dialects.dialect import Dialect
6267
6268    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6269    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6270
6271    parser = Dialect.get_or_raise(dialect)().parser()
6272    from_args_list = parser.FUNCTIONS.get(name.upper())
6273
6274    if from_args_list:
6275        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6276    else:
6277        kwargs = kwargs or {"expressions": converted}
6278        function = Anonymous(this=name, **kwargs)
6279
6280    for error_message in function.error_messages(converted):
6281        raise ValueError(error_message)
6282
6283    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing Func class.

def true() -> Boolean:
6286def true() -> Boolean:
6287    """
6288    Returns a true Boolean expression.
6289    """
6290    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> Boolean:
6293def false() -> Boolean:
6294    """
6295    Returns a false Boolean expression.
6296    """
6297    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> Null:
6300def null() -> Null:
6301    """
6302    Returns a Null expression.
6303    """
6304    return Null()

Returns a Null expression.

TRUE = (BOOLEAN this: True)
FALSE = (BOOLEAN this: False)
NULL = (NULL )