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

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

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

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):
1504class Drop(Expression):
1505    arg_types = {
1506        "this": False,
1507        "kind": False,
1508        "exists": False,
1509        "temporary": False,
1510        "materialized": False,
1511        "cascade": False,
1512        "constraints": False,
1513        "purge": False,
1514    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1517class Filter(Expression):
1518    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1521class Check(Expression):
1522    pass
key = 'check'
class Connect(Expression):
1526class Connect(Expression):
1527    arg_types = {"start": False, "connect": True}
arg_types = {'start': False, 'connect': True}
key = 'connect'
class Prior(Expression):
1530class Prior(Expression):
1531    pass
key = 'prior'
class Directory(Expression):
1534class Directory(Expression):
1535    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1536    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1539class ForeignKey(Expression):
1540    arg_types = {
1541        "expressions": True,
1542        "reference": False,
1543        "delete": False,
1544        "update": False,
1545    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class ColumnPrefix(Expression):
1548class ColumnPrefix(Expression):
1549    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'columnprefix'
class PrimaryKey(Expression):
1552class PrimaryKey(Expression):
1553    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1558class Into(Expression):
1559    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1562class From(Expression):
1563    @property
1564    def name(self) -> str:
1565        return self.this.name
1566
1567    @property
1568    def alias_or_name(self) -> str:
1569        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1572class Having(Expression):
1573    pass
key = 'having'
class Hint(Expression):
1576class Hint(Expression):
1577    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1580class JoinHint(Expression):
1581    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1584class Identifier(Expression):
1585    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1586
1587    @property
1588    def quoted(self) -> bool:
1589        return bool(self.args.get("quoted"))
1590
1591    @property
1592    def hashable_args(self) -> t.Any:
1593        return (self.this, self.quoted)
1594
1595    @property
1596    def output_name(self) -> str:
1597        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):
1600class Index(Expression):
1601    arg_types = {
1602        "this": False,
1603        "table": False,
1604        "using": False,
1605        "where": False,
1606        "columns": False,
1607        "unique": False,
1608        "primary": False,
1609        "amp": False,  # teradata
1610        "partition_by": False,  # teradata
1611    }
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):
1614class Insert(DDL):
1615    arg_types = {
1616        "with": False,
1617        "this": True,
1618        "expression": False,
1619        "conflict": False,
1620        "returning": False,
1621        "overwrite": False,
1622        "exists": False,
1623        "partition": False,
1624        "alternative": False,
1625        "where": False,
1626        "ignore": False,
1627        "by_name": False,
1628    }
1629
1630    def with_(
1631        self,
1632        alias: ExpOrStr,
1633        as_: ExpOrStr,
1634        recursive: t.Optional[bool] = None,
1635        append: bool = True,
1636        dialect: DialectType = None,
1637        copy: bool = True,
1638        **opts,
1639    ) -> Insert:
1640        """
1641        Append to or set the common table expressions.
1642
1643        Example:
1644            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1645            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1646
1647        Args:
1648            alias: the SQL code string to parse as the table name.
1649                If an `Expression` instance is passed, this is used as-is.
1650            as_: the SQL code string to parse as the table expression.
1651                If an `Expression` instance is passed, it will be used as-is.
1652            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1653            append: if `True`, add to any existing expressions.
1654                Otherwise, this resets the expressions.
1655            dialect: the dialect used to parse the input expression.
1656            copy: if `False`, modify this expression instance in-place.
1657            opts: other options to use to parse the input expressions.
1658
1659        Returns:
1660            The modified expression.
1661        """
1662        return _apply_cte_builder(
1663            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1664        )
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:
1630    def with_(
1631        self,
1632        alias: ExpOrStr,
1633        as_: ExpOrStr,
1634        recursive: t.Optional[bool] = None,
1635        append: bool = True,
1636        dialect: DialectType = None,
1637        copy: bool = True,
1638        **opts,
1639    ) -> Insert:
1640        """
1641        Append to or set the common table expressions.
1642
1643        Example:
1644            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1645            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1646
1647        Args:
1648            alias: the SQL code string to parse as the table name.
1649                If an `Expression` instance is passed, this is used as-is.
1650            as_: the SQL code string to parse as the table expression.
1651                If an `Expression` instance is passed, it will be used as-is.
1652            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1653            append: if `True`, add to any existing expressions.
1654                Otherwise, this resets the expressions.
1655            dialect: the dialect used to parse the input expression.
1656            copy: if `False`, modify this expression instance in-place.
1657            opts: other options to use to parse the input expressions.
1658
1659        Returns:
1660            The modified expression.
1661        """
1662        return _apply_cte_builder(
1663            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1664        )

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):
1667class OnConflict(Expression):
1668    arg_types = {
1669        "duplicate": False,
1670        "expressions": False,
1671        "nothing": False,
1672        "key": False,
1673        "constraint": False,
1674    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1677class Returning(Expression):
1678    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1682class Introducer(Expression):
1683    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1687class National(Expression):
1688    pass
key = 'national'
class LoadData(Expression):
1691class LoadData(Expression):
1692    arg_types = {
1693        "this": True,
1694        "local": False,
1695        "overwrite": False,
1696        "inpath": True,
1697        "partition": False,
1698        "input_format": False,
1699        "serde": False,
1700    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1703class Partition(Expression):
1704    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1707class Fetch(Expression):
1708    arg_types = {
1709        "direction": False,
1710        "count": False,
1711        "percent": False,
1712        "with_ties": False,
1713    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1716class Group(Expression):
1717    arg_types = {
1718        "expressions": False,
1719        "grouping_sets": False,
1720        "cube": False,
1721        "rollup": False,
1722        "totals": False,
1723        "all": False,
1724    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1727class Lambda(Expression):
1728    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1731class Limit(Expression):
1732    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1735class Literal(Condition):
1736    arg_types = {"this": True, "is_string": True}
1737
1738    @property
1739    def hashable_args(self) -> t.Any:
1740        return (self.this, self.args.get("is_string"))
1741
1742    @classmethod
1743    def number(cls, number) -> Literal:
1744        return cls(this=str(number), is_string=False)
1745
1746    @classmethod
1747    def string(cls, string) -> Literal:
1748        return cls(this=str(string), is_string=True)
1749
1750    @property
1751    def output_name(self) -> str:
1752        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> Literal:
1742    @classmethod
1743    def number(cls, number) -> Literal:
1744        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> Literal:
1746    @classmethod
1747    def string(cls, string) -> Literal:
1748        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):
1755class Join(Expression):
1756    arg_types = {
1757        "this": True,
1758        "on": False,
1759        "side": False,
1760        "kind": False,
1761        "using": False,
1762        "method": False,
1763        "global": False,
1764        "hint": False,
1765    }
1766
1767    @property
1768    def method(self) -> str:
1769        return self.text("method").upper()
1770
1771    @property
1772    def kind(self) -> str:
1773        return self.text("kind").upper()
1774
1775    @property
1776    def side(self) -> str:
1777        return self.text("side").upper()
1778
1779    @property
1780    def hint(self) -> str:
1781        return self.text("hint").upper()
1782
1783    @property
1784    def alias_or_name(self) -> str:
1785        return self.this.alias_or_name
1786
1787    def on(
1788        self,
1789        *expressions: t.Optional[ExpOrStr],
1790        append: bool = True,
1791        dialect: DialectType = None,
1792        copy: bool = True,
1793        **opts,
1794    ) -> Join:
1795        """
1796        Append to or set the ON expressions.
1797
1798        Example:
1799            >>> import sqlglot
1800            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1801            'JOIN x ON y = 1'
1802
1803        Args:
1804            *expressions: the SQL code strings to parse.
1805                If an `Expression` instance is passed, it will be used as-is.
1806                Multiple expressions are combined with an AND operator.
1807            append: if `True`, AND the new expressions to any existing expression.
1808                Otherwise, this resets the expression.
1809            dialect: the dialect used to parse the input expressions.
1810            copy: if `False`, modify this expression instance in-place.
1811            opts: other options to use to parse the input expressions.
1812
1813        Returns:
1814            The modified Join expression.
1815        """
1816        join = _apply_conjunction_builder(
1817            *expressions,
1818            instance=self,
1819            arg="on",
1820            append=append,
1821            dialect=dialect,
1822            copy=copy,
1823            **opts,
1824        )
1825
1826        if join.kind == "CROSS":
1827            join.set("kind", None)
1828
1829        return join
1830
1831    def using(
1832        self,
1833        *expressions: t.Optional[ExpOrStr],
1834        append: bool = True,
1835        dialect: DialectType = None,
1836        copy: bool = True,
1837        **opts,
1838    ) -> Join:
1839        """
1840        Append to or set the USING expressions.
1841
1842        Example:
1843            >>> import sqlglot
1844            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1845            'JOIN x USING (foo, bla)'
1846
1847        Args:
1848            *expressions: the SQL code strings to parse.
1849                If an `Expression` instance is passed, it will be used as-is.
1850            append: if `True`, concatenate the new expressions to the existing "using" list.
1851                Otherwise, this resets the expression.
1852            dialect: the dialect used to parse the input expressions.
1853            copy: if `False`, modify this expression instance in-place.
1854            opts: other options to use to parse the input expressions.
1855
1856        Returns:
1857            The modified Join expression.
1858        """
1859        join = _apply_list_builder(
1860            *expressions,
1861            instance=self,
1862            arg="using",
1863            append=append,
1864            dialect=dialect,
1865            copy=copy,
1866            **opts,
1867        )
1868
1869        if join.kind == "CROSS":
1870            join.set("kind", None)
1871
1872        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:
1787    def on(
1788        self,
1789        *expressions: t.Optional[ExpOrStr],
1790        append: bool = True,
1791        dialect: DialectType = None,
1792        copy: bool = True,
1793        **opts,
1794    ) -> Join:
1795        """
1796        Append to or set the ON expressions.
1797
1798        Example:
1799            >>> import sqlglot
1800            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1801            'JOIN x ON y = 1'
1802
1803        Args:
1804            *expressions: the SQL code strings to parse.
1805                If an `Expression` instance is passed, it will be used as-is.
1806                Multiple expressions are combined with an AND operator.
1807            append: if `True`, AND the new expressions to any existing expression.
1808                Otherwise, this resets the expression.
1809            dialect: the dialect used to parse the input expressions.
1810            copy: if `False`, modify this expression instance in-place.
1811            opts: other options to use to parse the input expressions.
1812
1813        Returns:
1814            The modified Join expression.
1815        """
1816        join = _apply_conjunction_builder(
1817            *expressions,
1818            instance=self,
1819            arg="on",
1820            append=append,
1821            dialect=dialect,
1822            copy=copy,
1823            **opts,
1824        )
1825
1826        if join.kind == "CROSS":
1827            join.set("kind", None)
1828
1829        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:
1831    def using(
1832        self,
1833        *expressions: t.Optional[ExpOrStr],
1834        append: bool = True,
1835        dialect: DialectType = None,
1836        copy: bool = True,
1837        **opts,
1838    ) -> Join:
1839        """
1840        Append to or set the USING expressions.
1841
1842        Example:
1843            >>> import sqlglot
1844            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1845            'JOIN x USING (foo, bla)'
1846
1847        Args:
1848            *expressions: the SQL code strings to parse.
1849                If an `Expression` instance is passed, it will be used as-is.
1850            append: if `True`, concatenate the new expressions to the existing "using" list.
1851                Otherwise, this resets the expression.
1852            dialect: the dialect used to parse the input expressions.
1853            copy: if `False`, modify this expression instance in-place.
1854            opts: other options to use to parse the input expressions.
1855
1856        Returns:
1857            The modified Join expression.
1858        """
1859        join = _apply_list_builder(
1860            *expressions,
1861            instance=self,
1862            arg="using",
1863            append=append,
1864            dialect=dialect,
1865            copy=copy,
1866            **opts,
1867        )
1868
1869        if join.kind == "CROSS":
1870            join.set("kind", None)
1871
1872        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):
1875class Lateral(UDTF):
1876    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):
1879class MatchRecognize(Expression):
1880    arg_types = {
1881        "partition_by": False,
1882        "order": False,
1883        "measures": False,
1884        "rows": False,
1885        "after": False,
1886        "pattern": False,
1887        "define": False,
1888        "alias": False,
1889    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1894class Final(Expression):
1895    pass
key = 'final'
class Offset(Expression):
1898class Offset(Expression):
1899    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1902class Order(Expression):
1903    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1908class Cluster(Order):
1909    pass
key = 'cluster'
class Distribute(Order):
1912class Distribute(Order):
1913    pass
key = 'distribute'
class Sort(Order):
1916class Sort(Order):
1917    pass
key = 'sort'
class Ordered(Expression):
1920class Ordered(Expression):
1921    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1924class Property(Expression):
1925    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1928class AlgorithmProperty(Property):
1929    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1932class AutoIncrementProperty(Property):
1933    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1936class BlockCompressionProperty(Property):
1937    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):
1940class CharacterSetProperty(Property):
1941    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1944class ChecksumProperty(Property):
1945    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1948class CollateProperty(Property):
1949    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1952class CopyGrantsProperty(Property):
1953    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1956class DataBlocksizeProperty(Property):
1957    arg_types = {
1958        "size": False,
1959        "units": False,
1960        "minimum": False,
1961        "maximum": False,
1962        "default": False,
1963    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1966class DefinerProperty(Property):
1967    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1970class DistKeyProperty(Property):
1971    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1974class DistStyleProperty(Property):
1975    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1978class EngineProperty(Property):
1979    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
1982class HeapProperty(Property):
1983    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
1986class ToTableProperty(Property):
1987    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1990class ExecuteAsProperty(Property):
1991    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1994class ExternalProperty(Property):
1995    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1998class FallbackProperty(Property):
1999    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
2002class FileFormatProperty(Property):
2003    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
2006class FreespaceProperty(Property):
2007    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
2010class InputOutputFormat(Expression):
2011    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
2014class IsolatedLoadingProperty(Property):
2015    arg_types = {
2016        "no": True,
2017        "concurrent": True,
2018        "for_all": True,
2019        "for_insert": True,
2020        "for_none": True,
2021    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
2024class JournalProperty(Property):
2025    arg_types = {
2026        "no": False,
2027        "dual": False,
2028        "before": False,
2029        "local": False,
2030        "after": False,
2031    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
2034class LanguageProperty(Property):
2035    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
2039class ClusteredByProperty(Property):
2040    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
2043class DictProperty(Property):
2044    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2047class DictSubProperty(Property):
2048    pass
key = 'dictsubproperty'
class DictRange(Property):
2051class DictRange(Property):
2052    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2057class OnCluster(Property):
2058    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2061class LikeProperty(Property):
2062    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2065class LocationProperty(Property):
2066    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2069class LockingProperty(Property):
2070    arg_types = {
2071        "this": False,
2072        "kind": True,
2073        "for_or_in": True,
2074        "lock_type": True,
2075        "override": False,
2076    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2079class LogProperty(Property):
2080    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2083class MaterializedProperty(Property):
2084    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2087class MergeBlockRatioProperty(Property):
2088    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):
2091class NoPrimaryIndexProperty(Property):
2092    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnProperty(Property):
2095class OnProperty(Property):
2096    arg_types = {"this": True}
arg_types = {'this': True}
key = 'onproperty'
class OnCommitProperty(Property):
2099class OnCommitProperty(Property):
2100    arg_types = {"delete": False}
arg_types = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2103class PartitionedByProperty(Property):
2104    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2107class ReturnsProperty(Property):
2108    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2111class RowFormatProperty(Property):
2112    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2115class RowFormatDelimitedProperty(Property):
2116    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2117    arg_types = {
2118        "fields": False,
2119        "escaped": False,
2120        "collection_items": False,
2121        "map_keys": False,
2122        "lines": False,
2123        "null": False,
2124        "serde": False,
2125    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2128class RowFormatSerdeProperty(Property):
2129    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2133class QueryTransform(Expression):
2134    arg_types = {
2135        "expressions": True,
2136        "command_script": True,
2137        "schema": False,
2138        "row_format_before": False,
2139        "record_writer": False,
2140        "row_format_after": False,
2141        "record_reader": False,
2142    }
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):
2145class SchemaCommentProperty(Property):
2146    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2149class SerdeProperties(Property):
2150    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2153class SetProperty(Property):
2154    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2157class SettingsProperty(Property):
2158    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2161class SortKeyProperty(Property):
2162    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2165class SqlSecurityProperty(Property):
2166    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2169class StabilityProperty(Property):
2170    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2173class TemporaryProperty(Property):
2174    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2177class TransientProperty(Property):
2178    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2181class VolatileProperty(Property):
2182    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2185class WithDataProperty(Property):
2186    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2189class WithJournalTableProperty(Property):
2190    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2193class Properties(Expression):
2194    arg_types = {"expressions": True}
2195
2196    NAME_TO_PROPERTY = {
2197        "ALGORITHM": AlgorithmProperty,
2198        "AUTO_INCREMENT": AutoIncrementProperty,
2199        "CHARACTER SET": CharacterSetProperty,
2200        "CLUSTERED_BY": ClusteredByProperty,
2201        "COLLATE": CollateProperty,
2202        "COMMENT": SchemaCommentProperty,
2203        "DEFINER": DefinerProperty,
2204        "DISTKEY": DistKeyProperty,
2205        "DISTSTYLE": DistStyleProperty,
2206        "ENGINE": EngineProperty,
2207        "EXECUTE AS": ExecuteAsProperty,
2208        "FORMAT": FileFormatProperty,
2209        "LANGUAGE": LanguageProperty,
2210        "LOCATION": LocationProperty,
2211        "PARTITIONED_BY": PartitionedByProperty,
2212        "RETURNS": ReturnsProperty,
2213        "ROW_FORMAT": RowFormatProperty,
2214        "SORTKEY": SortKeyProperty,
2215    }
2216
2217    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2218
2219    # CREATE property locations
2220    # Form: schema specified
2221    #   create [POST_CREATE]
2222    #     table a [POST_NAME]
2223    #     (b int) [POST_SCHEMA]
2224    #     with ([POST_WITH])
2225    #     index (b) [POST_INDEX]
2226    #
2227    # Form: alias selection
2228    #   create [POST_CREATE]
2229    #     table a [POST_NAME]
2230    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2231    #     index (c) [POST_INDEX]
2232    class Location(AutoName):
2233        POST_CREATE = auto()
2234        POST_NAME = auto()
2235        POST_SCHEMA = auto()
2236        POST_WITH = auto()
2237        POST_ALIAS = auto()
2238        POST_EXPRESSION = auto()
2239        POST_INDEX = auto()
2240        UNSUPPORTED = auto()
2241
2242    @classmethod
2243    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2244        expressions = []
2245        for key, value in properties_dict.items():
2246            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2247            if property_cls:
2248                expressions.append(property_cls(this=convert(value)))
2249            else:
2250                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2251
2252        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:
2242    @classmethod
2243    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2244        expressions = []
2245        for key, value in properties_dict.items():
2246            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2247            if property_cls:
2248                expressions.append(property_cls(this=convert(value)))
2249            else:
2250                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2251
2252        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2232    class Location(AutoName):
2233        POST_CREATE = auto()
2234        POST_NAME = auto()
2235        POST_SCHEMA = auto()
2236        POST_WITH = auto()
2237        POST_ALIAS = auto()
2238        POST_EXPRESSION = auto()
2239        POST_INDEX = auto()
2240        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):
2255class Qualify(Expression):
2256    pass
key = 'qualify'
class Return(Expression):
2260class Return(Expression):
2261    pass
key = 'return'
class Reference(Expression):
2264class Reference(Expression):
2265    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2268class Tuple(Expression):
2269    arg_types = {"expressions": False}
2270
2271    def isin(
2272        self,
2273        *expressions: t.Any,
2274        query: t.Optional[ExpOrStr] = None,
2275        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2276        copy: bool = True,
2277        **opts,
2278    ) -> In:
2279        return In(
2280            this=maybe_copy(self, copy),
2281            expressions=[convert(e, copy=copy) for e in expressions],
2282            query=maybe_parse(query, copy=copy, **opts) if query else None,
2283            unnest=Unnest(
2284                expressions=[
2285                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2286                ]
2287            )
2288            if unnest
2289            else None,
2290        )
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:
2271    def isin(
2272        self,
2273        *expressions: t.Any,
2274        query: t.Optional[ExpOrStr] = None,
2275        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2276        copy: bool = True,
2277        **opts,
2278    ) -> In:
2279        return In(
2280            this=maybe_copy(self, copy),
2281            expressions=[convert(e, copy=copy) for e in expressions],
2282            query=maybe_parse(query, copy=copy, **opts) if query else None,
2283            unnest=Unnest(
2284                expressions=[
2285                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2286                ]
2287            )
2288            if unnest
2289            else None,
2290        )
key = 'tuple'
class Subqueryable(Unionable):
2293class Subqueryable(Unionable):
2294    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2295        """
2296        Convert this expression to an aliased expression that can be used as a Subquery.
2297
2298        Example:
2299            >>> subquery = Select().select("x").from_("tbl").subquery()
2300            >>> Select().select("x").from_(subquery).sql()
2301            'SELECT x FROM (SELECT x FROM tbl)'
2302
2303        Args:
2304            alias (str | Identifier): an optional alias for the subquery
2305            copy (bool): if `False`, modify this expression instance in-place.
2306
2307        Returns:
2308            Alias: the subquery
2309        """
2310        instance = maybe_copy(self, copy)
2311        if not isinstance(alias, Expression):
2312            alias = TableAlias(this=to_identifier(alias)) if alias else None
2313
2314        return Subquery(this=instance, alias=alias)
2315
2316    def limit(
2317        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2318    ) -> Select:
2319        raise NotImplementedError
2320
2321    @property
2322    def ctes(self):
2323        with_ = self.args.get("with")
2324        if not with_:
2325            return []
2326        return with_.expressions
2327
2328    @property
2329    def selects(self) -> t.List[Expression]:
2330        raise NotImplementedError("Subqueryable objects must implement `selects`")
2331
2332    @property
2333    def named_selects(self) -> t.List[str]:
2334        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2335
2336    def select(
2337        self,
2338        *expressions: t.Optional[ExpOrStr],
2339        append: bool = True,
2340        dialect: DialectType = None,
2341        copy: bool = True,
2342        **opts,
2343    ) -> Subqueryable:
2344        raise NotImplementedError("Subqueryable objects must implement `select`")
2345
2346    def with_(
2347        self,
2348        alias: ExpOrStr,
2349        as_: ExpOrStr,
2350        recursive: t.Optional[bool] = None,
2351        append: bool = True,
2352        dialect: DialectType = None,
2353        copy: bool = True,
2354        **opts,
2355    ) -> Subqueryable:
2356        """
2357        Append to or set the common table expressions.
2358
2359        Example:
2360            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2361            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2362
2363        Args:
2364            alias: the SQL code string to parse as the table name.
2365                If an `Expression` instance is passed, this is used as-is.
2366            as_: the SQL code string to parse as the table expression.
2367                If an `Expression` instance is passed, it will be used as-is.
2368            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2369            append: if `True`, add to any existing expressions.
2370                Otherwise, this resets the expressions.
2371            dialect: the dialect used to parse the input expression.
2372            copy: if `False`, modify this expression instance in-place.
2373            opts: other options to use to parse the input expressions.
2374
2375        Returns:
2376            The modified expression.
2377        """
2378        return _apply_cte_builder(
2379            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2380        )
def subquery( self, alias: Union[str, Expression, NoneType] = None, copy: bool = True) -> Subquery:
2294    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2295        """
2296        Convert this expression to an aliased expression that can be used as a Subquery.
2297
2298        Example:
2299            >>> subquery = Select().select("x").from_("tbl").subquery()
2300            >>> Select().select("x").from_(subquery).sql()
2301            'SELECT x FROM (SELECT x FROM tbl)'
2302
2303        Args:
2304            alias (str | Identifier): an optional alias for the subquery
2305            copy (bool): if `False`, modify this expression instance in-place.
2306
2307        Returns:
2308            Alias: the subquery
2309        """
2310        instance = maybe_copy(self, copy)
2311        if not isinstance(alias, Expression):
2312            alias = TableAlias(this=to_identifier(alias)) if alias else None
2313
2314        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:
2316    def limit(
2317        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2318    ) -> Select:
2319        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:
2336    def select(
2337        self,
2338        *expressions: t.Optional[ExpOrStr],
2339        append: bool = True,
2340        dialect: DialectType = None,
2341        copy: bool = True,
2342        **opts,
2343    ) -> Subqueryable:
2344        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:
2346    def with_(
2347        self,
2348        alias: ExpOrStr,
2349        as_: ExpOrStr,
2350        recursive: t.Optional[bool] = None,
2351        append: bool = True,
2352        dialect: DialectType = None,
2353        copy: bool = True,
2354        **opts,
2355    ) -> Subqueryable:
2356        """
2357        Append to or set the common table expressions.
2358
2359        Example:
2360            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2361            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2362
2363        Args:
2364            alias: the SQL code string to parse as the table name.
2365                If an `Expression` instance is passed, this is used as-is.
2366            as_: the SQL code string to parse as the table expression.
2367                If an `Expression` instance is passed, it will be used as-is.
2368            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2369            append: if `True`, add to any existing expressions.
2370                Otherwise, this resets the expressions.
2371            dialect: the dialect used to parse the input expression.
2372            copy: if `False`, modify this expression instance in-place.
2373            opts: other options to use to parse the input expressions.
2374
2375        Returns:
2376            The modified expression.
2377        """
2378        return _apply_cte_builder(
2379            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2380        )

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):
2408class WithTableHint(Expression):
2409    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2413class IndexTableHint(Expression):
2414    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2417class Table(Expression):
2418    arg_types = {
2419        "this": True,
2420        "alias": False,
2421        "db": False,
2422        "catalog": False,
2423        "laterals": False,
2424        "joins": False,
2425        "pivots": False,
2426        "hints": False,
2427        "system_time": False,
2428        "version": False,
2429    }
2430
2431    @property
2432    def name(self) -> str:
2433        if isinstance(self.this, Func):
2434            return ""
2435        return self.this.name
2436
2437    @property
2438    def db(self) -> str:
2439        return self.text("db")
2440
2441    @property
2442    def catalog(self) -> str:
2443        return self.text("catalog")
2444
2445    @property
2446    def selects(self) -> t.List[Expression]:
2447        return []
2448
2449    @property
2450    def named_selects(self) -> t.List[str]:
2451        return []
2452
2453    @property
2454    def parts(self) -> t.List[Identifier]:
2455        """Return the parts of a table in order catalog, db, table."""
2456        parts: t.List[Identifier] = []
2457
2458        for arg in ("catalog", "db", "this"):
2459            part = self.args.get(arg)
2460
2461            if isinstance(part, Identifier):
2462                parts.append(part)
2463            elif isinstance(part, Dot):
2464                parts.extend(part.flatten())
2465
2466        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):
2469class Union(Subqueryable):
2470    arg_types = {
2471        "with": False,
2472        "this": True,
2473        "expression": True,
2474        "distinct": False,
2475        "by_name": False,
2476        **QUERY_MODIFIERS,
2477    }
2478
2479    def limit(
2480        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2481    ) -> Select:
2482        """
2483        Set the LIMIT expression.
2484
2485        Example:
2486            >>> select("1").union(select("1")).limit(1).sql()
2487            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2488
2489        Args:
2490            expression: the SQL code string to parse.
2491                This can also be an integer.
2492                If a `Limit` instance is passed, this is used as-is.
2493                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2494            dialect: the dialect used to parse the input expression.
2495            copy: if `False`, modify this expression instance in-place.
2496            opts: other options to use to parse the input expressions.
2497
2498        Returns:
2499            The limited subqueryable.
2500        """
2501        return (
2502            select("*")
2503            .from_(self.subquery(alias="_l_0", copy=copy))
2504            .limit(expression, dialect=dialect, copy=False, **opts)
2505        )
2506
2507    def select(
2508        self,
2509        *expressions: t.Optional[ExpOrStr],
2510        append: bool = True,
2511        dialect: DialectType = None,
2512        copy: bool = True,
2513        **opts,
2514    ) -> Union:
2515        """Append to or set the SELECT of the union recursively.
2516
2517        Example:
2518            >>> from sqlglot import parse_one
2519            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2520            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2521
2522        Args:
2523            *expressions: the SQL code strings to parse.
2524                If an `Expression` instance is passed, it will be used as-is.
2525            append: if `True`, add to any existing expressions.
2526                Otherwise, this resets the expressions.
2527            dialect: the dialect used to parse the input expressions.
2528            copy: if `False`, modify this expression instance in-place.
2529            opts: other options to use to parse the input expressions.
2530
2531        Returns:
2532            Union: the modified expression.
2533        """
2534        this = self.copy() if copy else self
2535        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2536        this.expression.unnest().select(
2537            *expressions, append=append, dialect=dialect, copy=False, **opts
2538        )
2539        return this
2540
2541    @property
2542    def named_selects(self) -> t.List[str]:
2543        return self.this.unnest().named_selects
2544
2545    @property
2546    def is_star(self) -> bool:
2547        return self.this.is_star or self.expression.is_star
2548
2549    @property
2550    def selects(self) -> t.List[Expression]:
2551        return self.this.unnest().selects
2552
2553    @property
2554    def left(self):
2555        return self.this
2556
2557    @property
2558    def right(self):
2559        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:
2479    def limit(
2480        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2481    ) -> Select:
2482        """
2483        Set the LIMIT expression.
2484
2485        Example:
2486            >>> select("1").union(select("1")).limit(1).sql()
2487            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2488
2489        Args:
2490            expression: the SQL code string to parse.
2491                This can also be an integer.
2492                If a `Limit` instance is passed, this is used as-is.
2493                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2494            dialect: the dialect used to parse the input expression.
2495            copy: if `False`, modify this expression instance in-place.
2496            opts: other options to use to parse the input expressions.
2497
2498        Returns:
2499            The limited subqueryable.
2500        """
2501        return (
2502            select("*")
2503            .from_(self.subquery(alias="_l_0", copy=copy))
2504            .limit(expression, dialect=dialect, copy=False, **opts)
2505        )

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

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

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

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

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

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

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

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

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

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

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

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

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:
3154    def window(
3155        self,
3156        *expressions: t.Optional[ExpOrStr],
3157        append: bool = True,
3158        dialect: DialectType = None,
3159        copy: bool = True,
3160        **opts,
3161    ) -> Select:
3162        return _apply_list_builder(
3163            *expressions,
3164            instance=self,
3165            arg="windows",
3166            append=append,
3167            into=Window,
3168            dialect=dialect,
3169            copy=copy,
3170            **opts,
3171        )
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:
3173    def qualify(
3174        self,
3175        *expressions: t.Optional[ExpOrStr],
3176        append: bool = True,
3177        dialect: DialectType = None,
3178        copy: bool = True,
3179        **opts,
3180    ) -> Select:
3181        return _apply_conjunction_builder(
3182            *expressions,
3183            instance=self,
3184            arg="qualify",
3185            append=append,
3186            into=Qualify,
3187            dialect=dialect,
3188            copy=copy,
3189            **opts,
3190        )
def distinct( self, *ons: Union[str, Expression, NoneType], distinct: bool = True, copy: bool = True) -> Select:
3192    def distinct(
3193        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3194    ) -> Select:
3195        """
3196        Set the OFFSET expression.
3197
3198        Example:
3199            >>> Select().from_("tbl").select("x").distinct().sql()
3200            'SELECT DISTINCT x FROM tbl'
3201
3202        Args:
3203            ons: the expressions to distinct on
3204            distinct: whether the Select should be distinct
3205            copy: if `False`, modify this expression instance in-place.
3206
3207        Returns:
3208            Select: the modified expression.
3209        """
3210        instance = maybe_copy(self, copy)
3211        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3212        instance.set("distinct", Distinct(on=on) if distinct else None)
3213        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:
3215    def ctas(
3216        self,
3217        table: ExpOrStr,
3218        properties: t.Optional[t.Dict] = None,
3219        dialect: DialectType = None,
3220        copy: bool = True,
3221        **opts,
3222    ) -> Create:
3223        """
3224        Convert this expression to a CREATE TABLE AS statement.
3225
3226        Example:
3227            >>> Select().select("*").from_("tbl").ctas("x").sql()
3228            'CREATE TABLE x AS SELECT * FROM tbl'
3229
3230        Args:
3231            table: the SQL code string to parse as the table name.
3232                If another `Expression` instance is passed, it will be used as-is.
3233            properties: an optional mapping of table properties
3234            dialect: the dialect used to parse the input table.
3235            copy: if `False`, modify this expression instance in-place.
3236            opts: other options to use to parse the input table.
3237
3238        Returns:
3239            The new Create expression.
3240        """
3241        instance = maybe_copy(self, copy)
3242        table_expression = maybe_parse(
3243            table,
3244            into=Table,
3245            dialect=dialect,
3246            **opts,
3247        )
3248        properties_expression = None
3249        if properties:
3250            properties_expression = Properties.from_dict(properties)
3251
3252        return Create(
3253            this=table_expression,
3254            kind="table",
3255            expression=instance,
3256            properties=properties_expression,
3257        )

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:
3259    def lock(self, update: bool = True, copy: bool = True) -> Select:
3260        """
3261        Set the locking read mode for this expression.
3262
3263        Examples:
3264            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3265            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3266
3267            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3268            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3269
3270        Args:
3271            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3272            copy: if `False`, modify this expression instance in-place.
3273
3274        Returns:
3275            The modified expression.
3276        """
3277        inst = maybe_copy(self, copy)
3278        inst.set("locks", [Lock(update=update)])
3279
3280        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:
3282    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3283        """
3284        Set hints for this expression.
3285
3286        Examples:
3287            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3288            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3289
3290        Args:
3291            hints: The SQL code strings to parse as the hints.
3292                If an `Expression` instance is passed, it will be used as-is.
3293            dialect: The dialect used to parse the hints.
3294            copy: If `False`, modify this expression instance in-place.
3295
3296        Returns:
3297            The modified expression.
3298        """
3299        inst = maybe_copy(self, copy)
3300        inst.set(
3301            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3302        )
3303
3304        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):
3319class Subquery(DerivedTable, Unionable):
3320    arg_types = {
3321        "this": True,
3322        "alias": False,
3323        "with": False,
3324        **QUERY_MODIFIERS,
3325    }
3326
3327    def unnest(self):
3328        """
3329        Returns the first non subquery.
3330        """
3331        expression = self
3332        while isinstance(expression, Subquery):
3333            expression = expression.this
3334        return expression
3335
3336    def unwrap(self) -> Subquery:
3337        expression = self
3338        while expression.same_parent and expression.is_wrapper:
3339            expression = t.cast(Subquery, expression.parent)
3340        return expression
3341
3342    @property
3343    def is_wrapper(self) -> bool:
3344        """
3345        Whether this Subquery acts as a simple wrapper around another expression.
3346
3347        SELECT * FROM (((SELECT * FROM t)))
3348                      ^
3349                      This corresponds to a "wrapper" Subquery node
3350        """
3351        return all(v is None for k, v in self.args.items() if k != "this")
3352
3353    @property
3354    def is_star(self) -> bool:
3355        return self.this.is_star
3356
3357    @property
3358    def output_name(self) -> str:
3359        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):
3327    def unnest(self):
3328        """
3329        Returns the first non subquery.
3330        """
3331        expression = self
3332        while isinstance(expression, Subquery):
3333            expression = expression.this
3334        return expression

Returns the first non subquery.

def unwrap(self) -> Subquery:
3336    def unwrap(self) -> Subquery:
3337        expression = self
3338        while expression.same_parent and expression.is_wrapper:
3339            expression = t.cast(Subquery, expression.parent)
3340        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):
3362class TableSample(Expression):
3363    arg_types = {
3364        "this": False,
3365        "expressions": False,
3366        "method": False,
3367        "bucket_numerator": False,
3368        "bucket_denominator": False,
3369        "bucket_field": False,
3370        "percent": False,
3371        "rows": False,
3372        "size": False,
3373        "seed": False,
3374        "kind": False,
3375    }
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):
3378class Tag(Expression):
3379    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3380
3381    arg_types = {
3382        "this": False,
3383        "prefix": False,
3384        "postfix": False,
3385    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3390class Pivot(Expression):
3391    arg_types = {
3392        "this": False,
3393        "alias": False,
3394        "expressions": True,
3395        "field": False,
3396        "unpivot": False,
3397        "using": False,
3398        "group": False,
3399        "columns": False,
3400        "include_nulls": False,
3401    }
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):
3404class Window(Condition):
3405    arg_types = {
3406        "this": True,
3407        "partition_by": False,
3408        "order": False,
3409        "spec": False,
3410        "alias": False,
3411        "over": False,
3412        "first": False,
3413    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3416class WindowSpec(Expression):
3417    arg_types = {
3418        "kind": False,
3419        "start": False,
3420        "start_side": False,
3421        "end": False,
3422        "end_side": False,
3423    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3426class Where(Expression):
3427    pass
key = 'where'
class Star(Expression):
3430class Star(Expression):
3431    arg_types = {"except": False, "replace": False}
3432
3433    @property
3434    def name(self) -> str:
3435        return "*"
3436
3437    @property
3438    def output_name(self) -> str:
3439        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):
3442class Parameter(Condition):
3443    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3446class SessionParameter(Condition):
3447    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3450class Placeholder(Condition):
3451    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3454class Null(Condition):
3455    arg_types: t.Dict[str, t.Any] = {}
3456
3457    @property
3458    def name(self) -> str:
3459        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3462class Boolean(Condition):
3463    pass
key = 'boolean'
class DataTypeParam(Expression):
3466class DataTypeParam(Expression):
3467    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypeparam'
class DataType(Expression):
3470class DataType(Expression):
3471    arg_types = {
3472        "this": True,
3473        "expressions": False,
3474        "nested": False,
3475        "values": False,
3476        "prefix": False,
3477        "kind": False,
3478    }
3479
3480    class Type(AutoName):
3481        ARRAY = auto()
3482        BIGDECIMAL = auto()
3483        BIGINT = auto()
3484        BIGSERIAL = auto()
3485        BINARY = auto()
3486        BIT = auto()
3487        BOOLEAN = auto()
3488        CHAR = auto()
3489        DATE = auto()
3490        DATEMULTIRANGE = auto()
3491        DATERANGE = auto()
3492        DATETIME = auto()
3493        DATETIME64 = auto()
3494        DECIMAL = auto()
3495        DOUBLE = auto()
3496        ENUM = auto()
3497        ENUM8 = auto()
3498        ENUM16 = auto()
3499        FIXEDSTRING = auto()
3500        FLOAT = auto()
3501        GEOGRAPHY = auto()
3502        GEOMETRY = auto()
3503        HLLSKETCH = auto()
3504        HSTORE = auto()
3505        IMAGE = auto()
3506        INET = auto()
3507        INT = auto()
3508        INT128 = auto()
3509        INT256 = auto()
3510        INT4MULTIRANGE = auto()
3511        INT4RANGE = auto()
3512        INT8MULTIRANGE = auto()
3513        INT8RANGE = auto()
3514        INTERVAL = auto()
3515        IPADDRESS = auto()
3516        IPPREFIX = auto()
3517        JSON = auto()
3518        JSONB = auto()
3519        LONGBLOB = auto()
3520        LONGTEXT = auto()
3521        LOWCARDINALITY = auto()
3522        MAP = auto()
3523        MEDIUMBLOB = auto()
3524        MEDIUMINT = auto()
3525        MEDIUMTEXT = auto()
3526        MONEY = auto()
3527        NCHAR = auto()
3528        NESTED = auto()
3529        NULL = auto()
3530        NULLABLE = auto()
3531        NUMMULTIRANGE = auto()
3532        NUMRANGE = auto()
3533        NVARCHAR = auto()
3534        OBJECT = auto()
3535        ROWVERSION = auto()
3536        SERIAL = auto()
3537        SET = auto()
3538        SMALLINT = auto()
3539        SMALLMONEY = auto()
3540        SMALLSERIAL = auto()
3541        STRUCT = auto()
3542        SUPER = auto()
3543        TEXT = auto()
3544        TINYBLOB = auto()
3545        TINYTEXT = auto()
3546        TIME = auto()
3547        TIMETZ = auto()
3548        TIMESTAMP = auto()
3549        TIMESTAMPLTZ = auto()
3550        TIMESTAMPTZ = auto()
3551        TINYINT = auto()
3552        TSMULTIRANGE = auto()
3553        TSRANGE = auto()
3554        TSTZMULTIRANGE = auto()
3555        TSTZRANGE = auto()
3556        UBIGINT = auto()
3557        UINT = auto()
3558        UINT128 = auto()
3559        UINT256 = auto()
3560        UMEDIUMINT = auto()
3561        UNIQUEIDENTIFIER = auto()
3562        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3563        USERDEFINED = "USER-DEFINED"
3564        USMALLINT = auto()
3565        UTINYINT = auto()
3566        UUID = auto()
3567        VARBINARY = auto()
3568        VARCHAR = auto()
3569        VARIANT = auto()
3570        XML = auto()
3571        YEAR = auto()
3572
3573    TEXT_TYPES = {
3574        Type.CHAR,
3575        Type.NCHAR,
3576        Type.VARCHAR,
3577        Type.NVARCHAR,
3578        Type.TEXT,
3579    }
3580
3581    INTEGER_TYPES = {
3582        Type.INT,
3583        Type.TINYINT,
3584        Type.SMALLINT,
3585        Type.BIGINT,
3586        Type.INT128,
3587        Type.INT256,
3588    }
3589
3590    FLOAT_TYPES = {
3591        Type.FLOAT,
3592        Type.DOUBLE,
3593    }
3594
3595    NUMERIC_TYPES = {
3596        *INTEGER_TYPES,
3597        *FLOAT_TYPES,
3598    }
3599
3600    TEMPORAL_TYPES = {
3601        Type.TIME,
3602        Type.TIMETZ,
3603        Type.TIMESTAMP,
3604        Type.TIMESTAMPTZ,
3605        Type.TIMESTAMPLTZ,
3606        Type.DATE,
3607        Type.DATETIME,
3608        Type.DATETIME64,
3609    }
3610
3611    @classmethod
3612    def build(
3613        cls,
3614        dtype: str | DataType | DataType.Type,
3615        dialect: DialectType = None,
3616        udt: bool = False,
3617        **kwargs,
3618    ) -> DataType:
3619        """
3620        Constructs a DataType object.
3621
3622        Args:
3623            dtype: the data type of interest.
3624            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3625            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3626                DataType, thus creating a user-defined type.
3627            kawrgs: additional arguments to pass in the constructor of DataType.
3628
3629        Returns:
3630            The constructed DataType object.
3631        """
3632        from sqlglot import parse_one
3633
3634        if isinstance(dtype, str):
3635            if dtype.upper() == "UNKNOWN":
3636                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3637
3638            try:
3639                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3640            except ParseError:
3641                if udt:
3642                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3643                raise
3644        elif isinstance(dtype, DataType.Type):
3645            data_type_exp = DataType(this=dtype)
3646        elif isinstance(dtype, DataType):
3647            return dtype
3648        else:
3649            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3650
3651        return DataType(**{**data_type_exp.args, **kwargs})
3652
3653    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3654        """
3655        Checks whether this DataType matches one of the provided data types. Nested types or precision
3656        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3657
3658        Args:
3659            dtypes: the data types to compare this DataType to.
3660
3661        Returns:
3662            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3663        """
3664        for dtype in dtypes:
3665            other = DataType.build(dtype, udt=True)
3666
3667            if (
3668                other.expressions
3669                or self.this == DataType.Type.USERDEFINED
3670                or other.this == DataType.Type.USERDEFINED
3671            ):
3672                matches = self == other
3673            else:
3674                matches = self.this == other.this
3675
3676            if matches:
3677                return True
3678        return False
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False, 'kind': False}
TEXT_TYPES = {<Type.CHAR: 'CHAR'>, <Type.TEXT: 'TEXT'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>}
INTEGER_TYPES = {<Type.TINYINT: 'TINYINT'>, <Type.BIGINT: 'BIGINT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT256: 'INT256'>, <Type.INT128: 'INT128'>, <Type.INT: 'INT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.TINYINT: 'TINYINT'>, <Type.INT256: 'INT256'>, <Type.BIGINT: 'BIGINT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>, <Type.INT128: 'INT128'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT: 'INT'>}
TEMPORAL_TYPES = {<Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATETIME: 'DATETIME'>, <Type.TIMETZ: 'TIMETZ'>, <Type.DATETIME64: 'DATETIME64'>, <Type.TIME: 'TIME'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <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:
3611    @classmethod
3612    def build(
3613        cls,
3614        dtype: str | DataType | DataType.Type,
3615        dialect: DialectType = None,
3616        udt: bool = False,
3617        **kwargs,
3618    ) -> DataType:
3619        """
3620        Constructs a DataType object.
3621
3622        Args:
3623            dtype: the data type of interest.
3624            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3625            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3626                DataType, thus creating a user-defined type.
3627            kawrgs: additional arguments to pass in the constructor of DataType.
3628
3629        Returns:
3630            The constructed DataType object.
3631        """
3632        from sqlglot import parse_one
3633
3634        if isinstance(dtype, str):
3635            if dtype.upper() == "UNKNOWN":
3636                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3637
3638            try:
3639                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3640            except ParseError:
3641                if udt:
3642                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3643                raise
3644        elif isinstance(dtype, DataType.Type):
3645            data_type_exp = DataType(this=dtype)
3646        elif isinstance(dtype, DataType):
3647            return dtype
3648        else:
3649            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3650
3651        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:
3653    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3654        """
3655        Checks whether this DataType matches one of the provided data types. Nested types or precision
3656        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3657
3658        Args:
3659            dtypes: the data types to compare this DataType to.
3660
3661        Returns:
3662            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3663        """
3664        for dtype in dtypes:
3665            other = DataType.build(dtype, udt=True)
3666
3667            if (
3668                other.expressions
3669                or self.this == DataType.Type.USERDEFINED
3670                or other.this == DataType.Type.USERDEFINED
3671            ):
3672                matches = self == other
3673            else:
3674                matches = self.this == other.this
3675
3676            if matches:
3677                return True
3678        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):
3480    class Type(AutoName):
3481        ARRAY = auto()
3482        BIGDECIMAL = auto()
3483        BIGINT = auto()
3484        BIGSERIAL = auto()
3485        BINARY = auto()
3486        BIT = auto()
3487        BOOLEAN = auto()
3488        CHAR = auto()
3489        DATE = auto()
3490        DATEMULTIRANGE = auto()
3491        DATERANGE = auto()
3492        DATETIME = auto()
3493        DATETIME64 = auto()
3494        DECIMAL = auto()
3495        DOUBLE = auto()
3496        ENUM = auto()
3497        ENUM8 = auto()
3498        ENUM16 = auto()
3499        FIXEDSTRING = auto()
3500        FLOAT = auto()
3501        GEOGRAPHY = auto()
3502        GEOMETRY = auto()
3503        HLLSKETCH = auto()
3504        HSTORE = auto()
3505        IMAGE = auto()
3506        INET = auto()
3507        INT = auto()
3508        INT128 = auto()
3509        INT256 = auto()
3510        INT4MULTIRANGE = auto()
3511        INT4RANGE = auto()
3512        INT8MULTIRANGE = auto()
3513        INT8RANGE = auto()
3514        INTERVAL = auto()
3515        IPADDRESS = auto()
3516        IPPREFIX = auto()
3517        JSON = auto()
3518        JSONB = auto()
3519        LONGBLOB = auto()
3520        LONGTEXT = auto()
3521        LOWCARDINALITY = auto()
3522        MAP = auto()
3523        MEDIUMBLOB = auto()
3524        MEDIUMINT = auto()
3525        MEDIUMTEXT = auto()
3526        MONEY = auto()
3527        NCHAR = auto()
3528        NESTED = auto()
3529        NULL = auto()
3530        NULLABLE = auto()
3531        NUMMULTIRANGE = auto()
3532        NUMRANGE = auto()
3533        NVARCHAR = auto()
3534        OBJECT = auto()
3535        ROWVERSION = auto()
3536        SERIAL = auto()
3537        SET = auto()
3538        SMALLINT = auto()
3539        SMALLMONEY = auto()
3540        SMALLSERIAL = auto()
3541        STRUCT = auto()
3542        SUPER = auto()
3543        TEXT = auto()
3544        TINYBLOB = auto()
3545        TINYTEXT = auto()
3546        TIME = auto()
3547        TIMETZ = auto()
3548        TIMESTAMP = auto()
3549        TIMESTAMPLTZ = auto()
3550        TIMESTAMPTZ = auto()
3551        TINYINT = auto()
3552        TSMULTIRANGE = auto()
3553        TSRANGE = auto()
3554        TSTZMULTIRANGE = auto()
3555        TSTZRANGE = auto()
3556        UBIGINT = auto()
3557        UINT = auto()
3558        UINT128 = auto()
3559        UINT256 = auto()
3560        UMEDIUMINT = auto()
3561        UNIQUEIDENTIFIER = auto()
3562        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3563        USERDEFINED = "USER-DEFINED"
3564        USMALLINT = auto()
3565        UTINYINT = auto()
3566        UUID = auto()
3567        VARBINARY = auto()
3568        VARCHAR = auto()
3569        VARIANT = auto()
3570        XML = auto()
3571        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):
3682class PseudoType(Expression):
3683    pass
key = 'pseudotype'
class ObjectIdentifier(Expression):
3687class ObjectIdentifier(Expression):
3688    pass
key = 'objectidentifier'
class SubqueryPredicate(Predicate):
3692class SubqueryPredicate(Predicate):
3693    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3696class All(SubqueryPredicate):
3697    pass
key = 'all'
class Any(SubqueryPredicate):
3700class Any(SubqueryPredicate):
3701    pass
key = 'any'
class Exists(SubqueryPredicate):
3704class Exists(SubqueryPredicate):
3705    pass
key = 'exists'
class Command(Expression):
3710class Command(Expression):
3711    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3714class Transaction(Expression):
3715    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3718class Commit(Expression):
3719    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3722class Rollback(Expression):
3723    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3726class AlterTable(Expression):
3727    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):
3730class AddConstraint(Expression):
3731    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3734class DropPartition(Expression):
3735    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3739class Binary(Condition):
3740    arg_types = {"this": True, "expression": True}
3741
3742    @property
3743    def left(self):
3744        return self.this
3745
3746    @property
3747    def right(self):
3748        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3751class Add(Binary):
3752    pass
key = 'add'
class Connector(Binary):
3755class Connector(Binary):
3756    pass
key = 'connector'
class And(Connector):
3759class And(Connector):
3760    pass
key = 'and'
class Or(Connector):
3763class Or(Connector):
3764    pass
key = 'or'
class BitwiseAnd(Binary):
3767class BitwiseAnd(Binary):
3768    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3771class BitwiseLeftShift(Binary):
3772    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3775class BitwiseOr(Binary):
3776    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3779class BitwiseRightShift(Binary):
3780    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3783class BitwiseXor(Binary):
3784    pass
key = 'bitwisexor'
class Div(Binary):
3787class Div(Binary):
3788    pass
key = 'div'
class Overlaps(Binary):
3791class Overlaps(Binary):
3792    pass
key = 'overlaps'
class Dot(Binary):
3795class Dot(Binary):
3796    @property
3797    def name(self) -> str:
3798        return self.expression.name
3799
3800    @property
3801    def output_name(self) -> str:
3802        return self.name
3803
3804    @classmethod
3805    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3806        """Build a Dot object with a sequence of expressions."""
3807        if len(expressions) < 2:
3808            raise ValueError(f"Dot requires >= 2 expressions.")
3809
3810        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:
3804    @classmethod
3805    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3806        """Build a Dot object with a sequence of expressions."""
3807        if len(expressions) < 2:
3808            raise ValueError(f"Dot requires >= 2 expressions.")
3809
3810        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):
3813class DPipe(Binary):
3814    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3817class SafeDPipe(DPipe):
3818    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3821class EQ(Binary, Predicate):
3822    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3825class NullSafeEQ(Binary, Predicate):
3826    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3829class NullSafeNEQ(Binary, Predicate):
3830    pass
key = 'nullsafeneq'
class Distance(Binary):
3833class Distance(Binary):
3834    pass
key = 'distance'
class Escape(Binary):
3837class Escape(Binary):
3838    pass
key = 'escape'
class Glob(Binary, Predicate):
3841class Glob(Binary, Predicate):
3842    pass
key = 'glob'
class GT(Binary, Predicate):
3845class GT(Binary, Predicate):
3846    pass
key = 'gt'
class GTE(Binary, Predicate):
3849class GTE(Binary, Predicate):
3850    pass
key = 'gte'
class ILike(Binary, Predicate):
3853class ILike(Binary, Predicate):
3854    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3857class ILikeAny(Binary, Predicate):
3858    pass
key = 'ilikeany'
class IntDiv(Binary):
3861class IntDiv(Binary):
3862    pass
key = 'intdiv'
class Is(Binary, Predicate):
3865class Is(Binary, Predicate):
3866    pass
key = 'is'
class Kwarg(Binary):
3869class Kwarg(Binary):
3870    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3873class Like(Binary, Predicate):
3874    pass
key = 'like'
class LikeAny(Binary, Predicate):
3877class LikeAny(Binary, Predicate):
3878    pass
key = 'likeany'
class LT(Binary, Predicate):
3881class LT(Binary, Predicate):
3882    pass
key = 'lt'
class LTE(Binary, Predicate):
3885class LTE(Binary, Predicate):
3886    pass
key = 'lte'
class Mod(Binary):
3889class Mod(Binary):
3890    pass
key = 'mod'
class Mul(Binary):
3893class Mul(Binary):
3894    pass
key = 'mul'
class NEQ(Binary, Predicate):
3897class NEQ(Binary, Predicate):
3898    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3901class SimilarTo(Binary, Predicate):
3902    pass
key = 'similarto'
class Slice(Binary):
3905class Slice(Binary):
3906    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3909class Sub(Binary):
3910    pass
key = 'sub'
class ArrayOverlaps(Binary):
3913class ArrayOverlaps(Binary):
3914    pass
key = 'arrayoverlaps'
class Unary(Condition):
3919class Unary(Condition):
3920    pass
key = 'unary'
class BitwiseNot(Unary):
3923class BitwiseNot(Unary):
3924    pass
key = 'bitwisenot'
class Not(Unary):
3927class Not(Unary):
3928    pass
key = 'not'
class Paren(Unary):
3931class Paren(Unary):
3932    arg_types = {"this": True, "with": False}
3933
3934    @property
3935    def output_name(self) -> str:
3936        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):
3939class Neg(Unary):
3940    pass
key = 'neg'
class Alias(Expression):
3943class Alias(Expression):
3944    arg_types = {"this": True, "alias": False}
3945
3946    @property
3947    def output_name(self) -> str:
3948        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):
3951class Aliases(Expression):
3952    arg_types = {"this": True, "expressions": True}
3953
3954    @property
3955    def aliases(self):
3956        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3959class AtTimeZone(Expression):
3960    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3963class Between(Predicate):
3964    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3967class Bracket(Condition):
3968    arg_types = {"this": True, "expressions": True}
3969
3970    @property
3971    def output_name(self) -> str:
3972        if len(self.expressions) == 1:
3973            return self.expressions[0].output_name
3974
3975        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):
3978class SafeBracket(Bracket):
3979    """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):
3982class Distinct(Expression):
3983    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3986class In(Predicate):
3987    arg_types = {
3988        "this": True,
3989        "expressions": False,
3990        "query": False,
3991        "unnest": False,
3992        "field": False,
3993        "is_global": False,
3994    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3997class TimeUnit(Expression):
3998    """Automatically converts unit arg into a var."""
3999
4000    arg_types = {"unit": False}
4001
4002    def __init__(self, **args):
4003        unit = args.get("unit")
4004        if isinstance(unit, (Column, Literal)):
4005            args["unit"] = Var(this=unit.name)
4006        elif isinstance(unit, Week):
4007            unit.set("this", Var(this=unit.this.name))
4008
4009        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
4002    def __init__(self, **args):
4003        unit = args.get("unit")
4004        if isinstance(unit, (Column, Literal)):
4005            args["unit"] = Var(this=unit.name)
4006        elif isinstance(unit, Week):
4007            unit.set("this", Var(this=unit.this.name))
4008
4009        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class IntervalSpan(Expression):
4015class IntervalSpan(Expression):
4016    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'intervalspan'
class Interval(TimeUnit):
4019class Interval(TimeUnit):
4020    arg_types = {"this": False, "unit": False}
4021
4022    @property
4023    def unit(self) -> t.Optional[Var]:
4024        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[Var]
key = 'interval'
class IgnoreNulls(Expression):
4027class IgnoreNulls(Expression):
4028    pass
key = 'ignorenulls'
class RespectNulls(Expression):
4031class RespectNulls(Expression):
4032    pass
key = 'respectnulls'
class Func(Condition):
4036class Func(Condition):
4037    """
4038    The base class for all function expressions.
4039
4040    Attributes:
4041        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
4042            treated as a variable length argument and the argument's value will be stored as a list.
4043        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
4044            for this function expression. These values are used to map this node to a name during parsing
4045            as well as to provide the function's name during SQL string generation. By default the SQL
4046            name is set to the expression's class name transformed to snake case.
4047    """
4048
4049    is_var_len_args = False
4050
4051    @classmethod
4052    def from_arg_list(cls, args):
4053        if cls.is_var_len_args:
4054            all_arg_keys = list(cls.arg_types)
4055            # If this function supports variable length argument treat the last argument as such.
4056            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4057            num_non_var = len(non_var_len_arg_keys)
4058
4059            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4060            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4061        else:
4062            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4063
4064        return cls(**args_dict)
4065
4066    @classmethod
4067    def sql_names(cls):
4068        if cls is Func:
4069            raise NotImplementedError(
4070                "SQL name is only supported by concrete function implementations"
4071            )
4072        if "_sql_names" not in cls.__dict__:
4073            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4074        return cls._sql_names
4075
4076    @classmethod
4077    def sql_name(cls):
4078        return cls.sql_names()[0]
4079
4080    @classmethod
4081    def default_parser_mappings(cls):
4082        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):
4051    @classmethod
4052    def from_arg_list(cls, args):
4053        if cls.is_var_len_args:
4054            all_arg_keys = list(cls.arg_types)
4055            # If this function supports variable length argument treat the last argument as such.
4056            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4057            num_non_var = len(non_var_len_arg_keys)
4058
4059            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4060            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4061        else:
4062            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4063
4064        return cls(**args_dict)
@classmethod
def sql_names(cls):
4066    @classmethod
4067    def sql_names(cls):
4068        if cls is Func:
4069            raise NotImplementedError(
4070                "SQL name is only supported by concrete function implementations"
4071            )
4072        if "_sql_names" not in cls.__dict__:
4073            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4074        return cls._sql_names
@classmethod
def sql_name(cls):
4076    @classmethod
4077    def sql_name(cls):
4078        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
4080    @classmethod
4081    def default_parser_mappings(cls):
4082        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
4085class AggFunc(Func):
4086    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
4089class ParameterizedAgg(AggFunc):
4090    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
4093class Abs(Func):
4094    pass
key = 'abs'
class Transform(Func):
4098class Transform(Func):
4099    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
4102class Anonymous(Func):
4103    arg_types = {"this": True, "expressions": False}
4104    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
4109class Hll(AggFunc):
4110    arg_types = {"this": True, "expressions": False}
4111    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
4114class ApproxDistinct(AggFunc):
4115    arg_types = {"this": True, "accuracy": False}
4116    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
4119class Array(Func):
4120    arg_types = {"expressions": False}
4121    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
4125class ToChar(Func):
4126    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
4129class GenerateSeries(Func):
4130    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
4133class ArrayAgg(AggFunc):
4134    pass
key = 'arrayagg'
class ArrayAll(Func):
4137class ArrayAll(Func):
4138    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4141class ArrayAny(Func):
4142    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4145class ArrayConcat(Func):
4146    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4147    arg_types = {"this": True, "expressions": False}
4148    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4151class ArrayContains(Binary, Func):
4152    pass
key = 'arraycontains'
class ArrayContained(Binary):
4155class ArrayContained(Binary):
4156    pass
key = 'arraycontained'
class ArrayFilter(Func):
4159class ArrayFilter(Func):
4160    arg_types = {"this": True, "expression": True}
4161    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4164class ArrayJoin(Func):
4165    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4168class ArraySize(Func):
4169    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4172class ArraySort(Func):
4173    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4176class ArraySum(Func):
4177    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4180class ArrayUnionAgg(AggFunc):
4181    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4184class Avg(AggFunc):
4185    pass
key = 'avg'
class AnyValue(AggFunc):
4188class AnyValue(AggFunc):
4189    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):
4192class First(Func):
4193    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4196class Last(Func):
4197    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4200class Case(Func):
4201    arg_types = {"this": False, "ifs": True, "default": False}
4202
4203    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4204        instance = maybe_copy(self, copy)
4205        instance.append(
4206            "ifs",
4207            If(
4208                this=maybe_parse(condition, copy=copy, **opts),
4209                true=maybe_parse(then, copy=copy, **opts),
4210            ),
4211        )
4212        return instance
4213
4214    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4215        instance = maybe_copy(self, copy)
4216        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4217        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:
4203    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4204        instance = maybe_copy(self, copy)
4205        instance.append(
4206            "ifs",
4207            If(
4208                this=maybe_parse(condition, copy=copy, **opts),
4209                true=maybe_parse(then, copy=copy, **opts),
4210            ),
4211        )
4212        return instance
def else_( self, condition: Union[str, Expression], copy: bool = True, **opts) -> Case:
4214    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4215        instance = maybe_copy(self, copy)
4216        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4217        return instance
key = 'case'
class Cast(Func):
4220class Cast(Func):
4221    arg_types = {"this": True, "to": True, "format": False}
4222
4223    @property
4224    def name(self) -> str:
4225        return self.this.name
4226
4227    @property
4228    def to(self) -> DataType:
4229        return self.args["to"]
4230
4231    @property
4232    def output_name(self) -> str:
4233        return self.name
4234
4235    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4236        """
4237        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4238        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4239        array<int> != array<float>.
4240
4241        Args:
4242            dtypes: the data types to compare this Cast's DataType to.
4243
4244        Returns:
4245            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4246        """
4247        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:
4235    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4236        """
4237        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4238        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4239        array<int> != array<float>.
4240
4241        Args:
4242            dtypes: the data types to compare this Cast's DataType to.
4243
4244        Returns:
4245            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4246        """
4247        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):
4250class TryCast(Cast):
4251    pass
key = 'trycast'
class CastToStrType(Func):
4254class CastToStrType(Func):
4255    arg_types = {"this": True, "to": True}
arg_types = {'this': True, 'to': True}
key = 'casttostrtype'
class Collate(Binary):
4258class Collate(Binary):
4259    pass
key = 'collate'
class Ceil(Func):
4262class Ceil(Func):
4263    arg_types = {"this": True, "decimals": False}
4264    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4267class Coalesce(Func):
4268    arg_types = {"this": True, "expressions": False}
4269    is_var_len_args = True
4270    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4273class Concat(Func):
4274    arg_types = {"expressions": True}
4275    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4278class SafeConcat(Concat):
4279    pass
key = 'safeconcat'
class ConcatWs(Concat):
4282class ConcatWs(Concat):
4283    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4286class Count(AggFunc):
4287    arg_types = {"this": False, "expressions": False}
4288    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4291class CountIf(AggFunc):
4292    pass
key = 'countif'
class CurrentDate(Func):
4295class CurrentDate(Func):
4296    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4299class CurrentDatetime(Func):
4300    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4303class CurrentTime(Func):
4304    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4307class CurrentTimestamp(Func):
4308    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4311class CurrentUser(Func):
4312    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4315class DateAdd(Func, TimeUnit):
4316    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4319class DateSub(Func, TimeUnit):
4320    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4323class DateDiff(Func, TimeUnit):
4324    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4325    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4328class DateTrunc(Func):
4329    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4332class DatetimeAdd(Func, TimeUnit):
4333    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4336class DatetimeSub(Func, TimeUnit):
4337    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4340class DatetimeDiff(Func, TimeUnit):
4341    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4344class DatetimeTrunc(Func, TimeUnit):
4345    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4348class DayOfWeek(Func):
4349    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4352class DayOfMonth(Func):
4353    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4356class DayOfYear(Func):
4357    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4360class WeekOfYear(Func):
4361    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4364class MonthsBetween(Func):
4365    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4368class LastDateOfMonth(Func):
4369    pass
key = 'lastdateofmonth'
class Extract(Func):
4372class Extract(Func):
4373    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4376class TimestampAdd(Func, TimeUnit):
4377    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4380class TimestampSub(Func, TimeUnit):
4381    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4384class TimestampDiff(Func, TimeUnit):
4385    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4388class TimestampTrunc(Func, TimeUnit):
4389    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4392class TimeAdd(Func, TimeUnit):
4393    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4396class TimeSub(Func, TimeUnit):
4397    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4400class TimeDiff(Func, TimeUnit):
4401    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4404class TimeTrunc(Func, TimeUnit):
4405    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4408class DateFromParts(Func):
4409    _sql_names = ["DATEFROMPARTS"]
4410    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4413class DateStrToDate(Func):
4414    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4417class DateToDateStr(Func):
4418    pass
key = 'datetodatestr'
class DateToDi(Func):
4421class DateToDi(Func):
4422    pass
key = 'datetodi'
class Date(Func):
4426class Date(Func):
4427    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4430class Day(Func):
4431    pass
key = 'day'
class Decode(Func):
4434class Decode(Func):
4435    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4438class DiToDate(Func):
4439    pass
key = 'ditodate'
class Encode(Func):
4442class Encode(Func):
4443    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4446class Exp(Func):
4447    pass
key = 'exp'
class Explode(Func):
4450class Explode(Func):
4451    pass
key = 'explode'
class Floor(Func):
4454class Floor(Func):
4455    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4458class FromBase64(Func):
4459    pass
key = 'frombase64'
class ToBase64(Func):
4462class ToBase64(Func):
4463    pass
key = 'tobase64'
class Greatest(Func):
4466class Greatest(Func):
4467    arg_types = {"this": True, "expressions": False}
4468    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(AggFunc):
4471class GroupConcat(AggFunc):
4472    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4475class Hex(Func):
4476    pass
key = 'hex'
class Xor(Connector, Func):
4479class Xor(Connector, Func):
4480    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4483class If(Func):
4484    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4487class Initcap(Func):
4488    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4491class IsNan(Func):
4492    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class FormatJson(Expression):
4495class FormatJson(Expression):
4496    pass
key = 'formatjson'
class JSONKeyValue(Expression):
4499class JSONKeyValue(Expression):
4500    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4503class JSONObject(Func):
4504    arg_types = {
4505        "expressions": False,
4506        "null_handling": False,
4507        "unique_keys": False,
4508        "return_type": False,
4509        "encoding": False,
4510    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'encoding': False}
key = 'jsonobject'
class JSONArray(Func):
4514class JSONArray(Func):
4515    arg_types = {
4516        "expressions": True,
4517        "null_handling": False,
4518        "return_type": False,
4519        "strict": False,
4520    }
arg_types = {'expressions': True, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarray'
class JSONArrayAgg(Func):
4524class JSONArrayAgg(Func):
4525    arg_types = {
4526        "this": True,
4527        "order": False,
4528        "null_handling": False,
4529        "return_type": False,
4530        "strict": False,
4531    }
arg_types = {'this': True, 'order': False, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarrayagg'
class JSONColumnDef(Expression):
4536class JSONColumnDef(Expression):
4537    arg_types = {"this": True, "kind": False, "path": False}
arg_types = {'this': True, 'kind': False, 'path': False}
key = 'jsoncolumndef'
class JSONTable(Func):
4541class JSONTable(Func):
4542    arg_types = {
4543        "this": True,
4544        "expressions": True,
4545        "path": False,
4546        "error_handling": False,
4547        "empty_handling": False,
4548    }
arg_types = {'this': True, 'expressions': True, 'path': False, 'error_handling': False, 'empty_handling': False}
key = 'jsontable'
class OpenJSONColumnDef(Expression):
4551class OpenJSONColumnDef(Expression):
4552    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):
4555class OpenJSON(Func):
4556    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4559class JSONBContains(Binary):
4560    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4563class JSONExtract(Binary, Func):
4564    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4567class JSONExtractScalar(JSONExtract):
4568    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4571class JSONBExtract(JSONExtract):
4572    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4575class JSONBExtractScalar(JSONExtract):
4576    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4579class JSONFormat(Func):
4580    arg_types = {"this": False, "options": False}
4581    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4585class JSONArrayContains(Binary, Predicate, Func):
4586    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4589class Least(Func):
4590    arg_types = {"this": True, "expressions": False}
4591    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4594class Left(Func):
4595    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4602class Length(Func):
4603    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4606class Levenshtein(Func):
4607    arg_types = {
4608        "this": True,
4609        "expression": False,
4610        "ins_cost": False,
4611        "del_cost": False,
4612        "sub_cost": False,
4613    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4616class Ln(Func):
4617    pass
key = 'ln'
class Log(Func):
4620class Log(Func):
4621    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4624class Log2(Func):
4625    pass
key = 'log2'
class Log10(Func):
4628class Log10(Func):
4629    pass
key = 'log10'
class LogicalOr(AggFunc):
4632class LogicalOr(AggFunc):
4633    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4636class LogicalAnd(AggFunc):
4637    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4640class Lower(Func):
4641    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4644class Map(Func):
4645    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4648class MapFromEntries(Func):
4649    pass
key = 'mapfromentries'
class StarMap(Func):
4652class StarMap(Func):
4653    pass
key = 'starmap'
class VarMap(Func):
4656class VarMap(Func):
4657    arg_types = {"keys": True, "values": True}
4658    is_var_len_args = True
4659
4660    @property
4661    def keys(self) -> t.List[Expression]:
4662        return self.args["keys"].expressions
4663
4664    @property
4665    def values(self) -> t.List[Expression]:
4666        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):
4670class MatchAgainst(Func):
4671    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4674class Max(AggFunc):
4675    arg_types = {"this": True, "expressions": False}
4676    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4679class MD5(Func):
4680    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4684class MD5Digest(Func):
4685    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4688class Min(AggFunc):
4689    arg_types = {"this": True, "expressions": False}
4690    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4693class Month(Func):
4694    pass
key = 'month'
class Nvl2(Func):
4697class Nvl2(Func):
4698    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4701class Posexplode(Func):
4702    pass
key = 'posexplode'
class Pow(Binary, Func):
4705class Pow(Binary, Func):
4706    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4709class PercentileCont(AggFunc):
4710    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4713class PercentileDisc(AggFunc):
4714    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4717class Quantile(AggFunc):
4718    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4721class ApproxQuantile(Quantile):
4722    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):
4725class RangeN(Func):
4726    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4729class ReadCSV(Func):
4730    _sql_names = ["READ_CSV"]
4731    is_var_len_args = True
4732    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4735class Reduce(Func):
4736    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):
4739class RegexpExtract(Func):
4740    arg_types = {
4741        "this": True,
4742        "expression": True,
4743        "position": False,
4744        "occurrence": False,
4745        "parameters": False,
4746        "group": False,
4747    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4750class RegexpReplace(Func):
4751    arg_types = {
4752        "this": True,
4753        "expression": True,
4754        "replacement": True,
4755        "position": False,
4756        "occurrence": False,
4757        "parameters": False,
4758    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4761class RegexpLike(Binary, Func):
4762    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4765class RegexpILike(Func):
4766    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4771class RegexpSplit(Func):
4772    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4775class Repeat(Func):
4776    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4779class Round(Func):
4780    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4783class RowNumber(Func):
4784    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4787class SafeDivide(Func):
4788    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4791class SetAgg(AggFunc):
4792    pass
key = 'setagg'
class SHA(Func):
4795class SHA(Func):
4796    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4799class SHA2(Func):
4800    _sql_names = ["SHA2"]
4801    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4804class SortArray(Func):
4805    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4808class Split(Func):
4809    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4814class Substring(Func):
4815    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4818class StandardHash(Func):
4819    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4822class StartsWith(Func):
4823    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4824    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4827class StrPosition(Func):
4828    arg_types = {
4829        "this": True,
4830        "substr": True,
4831        "position": False,
4832        "instance": False,
4833    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4836class StrToDate(Func):
4837    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4840class StrToTime(Func):
4841    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4846class StrToUnix(Func):
4847    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
4852class StrToMap(Func):
4853    arg_types = {
4854        "this": True,
4855        "pair_delim": False,
4856        "key_value_delim": False,
4857        "duplicate_resolution_callback": False,
4858    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
4861class NumberToStr(Func):
4862    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
4865class FromBase(Func):
4866    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4869class Struct(Func):
4870    arg_types = {"expressions": True}
4871    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4874class StructExtract(Func):
4875    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Stuff(Func):
4880class Stuff(Func):
4881    _sql_names = ["STUFF", "INSERT"]
4882    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):
4885class Sum(AggFunc):
4886    pass
key = 'sum'
class Sqrt(Func):
4889class Sqrt(Func):
4890    pass
key = 'sqrt'
class Stddev(AggFunc):
4893class Stddev(AggFunc):
4894    pass
key = 'stddev'
class StddevPop(AggFunc):
4897class StddevPop(AggFunc):
4898    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4901class StddevSamp(AggFunc):
4902    pass
key = 'stddevsamp'
class TimeToStr(Func):
4905class TimeToStr(Func):
4906    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
4909class TimeToTimeStr(Func):
4910    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4913class TimeToUnix(Func):
4914    pass
key = 'timetounix'
class TimeStrToDate(Func):
4917class TimeStrToDate(Func):
4918    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4921class TimeStrToTime(Func):
4922    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4925class TimeStrToUnix(Func):
4926    pass
key = 'timestrtounix'
class Trim(Func):
4929class Trim(Func):
4930    arg_types = {
4931        "this": True,
4932        "expression": False,
4933        "position": False,
4934        "collation": False,
4935    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4938class TsOrDsAdd(Func, TimeUnit):
4939    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4942class TsOrDsToDateStr(Func):
4943    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4946class TsOrDsToDate(Func):
4947    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4950class TsOrDiToDi(Func):
4951    pass
key = 'tsorditodi'
class Unhex(Func):
4954class Unhex(Func):
4955    pass
key = 'unhex'
class UnixToStr(Func):
4958class UnixToStr(Func):
4959    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4964class UnixToTime(Func):
4965    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4966
4967    SECONDS = Literal.string("seconds")
4968    MILLIS = Literal.string("millis")
4969    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):
4972class UnixToTimeStr(Func):
4973    pass
key = 'unixtotimestr'
class Upper(Func):
4976class Upper(Func):
4977    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4980class Variance(AggFunc):
4981    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4984class VariancePop(AggFunc):
4985    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4988class Week(Func):
4989    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4992class XMLTable(Func):
4993    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):
4996class Year(Func):
4997    pass
key = 'year'
class Use(Expression):
5000class Use(Expression):
5001    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
5004class Merge(Expression):
5005    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):
5008class When(Func):
5009    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):
5014class NextValueFor(Func):
5015    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:
5052def maybe_parse(
5053    sql_or_expression: ExpOrStr,
5054    *,
5055    into: t.Optional[IntoType] = None,
5056    dialect: DialectType = None,
5057    prefix: t.Optional[str] = None,
5058    copy: bool = False,
5059    **opts,
5060) -> Expression:
5061    """Gracefully handle a possible string or expression.
5062
5063    Example:
5064        >>> maybe_parse("1")
5065        (LITERAL this: 1, is_string: False)
5066        >>> maybe_parse(to_identifier("x"))
5067        (IDENTIFIER this: x, quoted: False)
5068
5069    Args:
5070        sql_or_expression: the SQL code string or an expression
5071        into: the SQLGlot Expression to parse into
5072        dialect: the dialect used to parse the input expressions (in the case that an
5073            input expression is a SQL string).
5074        prefix: a string to prefix the sql with before it gets parsed
5075            (automatically includes a space)
5076        copy: whether or not to copy the expression.
5077        **opts: other options to use to parse the input expressions (again, in the case
5078            that an input expression is a SQL string).
5079
5080    Returns:
5081        Expression: the parsed or given expression.
5082    """
5083    if isinstance(sql_or_expression, Expression):
5084        if copy:
5085            return sql_or_expression.copy()
5086        return sql_or_expression
5087
5088    if sql_or_expression is None:
5089        raise ParseError(f"SQL cannot be None")
5090
5091    import sqlglot
5092
5093    sql = str(sql_or_expression)
5094    if prefix:
5095        sql = f"{prefix} {sql}"
5096
5097    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):
5110def maybe_copy(instance, copy=True):
5111    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:
5291def union(
5292    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5293) -> Union:
5294    """
5295    Initializes a syntax tree from one UNION expression.
5296
5297    Example:
5298        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5299        'SELECT * FROM foo UNION SELECT * FROM bla'
5300
5301    Args:
5302        left: the SQL code string corresponding to the left-hand side.
5303            If an `Expression` instance is passed, it will be used as-is.
5304        right: the SQL code string corresponding to the right-hand side.
5305            If an `Expression` instance is passed, it will be used as-is.
5306        distinct: set the DISTINCT flag if and only if this is true.
5307        dialect: the dialect used to parse the input expression.
5308        opts: other options to use to parse the input expressions.
5309
5310    Returns:
5311        The new Union instance.
5312    """
5313    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5314    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5315
5316    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:
5319def intersect(
5320    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5321) -> Intersect:
5322    """
5323    Initializes a syntax tree from one INTERSECT expression.
5324
5325    Example:
5326        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5327        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5328
5329    Args:
5330        left: the SQL code string corresponding to the left-hand side.
5331            If an `Expression` instance is passed, it will be used as-is.
5332        right: the SQL code string corresponding to the right-hand side.
5333            If an `Expression` instance is passed, it will be used as-is.
5334        distinct: set the DISTINCT flag if and only if this is true.
5335        dialect: the dialect used to parse the input expression.
5336        opts: other options to use to parse the input expressions.
5337
5338    Returns:
5339        The new Intersect instance.
5340    """
5341    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5342    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5343
5344    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:
5347def except_(
5348    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5349) -> Except:
5350    """
5351    Initializes a syntax tree from one EXCEPT expression.
5352
5353    Example:
5354        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5355        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5356
5357    Args:
5358        left: the SQL code string corresponding to the left-hand side.
5359            If an `Expression` instance is passed, it will be used as-is.
5360        right: the SQL code string corresponding to the right-hand side.
5361            If an `Expression` instance is passed, it will be used as-is.
5362        distinct: set the DISTINCT flag if and only if this is true.
5363        dialect: the dialect used to parse the input expression.
5364        opts: other options to use to parse the input expressions.
5365
5366    Returns:
5367        The new Except instance.
5368    """
5369    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5370    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5371
5372    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:
5375def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5376    """
5377    Initializes a syntax tree from one or multiple SELECT expressions.
5378
5379    Example:
5380        >>> select("col1", "col2").from_("tbl").sql()
5381        'SELECT col1, col2 FROM tbl'
5382
5383    Args:
5384        *expressions: the SQL code string to parse as the expressions of a
5385            SELECT statement. If an Expression instance is passed, this is used as-is.
5386        dialect: the dialect used to parse the input expressions (in the case that an
5387            input expression is a SQL string).
5388        **opts: other options to use to parse the input expressions (again, in the case
5389            that an input expression is a SQL string).
5390
5391    Returns:
5392        Select: the syntax tree for the SELECT statement.
5393    """
5394    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:
5397def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5398    """
5399    Initializes a syntax tree from a FROM expression.
5400
5401    Example:
5402        >>> from_("tbl").select("col1", "col2").sql()
5403        'SELECT col1, col2 FROM tbl'
5404
5405    Args:
5406        *expression: the SQL code string to parse as the FROM expressions of a
5407            SELECT statement. If an Expression instance is passed, this is used as-is.
5408        dialect: the dialect used to parse the input expression (in the case that the
5409            input expression is a SQL string).
5410        **opts: other options to use to parse the input expressions (again, in the case
5411            that the input expression is a SQL string).
5412
5413    Returns:
5414        Select: the syntax tree for the SELECT statement.
5415    """
5416    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:
5419def update(
5420    table: str | Table,
5421    properties: dict,
5422    where: t.Optional[ExpOrStr] = None,
5423    from_: t.Optional[ExpOrStr] = None,
5424    dialect: DialectType = None,
5425    **opts,
5426) -> Update:
5427    """
5428    Creates an update statement.
5429
5430    Example:
5431        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5432        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5433
5434    Args:
5435        *properties: dictionary of properties to set which are
5436            auto converted to sql objects eg None -> NULL
5437        where: sql conditional parsed into a WHERE statement
5438        from_: sql statement parsed into a FROM statement
5439        dialect: the dialect used to parse the input expressions.
5440        **opts: other options to use to parse the input expressions.
5441
5442    Returns:
5443        Update: the syntax tree for the UPDATE statement.
5444    """
5445    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5446    update_expr.set(
5447        "expressions",
5448        [
5449            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5450            for k, v in properties.items()
5451        ],
5452    )
5453    if from_:
5454        update_expr.set(
5455            "from",
5456            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5457        )
5458    if isinstance(where, Condition):
5459        where = Where(this=where)
5460    if where:
5461        update_expr.set(
5462            "where",
5463            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5464        )
5465    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:
5468def delete(
5469    table: ExpOrStr,
5470    where: t.Optional[ExpOrStr] = None,
5471    returning: t.Optional[ExpOrStr] = None,
5472    dialect: DialectType = None,
5473    **opts,
5474) -> Delete:
5475    """
5476    Builds a delete statement.
5477
5478    Example:
5479        >>> delete("my_table", where="id > 1").sql()
5480        'DELETE FROM my_table WHERE id > 1'
5481
5482    Args:
5483        where: sql conditional parsed into a WHERE statement
5484        returning: sql conditional parsed into a RETURNING statement
5485        dialect: the dialect used to parse the input expressions.
5486        **opts: other options to use to parse the input expressions.
5487
5488    Returns:
5489        Delete: the syntax tree for the DELETE statement.
5490    """
5491    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5492    if where:
5493        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5494    if returning:
5495        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5496    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:
5499def insert(
5500    expression: ExpOrStr,
5501    into: ExpOrStr,
5502    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5503    overwrite: t.Optional[bool] = None,
5504    dialect: DialectType = None,
5505    copy: bool = True,
5506    **opts,
5507) -> Insert:
5508    """
5509    Builds an INSERT statement.
5510
5511    Example:
5512        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5513        'INSERT INTO tbl VALUES (1, 2, 3)'
5514
5515    Args:
5516        expression: the sql string or expression of the INSERT statement
5517        into: the tbl to insert data to.
5518        columns: optionally the table's column names.
5519        overwrite: whether to INSERT OVERWRITE or not.
5520        dialect: the dialect used to parse the input expressions.
5521        copy: whether or not to copy the expression.
5522        **opts: other options to use to parse the input expressions.
5523
5524    Returns:
5525        Insert: the syntax tree for the INSERT statement.
5526    """
5527    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5528    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5529
5530    if columns:
5531        this = _apply_list_builder(
5532            *columns,
5533            instance=Schema(this=this),
5534            arg="expressions",
5535            into=Identifier,
5536            copy=False,
5537            dialect=dialect,
5538            **opts,
5539        )
5540
5541    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:
5544def condition(
5545    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5546) -> Condition:
5547    """
5548    Initialize a logical condition expression.
5549
5550    Example:
5551        >>> condition("x=1").sql()
5552        'x = 1'
5553
5554        This is helpful for composing larger logical syntax trees:
5555        >>> where = condition("x=1")
5556        >>> where = where.and_("y=1")
5557        >>> Select().from_("tbl").select("*").where(where).sql()
5558        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5559
5560    Args:
5561        *expression: the SQL code string to parse.
5562            If an Expression instance is passed, this is used as-is.
5563        dialect: the dialect used to parse the input expression (in the case that the
5564            input expression is a SQL string).
5565        copy: Whether or not to copy `expression` (only applies to expressions).
5566        **opts: other options to use to parse the input expressions (again, in the case
5567            that the input expression is a SQL string).
5568
5569    Returns:
5570        The new Condition instance
5571    """
5572    return maybe_parse(
5573        expression,
5574        into=Condition,
5575        dialect=dialect,
5576        copy=copy,
5577        **opts,
5578    )

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:
5581def and_(
5582    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5583) -> Condition:
5584    """
5585    Combine multiple conditions with an AND logical operator.
5586
5587    Example:
5588        >>> and_("x=1", and_("y=1", "z=1")).sql()
5589        'x = 1 AND (y = 1 AND z = 1)'
5590
5591    Args:
5592        *expressions: the SQL code strings to parse.
5593            If an Expression instance is passed, this is used as-is.
5594        dialect: the dialect used to parse the input expression.
5595        copy: whether or not to copy `expressions` (only applies to Expressions).
5596        **opts: other options to use to parse the input expressions.
5597
5598    Returns:
5599        And: the new condition
5600    """
5601    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:
5604def or_(
5605    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5606) -> Condition:
5607    """
5608    Combine multiple conditions with an OR logical operator.
5609
5610    Example:
5611        >>> or_("x=1", or_("y=1", "z=1")).sql()
5612        'x = 1 OR (y = 1 OR z = 1)'
5613
5614    Args:
5615        *expressions: the SQL code strings to parse.
5616            If an Expression instance is passed, this is used as-is.
5617        dialect: the dialect used to parse the input expression.
5618        copy: whether or not to copy `expressions` (only applies to Expressions).
5619        **opts: other options to use to parse the input expressions.
5620
5621    Returns:
5622        Or: the new condition
5623    """
5624    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:
5627def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5628    """
5629    Wrap a condition with a NOT operator.
5630
5631    Example:
5632        >>> not_("this_suit='black'").sql()
5633        "NOT this_suit = 'black'"
5634
5635    Args:
5636        expression: the SQL code string to parse.
5637            If an Expression instance is passed, this is used as-is.
5638        dialect: the dialect used to parse the input expression.
5639        copy: whether to copy the expression or not.
5640        **opts: other options to use to parse the input expressions.
5641
5642    Returns:
5643        The new condition.
5644    """
5645    this = condition(
5646        expression,
5647        dialect=dialect,
5648        copy=copy,
5649        **opts,
5650    )
5651    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:
5654def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5655    """
5656    Wrap an expression in parentheses.
5657
5658    Example:
5659        >>> paren("5 + 3").sql()
5660        '(5 + 3)'
5661
5662    Args:
5663        expression: the SQL code string to parse.
5664            If an Expression instance is passed, this is used as-is.
5665        copy: whether to copy the expression or not.
5666
5667    Returns:
5668        The wrapped expression.
5669    """
5670    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):
5688def to_identifier(name, quoted=None, copy=True):
5689    """Builds an identifier.
5690
5691    Args:
5692        name: The name to turn into an identifier.
5693        quoted: Whether or not force quote the identifier.
5694        copy: Whether or not to copy a passed in Identefier node.
5695
5696    Returns:
5697        The identifier ast node.
5698    """
5699
5700    if name is None:
5701        return None
5702
5703    if isinstance(name, Identifier):
5704        identifier = maybe_copy(name, copy)
5705    elif isinstance(name, str):
5706        identifier = Identifier(
5707            this=name,
5708            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5709        )
5710    else:
5711        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5712    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:
5718def to_interval(interval: str | Literal) -> Interval:
5719    """Builds an interval expression from a string like '1 day' or '5 months'."""
5720    if isinstance(interval, Literal):
5721        if not interval.is_string:
5722            raise ValueError("Invalid interval string.")
5723
5724        interval = interval.this
5725
5726    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5727
5728    if not interval_parts:
5729        raise ValueError("Invalid interval string.")
5730
5731    return Interval(
5732        this=Literal.string(interval_parts.group(1)),
5733        unit=Var(this=interval_parts.group(2)),
5734    )

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]:
5747def to_table(
5748    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5749) -> t.Optional[Table]:
5750    """
5751    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5752    If a table is passed in then that table is returned.
5753
5754    Args:
5755        sql_path: a `[catalog].[schema].[table]` string.
5756        dialect: the source dialect according to which the table name will be parsed.
5757        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5758
5759    Returns:
5760        A table expression.
5761    """
5762    if sql_path is None or isinstance(sql_path, Table):
5763        return sql_path
5764    if not isinstance(sql_path, str):
5765        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5766
5767    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5768    if table:
5769        for k, v in kwargs.items():
5770            table.set(k, v)
5771
5772    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:
5775def to_column(sql_path: str | Column, **kwargs) -> Column:
5776    """
5777    Create a column from a `[table].[column]` sql path. Schema is optional.
5778
5779    If a column is passed in then that column is returned.
5780
5781    Args:
5782        sql_path: `[table].[column]` string
5783    Returns:
5784        Table: A column expression
5785    """
5786    if sql_path is None or isinstance(sql_path, Column):
5787        return sql_path
5788    if not isinstance(sql_path, str):
5789        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5790    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):
5793def alias_(
5794    expression: ExpOrStr,
5795    alias: str | Identifier,
5796    table: bool | t.Sequence[str | Identifier] = False,
5797    quoted: t.Optional[bool] = None,
5798    dialect: DialectType = None,
5799    copy: bool = True,
5800    **opts,
5801):
5802    """Create an Alias expression.
5803
5804    Example:
5805        >>> alias_('foo', 'bar').sql()
5806        'foo AS bar'
5807
5808        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5809        '(SELECT 1, 2) AS bar(a, b)'
5810
5811    Args:
5812        expression: the SQL code strings to parse.
5813            If an Expression instance is passed, this is used as-is.
5814        alias: the alias name to use. If the name has
5815            special characters it is quoted.
5816        table: Whether or not to create a table alias, can also be a list of columns.
5817        quoted: whether or not to quote the alias
5818        dialect: the dialect used to parse the input expression.
5819        copy: Whether or not to copy the expression.
5820        **opts: other options to use to parse the input expressions.
5821
5822    Returns:
5823        Alias: the aliased expression
5824    """
5825    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5826    alias = to_identifier(alias, quoted=quoted)
5827
5828    if table:
5829        table_alias = TableAlias(this=alias)
5830        exp.set("alias", table_alias)
5831
5832        if not isinstance(table, bool):
5833            for column in table:
5834                table_alias.append("columns", to_identifier(column, quoted=quoted))
5835
5836        return exp
5837
5838    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5839    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5840    # for the complete Window expression.
5841    #
5842    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5843
5844    if "alias" in exp.arg_types and not isinstance(exp, Window):
5845        exp.set("alias", alias)
5846        return exp
5847    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:
5850def subquery(
5851    expression: ExpOrStr,
5852    alias: t.Optional[Identifier | str] = None,
5853    dialect: DialectType = None,
5854    **opts,
5855) -> Select:
5856    """
5857    Build a subquery expression.
5858
5859    Example:
5860        >>> subquery('select x from tbl', 'bar').select('x').sql()
5861        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5862
5863    Args:
5864        expression: the SQL code strings to parse.
5865            If an Expression instance is passed, this is used as-is.
5866        alias: the alias name to use.
5867        dialect: the dialect used to parse the input expression.
5868        **opts: other options to use to parse the input expressions.
5869
5870    Returns:
5871        A new Select instance with the subquery expression included.
5872    """
5873
5874    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5875    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:
5878def column(
5879    col: str | Identifier,
5880    table: t.Optional[str | Identifier] = None,
5881    db: t.Optional[str | Identifier] = None,
5882    catalog: t.Optional[str | Identifier] = None,
5883    quoted: t.Optional[bool] = None,
5884) -> Column:
5885    """
5886    Build a Column.
5887
5888    Args:
5889        col: Column name.
5890        table: Table name.
5891        db: Database name.
5892        catalog: Catalog name.
5893        quoted: Whether to force quotes on the column's identifiers.
5894
5895    Returns:
5896        The new Column instance.
5897    """
5898    return Column(
5899        this=to_identifier(col, quoted=quoted),
5900        table=to_identifier(table, quoted=quoted),
5901        db=to_identifier(db, quoted=quoted),
5902        catalog=to_identifier(catalog, quoted=quoted),
5903    )

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:
5906def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5907    """Cast an expression to a data type.
5908
5909    Example:
5910        >>> cast('x + 1', 'int').sql()
5911        'CAST(x + 1 AS INT)'
5912
5913    Args:
5914        expression: The expression to cast.
5915        to: The datatype to cast to.
5916
5917    Returns:
5918        The new Cast instance.
5919    """
5920    expression = maybe_parse(expression, **opts)
5921    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:
5924def table_(
5925    table: Identifier | str,
5926    db: t.Optional[Identifier | str] = None,
5927    catalog: t.Optional[Identifier | str] = None,
5928    quoted: t.Optional[bool] = None,
5929    alias: t.Optional[Identifier | str] = None,
5930) -> Table:
5931    """Build a Table.
5932
5933    Args:
5934        table: Table name.
5935        db: Database name.
5936        catalog: Catalog name.
5937        quote: Whether to force quotes on the table's identifiers.
5938        alias: Table's alias.
5939
5940    Returns:
5941        The new Table instance.
5942    """
5943    return Table(
5944        this=to_identifier(table, quoted=quoted) if table else None,
5945        db=to_identifier(db, quoted=quoted) if db else None,
5946        catalog=to_identifier(catalog, quoted=quoted) if catalog else None,
5947        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5948    )

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

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:
5984def var(name: t.Optional[ExpOrStr]) -> Var:
5985    """Build a SQL variable.
5986
5987    Example:
5988        >>> repr(var('x'))
5989        '(VAR this: x)'
5990
5991        >>> repr(var(column('x', table='y')))
5992        '(VAR this: x)'
5993
5994    Args:
5995        name: The name of the var or an expression who's name will become the var.
5996
5997    Returns:
5998        The new variable node.
5999    """
6000    if not name:
6001        raise ValueError("Cannot convert empty name into var.")
6002
6003    if isinstance(name, Expression):
6004        name = name.name
6005    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:
6008def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
6009    """Build ALTER TABLE... RENAME... expression
6010
6011    Args:
6012        old_name: The old name of the table
6013        new_name: The new name of the table
6014
6015    Returns:
6016        Alter table expression
6017    """
6018    old_table = to_table(old_name)
6019    new_table = to_table(new_name)
6020    return AlterTable(
6021        this=old_table,
6022        actions=[
6023            RenameTable(this=new_table),
6024        ],
6025    )

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:
6028def convert(value: t.Any, copy: bool = False) -> Expression:
6029    """Convert a python value into an expression object.
6030
6031    Raises an error if a conversion is not possible.
6032
6033    Args:
6034        value: A python object.
6035        copy: Whether or not to copy `value` (only applies to Expressions and collections).
6036
6037    Returns:
6038        Expression: the equivalent expression object.
6039    """
6040    if isinstance(value, Expression):
6041        return maybe_copy(value, copy)
6042    if isinstance(value, str):
6043        return Literal.string(value)
6044    if isinstance(value, bool):
6045        return Boolean(this=value)
6046    if value is None or (isinstance(value, float) and math.isnan(value)):
6047        return NULL
6048    if isinstance(value, numbers.Number):
6049        return Literal.number(value)
6050    if isinstance(value, datetime.datetime):
6051        datetime_literal = Literal.string(
6052            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
6053        )
6054        return TimeStrToTime(this=datetime_literal)
6055    if isinstance(value, datetime.date):
6056        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
6057        return DateStrToDate(this=date_literal)
6058    if isinstance(value, tuple):
6059        return Tuple(expressions=[convert(v, copy=copy) for v in value])
6060    if isinstance(value, list):
6061        return Array(expressions=[convert(v, copy=copy) for v in value])
6062    if isinstance(value, dict):
6063        return Map(
6064            keys=Array(expressions=[convert(k, copy=copy) for k in value]),
6065            values=Array(expressions=[convert(v, copy=copy) for v in value.values()]),
6066        )
6067    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:
6070def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
6071    """
6072    Replace children of an expression with the result of a lambda fun(child) -> exp.
6073    """
6074    for k, v in expression.args.items():
6075        is_list_arg = type(v) is list
6076
6077        child_nodes = v if is_list_arg else [v]
6078        new_child_nodes = []
6079
6080        for cn in child_nodes:
6081            if isinstance(cn, Expression):
6082                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
6083                    new_child_nodes.append(child_node)
6084                    child_node.parent = expression
6085                    child_node.arg_key = k
6086            else:
6087                new_child_nodes.append(cn)
6088
6089        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]:
6092def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
6093    """
6094    Return all table names referenced through columns in an expression.
6095
6096    Example:
6097        >>> import sqlglot
6098        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
6099        ['a', 'c']
6100
6101    Args:
6102        expression: expression to find table names.
6103        exclude: a table name to exclude
6104
6105    Returns:
6106        A list of unique names.
6107    """
6108    return {
6109        table
6110        for table in (column.table for column in expression.find_all(Column))
6111        if table and table != exclude
6112    }

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:
6115def table_name(table: Table | str, dialect: DialectType = None) -> str:
6116    """Get the full name of a table as a string.
6117
6118    Args:
6119        table: Table expression node or string.
6120        dialect: The dialect to generate the table name for.
6121
6122    Examples:
6123        >>> from sqlglot import exp, parse_one
6124        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
6125        'a.b.c'
6126
6127    Returns:
6128        The table name.
6129    """
6130
6131    table = maybe_parse(table, into=Table)
6132
6133    if not table:
6134        raise ValueError(f"Cannot parse {table}")
6135
6136    return ".".join(
6137        part.sql(dialect=dialect, identify=True)
6138        if not SAFE_IDENTIFIER_RE.match(part.name)
6139        else part.name
6140        for part in table.parts
6141    )

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:
6144def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
6145    """Replace all tables in expression according to the mapping.
6146
6147    Args:
6148        expression: expression node to be transformed and replaced.
6149        mapping: mapping of table names.
6150        copy: whether or not to copy the expression.
6151
6152    Examples:
6153        >>> from sqlglot import exp, parse_one
6154        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
6155        'SELECT * FROM c'
6156
6157    Returns:
6158        The mapped expression.
6159    """
6160
6161    def _replace_tables(node: Expression) -> Expression:
6162        if isinstance(node, Table):
6163            new_name = mapping.get(table_name(node))
6164            if new_name:
6165                return to_table(
6166                    new_name,
6167                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
6168                )
6169        return node
6170
6171    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:
6174def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
6175    """Replace placeholders in an expression.
6176
6177    Args:
6178        expression: expression node to be transformed and replaced.
6179        args: positional names that will substitute unnamed placeholders in the given order.
6180        kwargs: keyword arguments that will substitute named placeholders.
6181
6182    Examples:
6183        >>> from sqlglot import exp, parse_one
6184        >>> replace_placeholders(
6185        ...     parse_one("select * from :tbl where ? = ?"),
6186        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
6187        ... ).sql()
6188        "SELECT * FROM foo WHERE str_col = 'b'"
6189
6190    Returns:
6191        The mapped expression.
6192    """
6193
6194    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
6195        if isinstance(node, Placeholder):
6196            if node.name:
6197                new_name = kwargs.get(node.name)
6198                if new_name:
6199                    return convert(new_name)
6200            else:
6201                try:
6202                    return convert(next(args))
6203                except StopIteration:
6204                    pass
6205        return node
6206
6207    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:
6210def expand(
6211    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
6212) -> Expression:
6213    """Transforms an expression by expanding all referenced sources into subqueries.
6214
6215    Examples:
6216        >>> from sqlglot import parse_one
6217        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
6218        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
6219
6220        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
6221        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
6222
6223    Args:
6224        expression: The expression to expand.
6225        sources: A dictionary of name to Subqueryables.
6226        copy: Whether or not to copy the expression during transformation. Defaults to True.
6227
6228    Returns:
6229        The transformed expression.
6230    """
6231
6232    def _expand(node: Expression):
6233        if isinstance(node, Table):
6234            name = table_name(node)
6235            source = sources.get(name)
6236            if source:
6237                subquery = source.subquery(node.alias or name)
6238                subquery.comments = [f"source: {name}"]
6239                return subquery.transform(_expand, copy=False)
6240        return node
6241
6242    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:
6245def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6246    """
6247    Returns a Func expression.
6248
6249    Examples:
6250        >>> func("abs", 5).sql()
6251        'ABS(5)'
6252
6253        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6254        'CAST(5 AS DOUBLE)'
6255
6256    Args:
6257        name: the name of the function to build.
6258        args: the args used to instantiate the function of interest.
6259        dialect: the source dialect.
6260        kwargs: the kwargs used to instantiate the function of interest.
6261
6262    Note:
6263        The arguments `args` and `kwargs` are mutually exclusive.
6264
6265    Returns:
6266        An instance of the function of interest, or an anonymous function, if `name` doesn't
6267        correspond to an existing `sqlglot.expressions.Func` class.
6268    """
6269    if args and kwargs:
6270        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6271
6272    from sqlglot.dialects.dialect import Dialect
6273
6274    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6275    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6276
6277    parser = Dialect.get_or_raise(dialect)().parser()
6278    from_args_list = parser.FUNCTIONS.get(name.upper())
6279
6280    if from_args_list:
6281        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6282    else:
6283        kwargs = kwargs or {"expressions": converted}
6284        function = Anonymous(this=name, **kwargs)
6285
6286    for error_message in function.error_messages(converted):
6287        raise ValueError(error_message)
6288
6289    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:
6292def true() -> Boolean:
6293    """
6294    Returns a true Boolean expression.
6295    """
6296    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> Boolean:
6299def false() -> Boolean:
6300    """
6301    Returns a false Boolean expression.
6302    """
6303    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> Null:
6306def null() -> Null:
6307    """
6308    Returns a Null expression.
6309    """
6310    return Null()

Returns a Null expression.

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