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

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.

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:
668    def and_(
669        self,
670        *expressions: t.Optional[ExpOrStr],
671        dialect: DialectType = None,
672        copy: bool = True,
673        **opts,
674    ) -> Condition:
675        """
676        AND this condition with one or multiple expressions.
677
678        Example:
679            >>> condition("x=1").and_("y=1").sql()
680            'x = 1 AND y = 1'
681
682        Args:
683            *expressions: the SQL code strings to parse.
684                If an `Expression` instance is passed, it will be used as-is.
685            dialect: the dialect used to parse the input expression.
686            copy: whether or not to copy the involved expressions (only applies to Expressions).
687            opts: other options to use to parse the input expressions.
688
689        Returns:
690            The new And condition.
691        """
692        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:
694    def or_(
695        self,
696        *expressions: t.Optional[ExpOrStr],
697        dialect: DialectType = None,
698        copy: bool = True,
699        **opts,
700    ) -> Condition:
701        """
702        OR this condition with one or multiple expressions.
703
704        Example:
705            >>> condition("x=1").or_("y=1").sql()
706            'x = 1 OR y = 1'
707
708        Args:
709            *expressions: the SQL code strings to parse.
710                If an `Expression` instance is passed, it will be used as-is.
711            dialect: the dialect used to parse the input expression.
712            copy: whether or not to copy the involved expressions (only applies to Expressions).
713            opts: other options to use to parse the input expressions.
714
715        Returns:
716            The new Or condition.
717        """
718        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):
720    def not_(self, copy: bool = True):
721        """
722        Wrap this condition with NOT.
723
724        Example:
725            >>> condition("x=1").not_().sql()
726            'NOT x = 1'
727
728        Args:
729            copy: whether or not to copy this object.
730
731        Returns:
732            The new Not instance.
733        """
734        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:
736    def as_(
737        self,
738        alias: str | Identifier,
739        quoted: t.Optional[bool] = None,
740        dialect: DialectType = None,
741        copy: bool = True,
742        **opts,
743    ) -> Alias:
744        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:
767    def isin(
768        self,
769        *expressions: t.Any,
770        query: t.Optional[ExpOrStr] = None,
771        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
772        copy: bool = True,
773        **opts,
774    ) -> In:
775        return In(
776            this=maybe_copy(self, copy),
777            expressions=[convert(e, copy=copy) for e in expressions],
778            query=maybe_parse(query, copy=copy, **opts) if query else None,
779            unnest=Unnest(
780                expressions=[
781                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
782                ]
783            )
784            if unnest
785            else None,
786        )
def between( self, low: Any, high: Any, copy: bool = True, **opts) -> Between:
788    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
789        return Between(
790            this=maybe_copy(self, copy),
791            low=convert(low, copy=copy, **opts),
792            high=convert(high, copy=copy, **opts),
793        )
def is_( self, other: Union[str, Expression]) -> Is:
795    def is_(self, other: ExpOrStr) -> Is:
796        return self._binop(Is, other)
def like( self, other: Union[str, Expression]) -> Like:
798    def like(self, other: ExpOrStr) -> Like:
799        return self._binop(Like, other)
def ilike( self, other: Union[str, Expression]) -> ILike:
801    def ilike(self, other: ExpOrStr) -> ILike:
802        return self._binop(ILike, other)
def eq(self, other: Any) -> EQ:
804    def eq(self, other: t.Any) -> EQ:
805        return self._binop(EQ, other)
def neq(self, other: Any) -> NEQ:
807    def neq(self, other: t.Any) -> NEQ:
808        return self._binop(NEQ, other)
def rlike( self, other: Union[str, Expression]) -> RegexpLike:
810    def rlike(self, other: ExpOrStr) -> RegexpLike:
811        return self._binop(RegexpLike, other)
IntoType = typing.Union[str, typing.Type[Expression], typing.Collection[typing.Union[str, typing.Type[Expression]]]]
ExpOrStr = typing.Union[str, Expression]
class Condition(Expression):
894class Condition(Expression):
895    """Logical conditions like x AND y, or simply x"""

Logical conditions like x AND y, or simply x

key = 'condition'
class Predicate(Condition):
898class Predicate(Condition):
899    """Relationships like x = y, x > 1, x >= y."""

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

key = 'predicate'
class DerivedTable(Expression):
902class DerivedTable(Expression):
903    @property
904    def selects(self) -> t.List[Expression]:
905        return self.this.selects if isinstance(self.this, Subqueryable) else []
906
907    @property
908    def named_selects(self) -> t.List[str]:
909        return [select.output_name for select in self.selects]
selects: List[Expression]
named_selects: List[str]
key = 'derivedtable'
class Unionable(Expression):
912class Unionable(Expression):
913    def union(
914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
915    ) -> Unionable:
916        """
917        Builds a UNION expression.
918
919        Example:
920            >>> import sqlglot
921            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
922            'SELECT * FROM foo UNION SELECT * FROM bla'
923
924        Args:
925            expression: the SQL code string.
926                If an `Expression` instance is passed, it will be used as-is.
927            distinct: set the DISTINCT flag if and only if this is true.
928            dialect: the dialect used to parse the input expression.
929            opts: other options to use to parse the input expressions.
930
931        Returns:
932            The new Union expression.
933        """
934        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
935
936    def intersect(
937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
938    ) -> Unionable:
939        """
940        Builds an INTERSECT expression.
941
942        Example:
943            >>> import sqlglot
944            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
945            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
946
947        Args:
948            expression: the SQL code string.
949                If an `Expression` instance is passed, it will be used as-is.
950            distinct: set the DISTINCT flag if and only if this is true.
951            dialect: the dialect used to parse the input expression.
952            opts: other options to use to parse the input expressions.
953
954        Returns:
955            The new Intersect expression.
956        """
957        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
958
959    def except_(
960        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
961    ) -> Unionable:
962        """
963        Builds an EXCEPT expression.
964
965        Example:
966            >>> import sqlglot
967            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
968            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
969
970        Args:
971            expression: the SQL code string.
972                If an `Expression` instance is passed, it will be used as-is.
973            distinct: set the DISTINCT flag if and only if this is true.
974            dialect: the dialect used to parse the input expression.
975            opts: other options to use to parse the input expressions.
976
977        Returns:
978            The new Except expression.
979        """
980        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:
913    def union(
914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
915    ) -> Unionable:
916        """
917        Builds a UNION expression.
918
919        Example:
920            >>> import sqlglot
921            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
922            'SELECT * FROM foo UNION SELECT * FROM bla'
923
924        Args:
925            expression: the SQL code string.
926                If an `Expression` instance is passed, it will be used as-is.
927            distinct: set the DISTINCT flag if and only if this is true.
928            dialect: the dialect used to parse the input expression.
929            opts: other options to use to parse the input expressions.
930
931        Returns:
932            The new Union expression.
933        """
934        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:
936    def intersect(
937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
938    ) -> Unionable:
939        """
940        Builds an INTERSECT expression.
941
942        Example:
943            >>> import sqlglot
944            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
945            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
946
947        Args:
948            expression: the SQL code string.
949                If an `Expression` instance is passed, it will be used as-is.
950            distinct: set the DISTINCT flag if and only if this is true.
951            dialect: the dialect used to parse the input expression.
952            opts: other options to use to parse the input expressions.
953
954        Returns:
955            The new Intersect expression.
956        """
957        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:
959    def except_(
960        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
961    ) -> Unionable:
962        """
963        Builds an EXCEPT expression.
964
965        Example:
966            >>> import sqlglot
967            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
968            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
969
970        Args:
971            expression: the SQL code string.
972                If an `Expression` instance is passed, it will be used as-is.
973            distinct: set the DISTINCT flag if and only if this is true.
974            dialect: the dialect used to parse the input expression.
975            opts: other options to use to parse the input expressions.
976
977        Returns:
978            The new Except expression.
979        """
980        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):
983class UDTF(DerivedTable, Unionable):
984    @property
985    def selects(self) -> t.List[Expression]:
986        alias = self.args.get("alias")
987        return alias.columns if alias else []
selects: List[Expression]
key = 'udtf'
class Cache(Expression):
990class Cache(Expression):
991    arg_types = {
992        "with": False,
993        "this": True,
994        "lazy": False,
995        "options": False,
996        "expression": False,
997    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
1000class Uncache(Expression):
1001    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class DDL(Expression):
1004class DDL(Expression):
1005    @property
1006    def ctes(self):
1007        with_ = self.args.get("with")
1008        if not with_:
1009            return []
1010        return with_.expressions
1011
1012    @property
1013    def named_selects(self) -> t.List[str]:
1014        if isinstance(self.expression, Subqueryable):
1015            return self.expression.named_selects
1016        return []
1017
1018    @property
1019    def selects(self) -> t.List[Expression]:
1020        if isinstance(self.expression, Subqueryable):
1021            return self.expression.selects
1022        return []
ctes
named_selects: List[str]
selects: List[Expression]
key = 'ddl'
class Create(DDL):
1025class Create(DDL):
1026    arg_types = {
1027        "with": False,
1028        "this": True,
1029        "kind": True,
1030        "expression": False,
1031        "exists": False,
1032        "properties": False,
1033        "replace": False,
1034        "unique": False,
1035        "indexes": False,
1036        "no_schema_binding": False,
1037        "begin": False,
1038        "clone": False,
1039    }
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):
1043class Clone(Expression):
1044    arg_types = {
1045        "this": True,
1046        "when": False,
1047        "kind": False,
1048        "shallow": False,
1049        "expression": False,
1050    }
arg_types = {'this': True, 'when': False, 'kind': False, 'shallow': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1053class Describe(Expression):
1054    arg_types = {"this": True, "kind": False, "expressions": False}
arg_types = {'this': True, 'kind': False, 'expressions': False}
key = 'describe'
class Kill(Expression):
1057class Kill(Expression):
1058    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'kill'
class Pragma(Expression):
1061class Pragma(Expression):
1062    pass
key = 'pragma'
class Set(Expression):
1065class Set(Expression):
1066    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1069class SetItem(Expression):
1070    arg_types = {
1071        "this": False,
1072        "expressions": False,
1073        "kind": False,
1074        "collate": False,  # MySQL SET NAMES statement
1075        "global": False,
1076    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1079class Show(Expression):
1080    arg_types = {
1081        "this": True,
1082        "target": False,
1083        "offset": False,
1084        "limit": False,
1085        "like": False,
1086        "where": False,
1087        "db": False,
1088        "scope": False,
1089        "scope_kind": False,
1090        "full": False,
1091        "mutex": False,
1092        "query": False,
1093        "channel": False,
1094        "global": False,
1095        "log": False,
1096        "position": False,
1097        "types": False,
1098    }
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):
1101class UserDefinedFunction(Expression):
1102    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1105class CharacterSet(Expression):
1106    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1109class With(Expression):
1110    arg_types = {"expressions": True, "recursive": False}
1111
1112    @property
1113    def recursive(self) -> bool:
1114        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1117class WithinGroup(Expression):
1118    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1121class CTE(DerivedTable):
1122    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1125class TableAlias(Expression):
1126    arg_types = {"this": False, "columns": False}
1127
1128    @property
1129    def columns(self):
1130        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1133class BitString(Condition):
1134    pass
key = 'bitstring'
class HexString(Condition):
1137class HexString(Condition):
1138    pass
key = 'hexstring'
class ByteString(Condition):
1141class ByteString(Condition):
1142    pass
key = 'bytestring'
class RawString(Condition):
1145class RawString(Condition):
1146    pass
key = 'rawstring'
class Column(Condition):
1149class Column(Condition):
1150    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1151
1152    @property
1153    def table(self) -> str:
1154        return self.text("table")
1155
1156    @property
1157    def db(self) -> str:
1158        return self.text("db")
1159
1160    @property
1161    def catalog(self) -> str:
1162        return self.text("catalog")
1163
1164    @property
1165    def output_name(self) -> str:
1166        return self.name
1167
1168    @property
1169    def parts(self) -> t.List[Identifier]:
1170        """Return the parts of a column in order catalog, db, table, name."""
1171        return [
1172            t.cast(Identifier, self.args[part])
1173            for part in ("catalog", "db", "table", "this")
1174            if self.args.get(part)
1175        ]
1176
1177    def to_dot(self) -> Dot:
1178        """Converts the column into a dot expression."""
1179        parts = self.parts
1180        parent = self.parent
1181
1182        while parent:
1183            if isinstance(parent, Dot):
1184                parts.append(parent.expression)
1185            parent = parent.parent
1186
1187        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:
1177    def to_dot(self) -> Dot:
1178        """Converts the column into a dot expression."""
1179        parts = self.parts
1180        parent = self.parent
1181
1182        while parent:
1183            if isinstance(parent, Dot):
1184                parts.append(parent.expression)
1185            parent = parent.parent
1186
1187        return Dot.build(deepcopy(parts))

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1190class ColumnPosition(Expression):
1191    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1194class ColumnDef(Expression):
1195    arg_types = {
1196        "this": True,
1197        "kind": False,
1198        "constraints": False,
1199        "exists": False,
1200        "position": False,
1201    }
1202
1203    @property
1204    def constraints(self) -> t.List[ColumnConstraint]:
1205        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):
1208class AlterColumn(Expression):
1209    arg_types = {
1210        "this": True,
1211        "dtype": False,
1212        "collate": False,
1213        "using": False,
1214        "default": False,
1215        "drop": False,
1216    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1219class RenameTable(Expression):
1220    pass
key = 'renametable'
class Comment(Expression):
1223class Comment(Expression):
1224    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):
1227class Comprehension(Expression):
1228    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):
1232class MergeTreeTTLAction(Expression):
1233    arg_types = {
1234        "this": True,
1235        "delete": False,
1236        "recompress": False,
1237        "to_disk": False,
1238        "to_volume": False,
1239    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1243class MergeTreeTTL(Expression):
1244    arg_types = {
1245        "expressions": True,
1246        "where": False,
1247        "group": False,
1248        "aggregates": False,
1249    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class IndexConstraintOption(Expression):
1253class IndexConstraintOption(Expression):
1254    arg_types = {
1255        "key_block_size": False,
1256        "using": False,
1257        "parser": False,
1258        "comment": False,
1259        "visible": False,
1260        "engine_attr": False,
1261        "secondary_engine_attr": False,
1262    }
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):
1265class ColumnConstraint(Expression):
1266    arg_types = {"this": False, "kind": True}
1267
1268    @property
1269    def kind(self) -> ColumnConstraintKind:
1270        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1273class ColumnConstraintKind(Expression):
1274    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1277class AutoIncrementColumnConstraint(ColumnConstraintKind):
1278    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1281class CaseSpecificColumnConstraint(ColumnConstraintKind):
1282    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1285class CharacterSetColumnConstraint(ColumnConstraintKind):
1286    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1289class CheckColumnConstraint(ColumnConstraintKind):
1290    pass
key = 'checkcolumnconstraint'
class ClusteredColumnConstraint(ColumnConstraintKind):
1293class ClusteredColumnConstraint(ColumnConstraintKind):
1294    pass
key = 'clusteredcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1297class CollateColumnConstraint(ColumnConstraintKind):
1298    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1301class CommentColumnConstraint(ColumnConstraintKind):
1302    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1305class CompressColumnConstraint(ColumnConstraintKind):
1306    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1309class DateFormatColumnConstraint(ColumnConstraintKind):
1310    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1313class DefaultColumnConstraint(ColumnConstraintKind):
1314    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1317class EncodeColumnConstraint(ColumnConstraintKind):
1318    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1321class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1322    # this: True -> ALWAYS, this: False -> BY DEFAULT
1323    arg_types = {
1324        "this": False,
1325        "expression": False,
1326        "on_null": False,
1327        "start": False,
1328        "increment": False,
1329        "minvalue": False,
1330        "maxvalue": False,
1331        "cycle": False,
1332    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class IndexColumnConstraint(ColumnConstraintKind):
1336class IndexColumnConstraint(ColumnConstraintKind):
1337    arg_types = {
1338        "this": False,
1339        "schema": True,
1340        "kind": False,
1341        "index_type": False,
1342        "options": False,
1343    }
arg_types = {'this': False, 'schema': True, 'kind': False, 'index_type': False, 'options': False}
key = 'indexcolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1346class InlineLengthColumnConstraint(ColumnConstraintKind):
1347    pass
key = 'inlinelengthcolumnconstraint'
class NonClusteredColumnConstraint(ColumnConstraintKind):
1350class NonClusteredColumnConstraint(ColumnConstraintKind):
1351    pass
key = 'nonclusteredcolumnconstraint'
class NotForReplicationColumnConstraint(ColumnConstraintKind):
1354class NotForReplicationColumnConstraint(ColumnConstraintKind):
1355    arg_types = {}
arg_types = {}
key = 'notforreplicationcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1358class NotNullColumnConstraint(ColumnConstraintKind):
1359    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1363class OnUpdateColumnConstraint(ColumnConstraintKind):
1364    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1367class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1368    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1371class TitleColumnConstraint(ColumnConstraintKind):
1372    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1375class UniqueColumnConstraint(ColumnConstraintKind):
1376    arg_types = {"this": False, "index_type": False}
arg_types = {'this': False, 'index_type': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1379class UppercaseColumnConstraint(ColumnConstraintKind):
1380    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1383class PathColumnConstraint(ColumnConstraintKind):
1384    pass
key = 'pathcolumnconstraint'
class ComputedColumnConstraint(ColumnConstraintKind):
1389class ComputedColumnConstraint(ColumnConstraintKind):
1390    arg_types = {"this": True, "persisted": False, "not_null": False}
arg_types = {'this': True, 'persisted': False, 'not_null': False}
key = 'computedcolumnconstraint'
class Constraint(Expression):
1393class Constraint(Expression):
1394    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1397class Delete(Expression):
1398    arg_types = {
1399        "with": False,
1400        "this": False,
1401        "using": False,
1402        "where": False,
1403        "returning": False,
1404        "limit": False,
1405        "tables": False,  # Multiple-Table Syntax (MySQL)
1406    }
1407
1408    def delete(
1409        self,
1410        table: ExpOrStr,
1411        dialect: DialectType = None,
1412        copy: bool = True,
1413        **opts,
1414    ) -> Delete:
1415        """
1416        Create a DELETE expression or replace the table on an existing DELETE expression.
1417
1418        Example:
1419            >>> delete("tbl").sql()
1420            'DELETE FROM tbl'
1421
1422        Args:
1423            table: the table from which to delete.
1424            dialect: the dialect used to parse the input expression.
1425            copy: if `False`, modify this expression instance in-place.
1426            opts: other options to use to parse the input expressions.
1427
1428        Returns:
1429            Delete: the modified expression.
1430        """
1431        return _apply_builder(
1432            expression=table,
1433            instance=self,
1434            arg="this",
1435            dialect=dialect,
1436            into=Table,
1437            copy=copy,
1438            **opts,
1439        )
1440
1441    def where(
1442        self,
1443        *expressions: t.Optional[ExpOrStr],
1444        append: bool = True,
1445        dialect: DialectType = None,
1446        copy: bool = True,
1447        **opts,
1448    ) -> Delete:
1449        """
1450        Append to or set the WHERE expressions.
1451
1452        Example:
1453            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1454            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1455
1456        Args:
1457            *expressions: the SQL code strings to parse.
1458                If an `Expression` instance is passed, it will be used as-is.
1459                Multiple expressions are combined with an AND operator.
1460            append: if `True`, AND the new expressions to any existing expression.
1461                Otherwise, this resets the expression.
1462            dialect: the dialect used to parse the input expressions.
1463            copy: if `False`, modify this expression instance in-place.
1464            opts: other options to use to parse the input expressions.
1465
1466        Returns:
1467            Delete: the modified expression.
1468        """
1469        return _apply_conjunction_builder(
1470            *expressions,
1471            instance=self,
1472            arg="where",
1473            append=append,
1474            into=Where,
1475            dialect=dialect,
1476            copy=copy,
1477            **opts,
1478        )
1479
1480    def returning(
1481        self,
1482        expression: ExpOrStr,
1483        dialect: DialectType = None,
1484        copy: bool = True,
1485        **opts,
1486    ) -> Delete:
1487        """
1488        Set the RETURNING expression. Not supported by all dialects.
1489
1490        Example:
1491            >>> delete("tbl").returning("*", dialect="postgres").sql()
1492            'DELETE FROM tbl RETURNING *'
1493
1494        Args:
1495            expression: the SQL code strings to parse.
1496                If an `Expression` instance is passed, it will be used as-is.
1497            dialect: the dialect used to parse the input expressions.
1498            copy: if `False`, modify this expression instance in-place.
1499            opts: other options to use to parse the input expressions.
1500
1501        Returns:
1502            Delete: the modified expression.
1503        """
1504        return _apply_builder(
1505            expression=expression,
1506            instance=self,
1507            arg="returning",
1508            prefix="RETURNING",
1509            dialect=dialect,
1510            copy=copy,
1511            into=Returning,
1512            **opts,
1513        )
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:
1408    def delete(
1409        self,
1410        table: ExpOrStr,
1411        dialect: DialectType = None,
1412        copy: bool = True,
1413        **opts,
1414    ) -> Delete:
1415        """
1416        Create a DELETE expression or replace the table on an existing DELETE expression.
1417
1418        Example:
1419            >>> delete("tbl").sql()
1420            'DELETE FROM tbl'
1421
1422        Args:
1423            table: the table from which to delete.
1424            dialect: the dialect used to parse the input expression.
1425            copy: if `False`, modify this expression instance in-place.
1426            opts: other options to use to parse the input expressions.
1427
1428        Returns:
1429            Delete: the modified expression.
1430        """
1431        return _apply_builder(
1432            expression=table,
1433            instance=self,
1434            arg="this",
1435            dialect=dialect,
1436            into=Table,
1437            copy=copy,
1438            **opts,
1439        )

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

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

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):
1516class Drop(Expression):
1517    arg_types = {
1518        "this": False,
1519        "kind": False,
1520        "exists": False,
1521        "temporary": False,
1522        "materialized": False,
1523        "cascade": False,
1524        "constraints": False,
1525        "purge": False,
1526    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1529class Filter(Expression):
1530    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1533class Check(Expression):
1534    pass
key = 'check'
class Connect(Expression):
1538class Connect(Expression):
1539    arg_types = {"start": False, "connect": True}
arg_types = {'start': False, 'connect': True}
key = 'connect'
class Prior(Expression):
1542class Prior(Expression):
1543    pass
key = 'prior'
class Directory(Expression):
1546class Directory(Expression):
1547    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1548    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1551class ForeignKey(Expression):
1552    arg_types = {
1553        "expressions": True,
1554        "reference": False,
1555        "delete": False,
1556        "update": False,
1557    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class ColumnPrefix(Expression):
1560class ColumnPrefix(Expression):
1561    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'columnprefix'
class PrimaryKey(Expression):
1564class PrimaryKey(Expression):
1565    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1570class Into(Expression):
1571    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1574class From(Expression):
1575    @property
1576    def name(self) -> str:
1577        return self.this.name
1578
1579    @property
1580    def alias_or_name(self) -> str:
1581        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1584class Having(Expression):
1585    pass
key = 'having'
class Hint(Expression):
1588class Hint(Expression):
1589    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1592class JoinHint(Expression):
1593    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1596class Identifier(Expression):
1597    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1598
1599    @property
1600    def quoted(self) -> bool:
1601        return bool(self.args.get("quoted"))
1602
1603    @property
1604    def hashable_args(self) -> t.Any:
1605        return (self.this, self.quoted)
1606
1607    @property
1608    def output_name(self) -> str:
1609        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):
1612class Index(Expression):
1613    arg_types = {
1614        "this": False,
1615        "table": False,
1616        "using": False,
1617        "where": False,
1618        "columns": False,
1619        "unique": False,
1620        "primary": False,
1621        "amp": False,  # teradata
1622        "partition_by": False,  # teradata
1623        "where": False,  # postgres partial indexes
1624    }
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):
1627class Insert(DDL):
1628    arg_types = {
1629        "with": False,
1630        "this": True,
1631        "expression": False,
1632        "conflict": False,
1633        "returning": False,
1634        "overwrite": False,
1635        "exists": False,
1636        "partition": False,
1637        "alternative": False,
1638        "where": False,
1639        "ignore": False,
1640        "by_name": False,
1641    }
1642
1643    def with_(
1644        self,
1645        alias: ExpOrStr,
1646        as_: ExpOrStr,
1647        recursive: t.Optional[bool] = None,
1648        append: bool = True,
1649        dialect: DialectType = None,
1650        copy: bool = True,
1651        **opts,
1652    ) -> Insert:
1653        """
1654        Append to or set the common table expressions.
1655
1656        Example:
1657            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1658            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1659
1660        Args:
1661            alias: the SQL code string to parse as the table name.
1662                If an `Expression` instance is passed, this is used as-is.
1663            as_: the SQL code string to parse as the table expression.
1664                If an `Expression` instance is passed, it will be used as-is.
1665            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1666            append: if `True`, add to any existing expressions.
1667                Otherwise, this resets the expressions.
1668            dialect: the dialect used to parse the input expression.
1669            copy: if `False`, modify this expression instance in-place.
1670            opts: other options to use to parse the input expressions.
1671
1672        Returns:
1673            The modified expression.
1674        """
1675        return _apply_cte_builder(
1676            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1677        )
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:
1643    def with_(
1644        self,
1645        alias: ExpOrStr,
1646        as_: ExpOrStr,
1647        recursive: t.Optional[bool] = None,
1648        append: bool = True,
1649        dialect: DialectType = None,
1650        copy: bool = True,
1651        **opts,
1652    ) -> Insert:
1653        """
1654        Append to or set the common table expressions.
1655
1656        Example:
1657            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1658            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1659
1660        Args:
1661            alias: the SQL code string to parse as the table name.
1662                If an `Expression` instance is passed, this is used as-is.
1663            as_: the SQL code string to parse as the table expression.
1664                If an `Expression` instance is passed, it will be used as-is.
1665            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1666            append: if `True`, add to any existing expressions.
1667                Otherwise, this resets the expressions.
1668            dialect: the dialect used to parse the input expression.
1669            copy: if `False`, modify this expression instance in-place.
1670            opts: other options to use to parse the input expressions.
1671
1672        Returns:
1673            The modified expression.
1674        """
1675        return _apply_cte_builder(
1676            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1677        )

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):
1680class OnConflict(Expression):
1681    arg_types = {
1682        "duplicate": False,
1683        "expressions": False,
1684        "nothing": False,
1685        "key": False,
1686        "constraint": False,
1687    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1690class Returning(Expression):
1691    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1695class Introducer(Expression):
1696    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1700class National(Expression):
1701    pass
key = 'national'
class LoadData(Expression):
1704class LoadData(Expression):
1705    arg_types = {
1706        "this": True,
1707        "local": False,
1708        "overwrite": False,
1709        "inpath": True,
1710        "partition": False,
1711        "input_format": False,
1712        "serde": False,
1713    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1716class Partition(Expression):
1717    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1720class Fetch(Expression):
1721    arg_types = {
1722        "direction": False,
1723        "count": False,
1724        "percent": False,
1725        "with_ties": False,
1726    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1729class Group(Expression):
1730    arg_types = {
1731        "expressions": False,
1732        "grouping_sets": False,
1733        "cube": False,
1734        "rollup": False,
1735        "totals": False,
1736        "all": False,
1737    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1740class Lambda(Expression):
1741    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1744class Limit(Expression):
1745    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1748class Literal(Condition):
1749    arg_types = {"this": True, "is_string": True}
1750
1751    @property
1752    def hashable_args(self) -> t.Any:
1753        return (self.this, self.args.get("is_string"))
1754
1755    @classmethod
1756    def number(cls, number) -> Literal:
1757        return cls(this=str(number), is_string=False)
1758
1759    @classmethod
1760    def string(cls, string) -> Literal:
1761        return cls(this=str(string), is_string=True)
1762
1763    @property
1764    def output_name(self) -> str:
1765        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> Literal:
1755    @classmethod
1756    def number(cls, number) -> Literal:
1757        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> Literal:
1759    @classmethod
1760    def string(cls, string) -> Literal:
1761        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):
1768class Join(Expression):
1769    arg_types = {
1770        "this": True,
1771        "on": False,
1772        "side": False,
1773        "kind": False,
1774        "using": False,
1775        "method": False,
1776        "global": False,
1777        "hint": False,
1778    }
1779
1780    @property
1781    def method(self) -> str:
1782        return self.text("method").upper()
1783
1784    @property
1785    def kind(self) -> str:
1786        return self.text("kind").upper()
1787
1788    @property
1789    def side(self) -> str:
1790        return self.text("side").upper()
1791
1792    @property
1793    def hint(self) -> str:
1794        return self.text("hint").upper()
1795
1796    @property
1797    def alias_or_name(self) -> str:
1798        return self.this.alias_or_name
1799
1800    def on(
1801        self,
1802        *expressions: t.Optional[ExpOrStr],
1803        append: bool = True,
1804        dialect: DialectType = None,
1805        copy: bool = True,
1806        **opts,
1807    ) -> Join:
1808        """
1809        Append to or set the ON expressions.
1810
1811        Example:
1812            >>> import sqlglot
1813            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1814            'JOIN x ON y = 1'
1815
1816        Args:
1817            *expressions: the SQL code strings to parse.
1818                If an `Expression` instance is passed, it will be used as-is.
1819                Multiple expressions are combined with an AND operator.
1820            append: if `True`, AND the new expressions to any existing expression.
1821                Otherwise, this resets the expression.
1822            dialect: the dialect used to parse the input expressions.
1823            copy: if `False`, modify this expression instance in-place.
1824            opts: other options to use to parse the input expressions.
1825
1826        Returns:
1827            The modified Join expression.
1828        """
1829        join = _apply_conjunction_builder(
1830            *expressions,
1831            instance=self,
1832            arg="on",
1833            append=append,
1834            dialect=dialect,
1835            copy=copy,
1836            **opts,
1837        )
1838
1839        if join.kind == "CROSS":
1840            join.set("kind", None)
1841
1842        return join
1843
1844    def using(
1845        self,
1846        *expressions: t.Optional[ExpOrStr],
1847        append: bool = True,
1848        dialect: DialectType = None,
1849        copy: bool = True,
1850        **opts,
1851    ) -> Join:
1852        """
1853        Append to or set the USING expressions.
1854
1855        Example:
1856            >>> import sqlglot
1857            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1858            'JOIN x USING (foo, bla)'
1859
1860        Args:
1861            *expressions: the SQL code strings to parse.
1862                If an `Expression` instance is passed, it will be used as-is.
1863            append: if `True`, concatenate the new expressions to the existing "using" list.
1864                Otherwise, this resets the expression.
1865            dialect: the dialect used to parse the input expressions.
1866            copy: if `False`, modify this expression instance in-place.
1867            opts: other options to use to parse the input expressions.
1868
1869        Returns:
1870            The modified Join expression.
1871        """
1872        join = _apply_list_builder(
1873            *expressions,
1874            instance=self,
1875            arg="using",
1876            append=append,
1877            dialect=dialect,
1878            copy=copy,
1879            **opts,
1880        )
1881
1882        if join.kind == "CROSS":
1883            join.set("kind", None)
1884
1885        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:
1800    def on(
1801        self,
1802        *expressions: t.Optional[ExpOrStr],
1803        append: bool = True,
1804        dialect: DialectType = None,
1805        copy: bool = True,
1806        **opts,
1807    ) -> Join:
1808        """
1809        Append to or set the ON expressions.
1810
1811        Example:
1812            >>> import sqlglot
1813            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1814            'JOIN x ON y = 1'
1815
1816        Args:
1817            *expressions: the SQL code strings to parse.
1818                If an `Expression` instance is passed, it will be used as-is.
1819                Multiple expressions are combined with an AND operator.
1820            append: if `True`, AND the new expressions to any existing expression.
1821                Otherwise, this resets the expression.
1822            dialect: the dialect used to parse the input expressions.
1823            copy: if `False`, modify this expression instance in-place.
1824            opts: other options to use to parse the input expressions.
1825
1826        Returns:
1827            The modified Join expression.
1828        """
1829        join = _apply_conjunction_builder(
1830            *expressions,
1831            instance=self,
1832            arg="on",
1833            append=append,
1834            dialect=dialect,
1835            copy=copy,
1836            **opts,
1837        )
1838
1839        if join.kind == "CROSS":
1840            join.set("kind", None)
1841
1842        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:
1844    def using(
1845        self,
1846        *expressions: t.Optional[ExpOrStr],
1847        append: bool = True,
1848        dialect: DialectType = None,
1849        copy: bool = True,
1850        **opts,
1851    ) -> Join:
1852        """
1853        Append to or set the USING expressions.
1854
1855        Example:
1856            >>> import sqlglot
1857            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1858            'JOIN x USING (foo, bla)'
1859
1860        Args:
1861            *expressions: the SQL code strings to parse.
1862                If an `Expression` instance is passed, it will be used as-is.
1863            append: if `True`, concatenate the new expressions to the existing "using" list.
1864                Otherwise, this resets the expression.
1865            dialect: the dialect used to parse the input expressions.
1866            copy: if `False`, modify this expression instance in-place.
1867            opts: other options to use to parse the input expressions.
1868
1869        Returns:
1870            The modified Join expression.
1871        """
1872        join = _apply_list_builder(
1873            *expressions,
1874            instance=self,
1875            arg="using",
1876            append=append,
1877            dialect=dialect,
1878            copy=copy,
1879            **opts,
1880        )
1881
1882        if join.kind == "CROSS":
1883            join.set("kind", None)
1884
1885        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):
1888class Lateral(UDTF):
1889    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):
1892class MatchRecognize(Expression):
1893    arg_types = {
1894        "partition_by": False,
1895        "order": False,
1896        "measures": False,
1897        "rows": False,
1898        "after": False,
1899        "pattern": False,
1900        "define": False,
1901        "alias": False,
1902    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1907class Final(Expression):
1908    pass
key = 'final'
class Offset(Expression):
1911class Offset(Expression):
1912    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1915class Order(Expression):
1916    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1921class Cluster(Order):
1922    pass
key = 'cluster'
class Distribute(Order):
1925class Distribute(Order):
1926    pass
key = 'distribute'
class Sort(Order):
1929class Sort(Order):
1930    pass
key = 'sort'
class Ordered(Expression):
1933class Ordered(Expression):
1934    arg_types = {"this": True, "desc": False, "nulls_first": True}
arg_types = {'this': True, 'desc': False, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1937class Property(Expression):
1938    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1941class AlgorithmProperty(Property):
1942    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1945class AutoIncrementProperty(Property):
1946    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1949class BlockCompressionProperty(Property):
1950    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):
1953class CharacterSetProperty(Property):
1954    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1957class ChecksumProperty(Property):
1958    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1961class CollateProperty(Property):
1962    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1965class CopyGrantsProperty(Property):
1966    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1969class DataBlocksizeProperty(Property):
1970    arg_types = {
1971        "size": False,
1972        "units": False,
1973        "minimum": False,
1974        "maximum": False,
1975        "default": False,
1976    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1979class DefinerProperty(Property):
1980    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1983class DistKeyProperty(Property):
1984    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1987class DistStyleProperty(Property):
1988    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1991class EngineProperty(Property):
1992    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
1995class HeapProperty(Property):
1996    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
1999class ToTableProperty(Property):
2000    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
2003class ExecuteAsProperty(Property):
2004    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
2007class ExternalProperty(Property):
2008    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
2011class FallbackProperty(Property):
2012    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
2015class FileFormatProperty(Property):
2016    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
2019class FreespaceProperty(Property):
2020    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
2023class InputOutputFormat(Expression):
2024    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
2027class IsolatedLoadingProperty(Property):
2028    arg_types = {
2029        "no": True,
2030        "concurrent": True,
2031        "for_all": True,
2032        "for_insert": True,
2033        "for_none": True,
2034    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
2037class JournalProperty(Property):
2038    arg_types = {
2039        "no": False,
2040        "dual": False,
2041        "before": False,
2042        "local": False,
2043        "after": False,
2044    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
2047class LanguageProperty(Property):
2048    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
2052class ClusteredByProperty(Property):
2053    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
2056class DictProperty(Property):
2057    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2060class DictSubProperty(Property):
2061    pass
key = 'dictsubproperty'
class DictRange(Property):
2064class DictRange(Property):
2065    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2070class OnCluster(Property):
2071    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2074class LikeProperty(Property):
2075    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2078class LocationProperty(Property):
2079    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2082class LockingProperty(Property):
2083    arg_types = {
2084        "this": False,
2085        "kind": True,
2086        "for_or_in": True,
2087        "lock_type": True,
2088        "override": False,
2089    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2092class LogProperty(Property):
2093    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2096class MaterializedProperty(Property):
2097    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2100class MergeBlockRatioProperty(Property):
2101    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):
2104class NoPrimaryIndexProperty(Property):
2105    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnProperty(Property):
2108class OnProperty(Property):
2109    arg_types = {"this": True}
arg_types = {'this': True}
key = 'onproperty'
class OnCommitProperty(Property):
2112class OnCommitProperty(Property):
2113    arg_types = {"delete": False}
arg_types = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2116class PartitionedByProperty(Property):
2117    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2120class ReturnsProperty(Property):
2121    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2124class RowFormatProperty(Property):
2125    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2128class RowFormatDelimitedProperty(Property):
2129    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2130    arg_types = {
2131        "fields": False,
2132        "escaped": False,
2133        "collection_items": False,
2134        "map_keys": False,
2135        "lines": False,
2136        "null": False,
2137        "serde": False,
2138    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2141class RowFormatSerdeProperty(Property):
2142    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2146class QueryTransform(Expression):
2147    arg_types = {
2148        "expressions": True,
2149        "command_script": True,
2150        "schema": False,
2151        "row_format_before": False,
2152        "record_writer": False,
2153        "row_format_after": False,
2154        "record_reader": False,
2155    }
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):
2158class SchemaCommentProperty(Property):
2159    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2162class SerdeProperties(Property):
2163    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2166class SetProperty(Property):
2167    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2170class SettingsProperty(Property):
2171    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2174class SortKeyProperty(Property):
2175    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2178class SqlSecurityProperty(Property):
2179    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2182class StabilityProperty(Property):
2183    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2186class TemporaryProperty(Property):
2187    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2190class TransientProperty(Property):
2191    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2194class VolatileProperty(Property):
2195    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2198class WithDataProperty(Property):
2199    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2202class WithJournalTableProperty(Property):
2203    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2206class Properties(Expression):
2207    arg_types = {"expressions": True}
2208
2209    NAME_TO_PROPERTY = {
2210        "ALGORITHM": AlgorithmProperty,
2211        "AUTO_INCREMENT": AutoIncrementProperty,
2212        "CHARACTER SET": CharacterSetProperty,
2213        "CLUSTERED_BY": ClusteredByProperty,
2214        "COLLATE": CollateProperty,
2215        "COMMENT": SchemaCommentProperty,
2216        "DEFINER": DefinerProperty,
2217        "DISTKEY": DistKeyProperty,
2218        "DISTSTYLE": DistStyleProperty,
2219        "ENGINE": EngineProperty,
2220        "EXECUTE AS": ExecuteAsProperty,
2221        "FORMAT": FileFormatProperty,
2222        "LANGUAGE": LanguageProperty,
2223        "LOCATION": LocationProperty,
2224        "PARTITIONED_BY": PartitionedByProperty,
2225        "RETURNS": ReturnsProperty,
2226        "ROW_FORMAT": RowFormatProperty,
2227        "SORTKEY": SortKeyProperty,
2228    }
2229
2230    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2231
2232    # CREATE property locations
2233    # Form: schema specified
2234    #   create [POST_CREATE]
2235    #     table a [POST_NAME]
2236    #     (b int) [POST_SCHEMA]
2237    #     with ([POST_WITH])
2238    #     index (b) [POST_INDEX]
2239    #
2240    # Form: alias selection
2241    #   create [POST_CREATE]
2242    #     table a [POST_NAME]
2243    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2244    #     index (c) [POST_INDEX]
2245    class Location(AutoName):
2246        POST_CREATE = auto()
2247        POST_NAME = auto()
2248        POST_SCHEMA = auto()
2249        POST_WITH = auto()
2250        POST_ALIAS = auto()
2251        POST_EXPRESSION = auto()
2252        POST_INDEX = auto()
2253        UNSUPPORTED = auto()
2254
2255    @classmethod
2256    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2257        expressions = []
2258        for key, value in properties_dict.items():
2259            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2260            if property_cls:
2261                expressions.append(property_cls(this=convert(value)))
2262            else:
2263                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2264
2265        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:
2255    @classmethod
2256    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2257        expressions = []
2258        for key, value in properties_dict.items():
2259            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2260            if property_cls:
2261                expressions.append(property_cls(this=convert(value)))
2262            else:
2263                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2264
2265        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2245    class Location(AutoName):
2246        POST_CREATE = auto()
2247        POST_NAME = auto()
2248        POST_SCHEMA = auto()
2249        POST_WITH = auto()
2250        POST_ALIAS = auto()
2251        POST_EXPRESSION = auto()
2252        POST_INDEX = auto()
2253        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):
2268class Qualify(Expression):
2269    pass
key = 'qualify'
class Return(Expression):
2273class Return(Expression):
2274    pass
key = 'return'
class Reference(Expression):
2277class Reference(Expression):
2278    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2281class Tuple(Expression):
2282    arg_types = {"expressions": False}
2283
2284    def isin(
2285        self,
2286        *expressions: t.Any,
2287        query: t.Optional[ExpOrStr] = None,
2288        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2289        copy: bool = True,
2290        **opts,
2291    ) -> In:
2292        return In(
2293            this=maybe_copy(self, copy),
2294            expressions=[convert(e, copy=copy) for e in expressions],
2295            query=maybe_parse(query, copy=copy, **opts) if query else None,
2296            unnest=Unnest(
2297                expressions=[
2298                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2299                ]
2300            )
2301            if unnest
2302            else None,
2303        )
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:
2284    def isin(
2285        self,
2286        *expressions: t.Any,
2287        query: t.Optional[ExpOrStr] = None,
2288        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2289        copy: bool = True,
2290        **opts,
2291    ) -> In:
2292        return In(
2293            this=maybe_copy(self, copy),
2294            expressions=[convert(e, copy=copy) for e in expressions],
2295            query=maybe_parse(query, copy=copy, **opts) if query else None,
2296            unnest=Unnest(
2297                expressions=[
2298                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2299                ]
2300            )
2301            if unnest
2302            else None,
2303        )
key = 'tuple'
class Subqueryable(Unionable):
2306class Subqueryable(Unionable):
2307    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2308        """
2309        Convert this expression to an aliased expression that can be used as a Subquery.
2310
2311        Example:
2312            >>> subquery = Select().select("x").from_("tbl").subquery()
2313            >>> Select().select("x").from_(subquery).sql()
2314            'SELECT x FROM (SELECT x FROM tbl)'
2315
2316        Args:
2317            alias (str | Identifier): an optional alias for the subquery
2318            copy (bool): if `False`, modify this expression instance in-place.
2319
2320        Returns:
2321            Alias: the subquery
2322        """
2323        instance = maybe_copy(self, copy)
2324        if not isinstance(alias, Expression):
2325            alias = TableAlias(this=to_identifier(alias)) if alias else None
2326
2327        return Subquery(this=instance, alias=alias)
2328
2329    def limit(
2330        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2331    ) -> Select:
2332        raise NotImplementedError
2333
2334    @property
2335    def ctes(self):
2336        with_ = self.args.get("with")
2337        if not with_:
2338            return []
2339        return with_.expressions
2340
2341    @property
2342    def selects(self) -> t.List[Expression]:
2343        raise NotImplementedError("Subqueryable objects must implement `selects`")
2344
2345    @property
2346    def named_selects(self) -> t.List[str]:
2347        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2348
2349    def select(
2350        self,
2351        *expressions: t.Optional[ExpOrStr],
2352        append: bool = True,
2353        dialect: DialectType = None,
2354        copy: bool = True,
2355        **opts,
2356    ) -> Subqueryable:
2357        raise NotImplementedError("Subqueryable objects must implement `select`")
2358
2359    def with_(
2360        self,
2361        alias: ExpOrStr,
2362        as_: ExpOrStr,
2363        recursive: t.Optional[bool] = None,
2364        append: bool = True,
2365        dialect: DialectType = None,
2366        copy: bool = True,
2367        **opts,
2368    ) -> Subqueryable:
2369        """
2370        Append to or set the common table expressions.
2371
2372        Example:
2373            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2374            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2375
2376        Args:
2377            alias: the SQL code string to parse as the table name.
2378                If an `Expression` instance is passed, this is used as-is.
2379            as_: the SQL code string to parse as the table expression.
2380                If an `Expression` instance is passed, it will be used as-is.
2381            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2382            append: if `True`, add to any existing expressions.
2383                Otherwise, this resets the expressions.
2384            dialect: the dialect used to parse the input expression.
2385            copy: if `False`, modify this expression instance in-place.
2386            opts: other options to use to parse the input expressions.
2387
2388        Returns:
2389            The modified expression.
2390        """
2391        return _apply_cte_builder(
2392            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2393        )
def subquery( self, alias: Union[str, Expression, NoneType] = None, copy: bool = True) -> Subquery:
2307    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2308        """
2309        Convert this expression to an aliased expression that can be used as a Subquery.
2310
2311        Example:
2312            >>> subquery = Select().select("x").from_("tbl").subquery()
2313            >>> Select().select("x").from_(subquery).sql()
2314            'SELECT x FROM (SELECT x FROM tbl)'
2315
2316        Args:
2317            alias (str | Identifier): an optional alias for the subquery
2318            copy (bool): if `False`, modify this expression instance in-place.
2319
2320        Returns:
2321            Alias: the subquery
2322        """
2323        instance = maybe_copy(self, copy)
2324        if not isinstance(alias, Expression):
2325            alias = TableAlias(this=to_identifier(alias)) if alias else None
2326
2327        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:
2329    def limit(
2330        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2331    ) -> Select:
2332        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:
2349    def select(
2350        self,
2351        *expressions: t.Optional[ExpOrStr],
2352        append: bool = True,
2353        dialect: DialectType = None,
2354        copy: bool = True,
2355        **opts,
2356    ) -> Subqueryable:
2357        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:
2359    def with_(
2360        self,
2361        alias: ExpOrStr,
2362        as_: ExpOrStr,
2363        recursive: t.Optional[bool] = None,
2364        append: bool = True,
2365        dialect: DialectType = None,
2366        copy: bool = True,
2367        **opts,
2368    ) -> Subqueryable:
2369        """
2370        Append to or set the common table expressions.
2371
2372        Example:
2373            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2374            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2375
2376        Args:
2377            alias: the SQL code string to parse as the table name.
2378                If an `Expression` instance is passed, this is used as-is.
2379            as_: the SQL code string to parse as the table expression.
2380                If an `Expression` instance is passed, it will be used as-is.
2381            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2382            append: if `True`, add to any existing expressions.
2383                Otherwise, this resets the expressions.
2384            dialect: the dialect used to parse the input expression.
2385            copy: if `False`, modify this expression instance in-place.
2386            opts: other options to use to parse the input expressions.
2387
2388        Returns:
2389            The modified expression.
2390        """
2391        return _apply_cte_builder(
2392            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2393        )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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:
3272    def lock(self, update: bool = True, copy: bool = True) -> Select:
3273        """
3274        Set the locking read mode for this expression.
3275
3276        Examples:
3277            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3278            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3279
3280            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3281            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3282
3283        Args:
3284            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3285            copy: if `False`, modify this expression instance in-place.
3286
3287        Returns:
3288            The modified expression.
3289        """
3290        inst = maybe_copy(self, copy)
3291        inst.set("locks", [Lock(update=update)])
3292
3293        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:
3295    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3296        """
3297        Set hints for this expression.
3298
3299        Examples:
3300            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3301            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3302
3303        Args:
3304            hints: The SQL code strings to parse as the hints.
3305                If an `Expression` instance is passed, it will be used as-is.
3306            dialect: The dialect used to parse the hints.
3307            copy: If `False`, modify this expression instance in-place.
3308
3309        Returns:
3310            The modified expression.
3311        """
3312        inst = maybe_copy(self, copy)
3313        inst.set(
3314            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3315        )
3316
3317        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):
3332class Subquery(DerivedTable, Unionable):
3333    arg_types = {
3334        "this": True,
3335        "alias": False,
3336        "with": False,
3337        **QUERY_MODIFIERS,
3338    }
3339
3340    def unnest(self):
3341        """
3342        Returns the first non subquery.
3343        """
3344        expression = self
3345        while isinstance(expression, Subquery):
3346            expression = expression.this
3347        return expression
3348
3349    def unwrap(self) -> Subquery:
3350        expression = self
3351        while expression.same_parent and expression.is_wrapper:
3352            expression = t.cast(Subquery, expression.parent)
3353        return expression
3354
3355    @property
3356    def is_wrapper(self) -> bool:
3357        """
3358        Whether this Subquery acts as a simple wrapper around another expression.
3359
3360        SELECT * FROM (((SELECT * FROM t)))
3361                      ^
3362                      This corresponds to a "wrapper" Subquery node
3363        """
3364        return all(v is None for k, v in self.args.items() if k != "this")
3365
3366    @property
3367    def is_star(self) -> bool:
3368        return self.this.is_star
3369
3370    @property
3371    def output_name(self) -> str:
3372        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):
3340    def unnest(self):
3341        """
3342        Returns the first non subquery.
3343        """
3344        expression = self
3345        while isinstance(expression, Subquery):
3346            expression = expression.this
3347        return expression

Returns the first non subquery.

def unwrap(self) -> Subquery:
3349    def unwrap(self) -> Subquery:
3350        expression = self
3351        while expression.same_parent and expression.is_wrapper:
3352            expression = t.cast(Subquery, expression.parent)
3353        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):
3375class TableSample(Expression):
3376    arg_types = {
3377        "this": False,
3378        "expressions": False,
3379        "method": False,
3380        "bucket_numerator": False,
3381        "bucket_denominator": False,
3382        "bucket_field": False,
3383        "percent": False,
3384        "rows": False,
3385        "size": False,
3386        "seed": False,
3387        "kind": False,
3388    }
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):
3391class Tag(Expression):
3392    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3393
3394    arg_types = {
3395        "this": False,
3396        "prefix": False,
3397        "postfix": False,
3398    }

Tags are used for generating arbitrary sql like SELECT x.

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

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

key = 'kwarg'
class Like(Binary, Predicate):
3886class Like(Binary, Predicate):
3887    pass
key = 'like'
class LikeAny(Binary, Predicate):
3890class LikeAny(Binary, Predicate):
3891    pass
key = 'likeany'
class LT(Binary, Predicate):
3894class LT(Binary, Predicate):
3895    pass
key = 'lt'
class LTE(Binary, Predicate):
3898class LTE(Binary, Predicate):
3899    pass
key = 'lte'
class Mod(Binary):
3902class Mod(Binary):
3903    pass
key = 'mod'
class Mul(Binary):
3906class Mul(Binary):
3907    pass
key = 'mul'
class NEQ(Binary, Predicate):
3910class NEQ(Binary, Predicate):
3911    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3914class SimilarTo(Binary, Predicate):
3915    pass
key = 'similarto'
class Slice(Binary):
3918class Slice(Binary):
3919    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3922class Sub(Binary):
3923    pass
key = 'sub'
class ArrayOverlaps(Binary):
3926class ArrayOverlaps(Binary):
3927    pass
key = 'arrayoverlaps'
class Unary(Condition):
3932class Unary(Condition):
3933    pass
key = 'unary'
class BitwiseNot(Unary):
3936class BitwiseNot(Unary):
3937    pass
key = 'bitwisenot'
class Not(Unary):
3940class Not(Unary):
3941    pass
key = 'not'
class Paren(Unary):
3944class Paren(Unary):
3945    arg_types = {"this": True, "with": False}
3946
3947    @property
3948    def output_name(self) -> str:
3949        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):
3952class Neg(Unary):
3953    pass
key = 'neg'
class Alias(Expression):
3956class Alias(Expression):
3957    arg_types = {"this": True, "alias": False}
3958
3959    @property
3960    def output_name(self) -> str:
3961        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):
3964class Aliases(Expression):
3965    arg_types = {"this": True, "expressions": True}
3966
3967    @property
3968    def aliases(self):
3969        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3972class AtTimeZone(Expression):
3973    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3976class Between(Predicate):
3977    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3980class Bracket(Condition):
3981    arg_types = {"this": True, "expressions": True}
3982
3983    @property
3984    def output_name(self) -> str:
3985        if len(self.expressions) == 1:
3986            return self.expressions[0].output_name
3987
3988        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):
3991class SafeBracket(Bracket):
3992    """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):
3995class Distinct(Expression):
3996    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3999class In(Predicate):
4000    arg_types = {
4001        "this": True,
4002        "expressions": False,
4003        "query": False,
4004        "unnest": False,
4005        "field": False,
4006        "is_global": False,
4007    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
4010class TimeUnit(Expression):
4011    """Automatically converts unit arg into a var."""
4012
4013    arg_types = {"unit": False}
4014
4015    def __init__(self, **args):
4016        unit = args.get("unit")
4017        if isinstance(unit, (Column, Literal)):
4018            args["unit"] = Var(this=unit.name)
4019        elif isinstance(unit, Week):
4020            unit.set("this", Var(this=unit.this.name))
4021
4022        super().__init__(**args)
4023
4024    @property
4025    def unit(self) -> t.Optional[Var]:
4026        return self.args.get("unit")

Automatically converts unit arg into a var.

TimeUnit(**args)
4015    def __init__(self, **args):
4016        unit = args.get("unit")
4017        if isinstance(unit, (Column, Literal)):
4018            args["unit"] = Var(this=unit.name)
4019        elif isinstance(unit, Week):
4020            unit.set("this", Var(this=unit.this.name))
4021
4022        super().__init__(**args)
arg_types = {'unit': False}
unit: Optional[Var]
key = 'timeunit'
class IntervalSpan(Expression):
4032class IntervalSpan(Expression):
4033    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'intervalspan'
class Interval(TimeUnit):
4036class Interval(TimeUnit):
4037    arg_types = {"this": False, "unit": False}
arg_types = {'this': False, 'unit': False}
key = 'interval'
class IgnoreNulls(Expression):
4040class IgnoreNulls(Expression):
4041    pass
key = 'ignorenulls'
class RespectNulls(Expression):
4044class RespectNulls(Expression):
4045    pass
key = 'respectnulls'
class Func(Condition):
4049class Func(Condition):
4050    """
4051    The base class for all function expressions.
4052
4053    Attributes:
4054        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
4055            treated as a variable length argument and the argument's value will be stored as a list.
4056        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
4057            for this function expression. These values are used to map this node to a name during parsing
4058            as well as to provide the function's name during SQL string generation. By default the SQL
4059            name is set to the expression's class name transformed to snake case.
4060    """
4061
4062    is_var_len_args = False
4063
4064    @classmethod
4065    def from_arg_list(cls, args):
4066        if cls.is_var_len_args:
4067            all_arg_keys = list(cls.arg_types)
4068            # If this function supports variable length argument treat the last argument as such.
4069            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4070            num_non_var = len(non_var_len_arg_keys)
4071
4072            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4073            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4074        else:
4075            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4076
4077        return cls(**args_dict)
4078
4079    @classmethod
4080    def sql_names(cls):
4081        if cls is Func:
4082            raise NotImplementedError(
4083                "SQL name is only supported by concrete function implementations"
4084            )
4085        if "_sql_names" not in cls.__dict__:
4086            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4087        return cls._sql_names
4088
4089    @classmethod
4090    def sql_name(cls):
4091        return cls.sql_names()[0]
4092
4093    @classmethod
4094    def default_parser_mappings(cls):
4095        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):
4064    @classmethod
4065    def from_arg_list(cls, args):
4066        if cls.is_var_len_args:
4067            all_arg_keys = list(cls.arg_types)
4068            # If this function supports variable length argument treat the last argument as such.
4069            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4070            num_non_var = len(non_var_len_arg_keys)
4071
4072            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4073            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4074        else:
4075            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4076
4077        return cls(**args_dict)
@classmethod
def sql_names(cls):
4079    @classmethod
4080    def sql_names(cls):
4081        if cls is Func:
4082            raise NotImplementedError(
4083                "SQL name is only supported by concrete function implementations"
4084            )
4085        if "_sql_names" not in cls.__dict__:
4086            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4087        return cls._sql_names
@classmethod
def sql_name(cls):
4089    @classmethod
4090    def sql_name(cls):
4091        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
4093    @classmethod
4094    def default_parser_mappings(cls):
4095        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
4098class AggFunc(Func):
4099    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
4102class ParameterizedAgg(AggFunc):
4103    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
4106class Abs(Func):
4107    pass
key = 'abs'
class Transform(Func):
4111class Transform(Func):
4112    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
4115class Anonymous(Func):
4116    arg_types = {"this": True, "expressions": False}
4117    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
4122class Hll(AggFunc):
4123    arg_types = {"this": True, "expressions": False}
4124    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
4127class ApproxDistinct(AggFunc):
4128    arg_types = {"this": True, "accuracy": False}
4129    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
4132class Array(Func):
4133    arg_types = {"expressions": False}
4134    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
4138class ToChar(Func):
4139    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
4142class GenerateSeries(Func):
4143    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
4146class ArrayAgg(AggFunc):
4147    pass
key = 'arrayagg'
class ArrayAll(Func):
4150class ArrayAll(Func):
4151    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4154class ArrayAny(Func):
4155    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4158class ArrayConcat(Func):
4159    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4160    arg_types = {"this": True, "expressions": False}
4161    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4164class ArrayContains(Binary, Func):
4165    pass
key = 'arraycontains'
class ArrayContained(Binary):
4168class ArrayContained(Binary):
4169    pass
key = 'arraycontained'
class ArrayFilter(Func):
4172class ArrayFilter(Func):
4173    arg_types = {"this": True, "expression": True}
4174    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4177class ArrayJoin(Func):
4178    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4181class ArraySize(Func):
4182    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4185class ArraySort(Func):
4186    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4189class ArraySum(Func):
4190    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4193class ArrayUnionAgg(AggFunc):
4194    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4197class Avg(AggFunc):
4198    pass
key = 'avg'
class AnyValue(AggFunc):
4201class AnyValue(AggFunc):
4202    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):
4205class First(Func):
4206    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4209class Last(Func):
4210    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4213class Case(Func):
4214    arg_types = {"this": False, "ifs": True, "default": False}
4215
4216    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4217        instance = maybe_copy(self, copy)
4218        instance.append(
4219            "ifs",
4220            If(
4221                this=maybe_parse(condition, copy=copy, **opts),
4222                true=maybe_parse(then, copy=copy, **opts),
4223            ),
4224        )
4225        return instance
4226
4227    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4228        instance = maybe_copy(self, copy)
4229        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4230        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:
4216    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4217        instance = maybe_copy(self, copy)
4218        instance.append(
4219            "ifs",
4220            If(
4221                this=maybe_parse(condition, copy=copy, **opts),
4222                true=maybe_parse(then, copy=copy, **opts),
4223            ),
4224        )
4225        return instance
def else_( self, condition: Union[str, Expression], copy: bool = True, **opts) -> Case:
4227    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4228        instance = maybe_copy(self, copy)
4229        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4230        return instance
key = 'case'
class Cast(Func):
4233class Cast(Func):
4234    arg_types = {"this": True, "to": True, "format": False}
4235
4236    @property
4237    def name(self) -> str:
4238        return self.this.name
4239
4240    @property
4241    def to(self) -> DataType:
4242        return self.args["to"]
4243
4244    @property
4245    def output_name(self) -> str:
4246        return self.name
4247
4248    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4249        """
4250        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4251        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4252        array<int> != array<float>.
4253
4254        Args:
4255            dtypes: the data types to compare this Cast's DataType to.
4256
4257        Returns:
4258            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4259        """
4260        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:
4248    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4249        """
4250        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4251        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4252        array<int> != array<float>.
4253
4254        Args:
4255            dtypes: the data types to compare this Cast's DataType to.
4256
4257        Returns:
4258            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4259        """
4260        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):
4263class TryCast(Cast):
4264    pass
key = 'trycast'
class CastToStrType(Func):
4267class CastToStrType(Func):
4268    arg_types = {"this": True, "to": True}
arg_types = {'this': True, 'to': True}
key = 'casttostrtype'
class Collate(Binary):
4271class Collate(Binary):
4272    pass
key = 'collate'
class Ceil(Func):
4275class Ceil(Func):
4276    arg_types = {"this": True, "decimals": False}
4277    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4280class Coalesce(Func):
4281    arg_types = {"this": True, "expressions": False}
4282    is_var_len_args = True
4283    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4286class Concat(Func):
4287    arg_types = {"expressions": True}
4288    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4291class SafeConcat(Concat):
4292    pass
key = 'safeconcat'
class ConcatWs(Concat):
4295class ConcatWs(Concat):
4296    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4299class Count(AggFunc):
4300    arg_types = {"this": False, "expressions": False}
4301    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4304class CountIf(AggFunc):
4305    pass
key = 'countif'
class CurrentDate(Func):
4308class CurrentDate(Func):
4309    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4312class CurrentDatetime(Func):
4313    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4316class CurrentTime(Func):
4317    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4320class CurrentTimestamp(Func):
4321    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4324class CurrentUser(Func):
4325    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4328class DateAdd(Func, TimeUnit):
4329    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4332class DateSub(Func, TimeUnit):
4333    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4336class DateDiff(Func, TimeUnit):
4337    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4338    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4341class DateTrunc(Func):
4342    arg_types = {"unit": True, "this": True, "zone": False}
4343
4344    @property
4345    def unit(self) -> Expression:
4346        return self.args["unit"]
arg_types = {'unit': True, 'this': True, 'zone': False}
unit: Expression
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4349class DatetimeAdd(Func, TimeUnit):
4350    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4353class DatetimeSub(Func, TimeUnit):
4354    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4357class DatetimeDiff(Func, TimeUnit):
4358    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4361class DatetimeTrunc(Func, TimeUnit):
4362    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4365class DayOfWeek(Func):
4366    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4369class DayOfMonth(Func):
4370    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4373class DayOfYear(Func):
4374    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4377class WeekOfYear(Func):
4378    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4381class MonthsBetween(Func):
4382    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4385class LastDateOfMonth(Func):
4386    pass
key = 'lastdateofmonth'
class Extract(Func):
4389class Extract(Func):
4390    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class Timestamp(Func):
4393class Timestamp(Func):
4394    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'timestamp'
class TimestampAdd(Func, TimeUnit):
4397class TimestampAdd(Func, TimeUnit):
4398    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4401class TimestampSub(Func, TimeUnit):
4402    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4405class TimestampDiff(Func, TimeUnit):
4406    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4409class TimestampTrunc(Func, TimeUnit):
4410    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4413class TimeAdd(Func, TimeUnit):
4414    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4417class TimeSub(Func, TimeUnit):
4418    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4421class TimeDiff(Func, TimeUnit):
4422    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4425class TimeTrunc(Func, TimeUnit):
4426    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4429class DateFromParts(Func):
4430    _sql_names = ["DATEFROMPARTS"]
4431    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4434class DateStrToDate(Func):
4435    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4438class DateToDateStr(Func):
4439    pass
key = 'datetodatestr'
class DateToDi(Func):
4442class DateToDi(Func):
4443    pass
key = 'datetodi'
class Date(Func):
4447class Date(Func):
4448    arg_types = {"this": False, "zone": False, "expressions": False}
4449    is_var_len_args = True
arg_types = {'this': False, 'zone': False, 'expressions': False}
is_var_len_args = True
key = 'date'
class Day(Func):
4452class Day(Func):
4453    pass
key = 'day'
class Decode(Func):
4456class Decode(Func):
4457    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4460class DiToDate(Func):
4461    pass
key = 'ditodate'
class Encode(Func):
4464class Encode(Func):
4465    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4468class Exp(Func):
4469    pass
key = 'exp'
class Explode(Func):
4472class Explode(Func):
4473    pass
key = 'explode'
class Floor(Func):
4476class Floor(Func):
4477    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4480class FromBase64(Func):
4481    pass
key = 'frombase64'
class ToBase64(Func):
4484class ToBase64(Func):
4485    pass
key = 'tobase64'
class Greatest(Func):
4488class Greatest(Func):
4489    arg_types = {"this": True, "expressions": False}
4490    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(AggFunc):
4493class GroupConcat(AggFunc):
4494    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4497class Hex(Func):
4498    pass
key = 'hex'
class Xor(Connector, Func):
4501class Xor(Connector, Func):
4502    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4505class If(Func):
4506    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4509class Initcap(Func):
4510    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4513class IsNan(Func):
4514    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class FormatJson(Expression):
4517class FormatJson(Expression):
4518    pass
key = 'formatjson'
class JSONKeyValue(Expression):
4521class JSONKeyValue(Expression):
4522    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4525class JSONObject(Func):
4526    arg_types = {
4527        "expressions": False,
4528        "null_handling": False,
4529        "unique_keys": False,
4530        "return_type": False,
4531        "encoding": False,
4532    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'encoding': False}
key = 'jsonobject'
class JSONArray(Func):
4536class JSONArray(Func):
4537    arg_types = {
4538        "expressions": True,
4539        "null_handling": False,
4540        "return_type": False,
4541        "strict": False,
4542    }
arg_types = {'expressions': True, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarray'
class JSONArrayAgg(Func):
4546class JSONArrayAgg(Func):
4547    arg_types = {
4548        "this": True,
4549        "order": False,
4550        "null_handling": False,
4551        "return_type": False,
4552        "strict": False,
4553    }
arg_types = {'this': True, 'order': False, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarrayagg'
class JSONColumnDef(Expression):
4558class JSONColumnDef(Expression):
4559    arg_types = {"this": True, "kind": False, "path": False}
arg_types = {'this': True, 'kind': False, 'path': False}
key = 'jsoncolumndef'
class JSONTable(Func):
4563class JSONTable(Func):
4564    arg_types = {
4565        "this": True,
4566        "expressions": True,
4567        "path": False,
4568        "error_handling": False,
4569        "empty_handling": False,
4570    }
arg_types = {'this': True, 'expressions': True, 'path': False, 'error_handling': False, 'empty_handling': False}
key = 'jsontable'
class OpenJSONColumnDef(Expression):
4573class OpenJSONColumnDef(Expression):
4574    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):
4577class OpenJSON(Func):
4578    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4581class JSONBContains(Binary):
4582    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4585class JSONExtract(Binary, Func):
4586    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4589class JSONExtractScalar(JSONExtract):
4590    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4593class JSONBExtract(JSONExtract):
4594    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4597class JSONBExtractScalar(JSONExtract):
4598    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4601class JSONFormat(Func):
4602    arg_types = {"this": False, "options": False}
4603    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4607class JSONArrayContains(Binary, Predicate, Func):
4608    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class ParseJSON(Func):
4611class ParseJSON(Func):
4612    # BigQuery, Snowflake have PARSE_JSON, Presto has JSON_PARSE
4613    _sql_names = ["PARSE_JSON", "JSON_PARSE"]
key = 'parsejson'
class Least(Func):
4616class Least(Func):
4617    arg_types = {"this": True, "expressions": False}
4618    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4621class Left(Func):
4622    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4629class Length(Func):
4630    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4633class Levenshtein(Func):
4634    arg_types = {
4635        "this": True,
4636        "expression": False,
4637        "ins_cost": False,
4638        "del_cost": False,
4639        "sub_cost": False,
4640    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4643class Ln(Func):
4644    pass
key = 'ln'
class Log(Func):
4647class Log(Func):
4648    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4651class Log2(Func):
4652    pass
key = 'log2'
class Log10(Func):
4655class Log10(Func):
4656    pass
key = 'log10'
class LogicalOr(AggFunc):
4659class LogicalOr(AggFunc):
4660    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4663class LogicalAnd(AggFunc):
4664    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4667class Lower(Func):
4668    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4671class Map(Func):
4672    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4675class MapFromEntries(Func):
4676    pass
key = 'mapfromentries'
class StarMap(Func):
4679class StarMap(Func):
4680    pass
key = 'starmap'
class VarMap(Func):
4683class VarMap(Func):
4684    arg_types = {"keys": True, "values": True}
4685    is_var_len_args = True
4686
4687    @property
4688    def keys(self) -> t.List[Expression]:
4689        return self.args["keys"].expressions
4690
4691    @property
4692    def values(self) -> t.List[Expression]:
4693        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):
4697class MatchAgainst(Func):
4698    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4701class Max(AggFunc):
4702    arg_types = {"this": True, "expressions": False}
4703    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4706class MD5(Func):
4707    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4711class MD5Digest(Func):
4712    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4715class Min(AggFunc):
4716    arg_types = {"this": True, "expressions": False}
4717    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4720class Month(Func):
4721    pass
key = 'month'
class Nvl2(Func):
4724class Nvl2(Func):
4725    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4728class Posexplode(Func):
4729    pass
key = 'posexplode'
class Pow(Binary, Func):
4732class Pow(Binary, Func):
4733    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4736class PercentileCont(AggFunc):
4737    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4740class PercentileDisc(AggFunc):
4741    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4744class Quantile(AggFunc):
4745    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4748class ApproxQuantile(Quantile):
4749    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):
4752class RangeN(Func):
4753    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4756class ReadCSV(Func):
4757    _sql_names = ["READ_CSV"]
4758    is_var_len_args = True
4759    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4762class Reduce(Func):
4763    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):
4766class RegexpExtract(Func):
4767    arg_types = {
4768        "this": True,
4769        "expression": True,
4770        "position": False,
4771        "occurrence": False,
4772        "parameters": False,
4773        "group": False,
4774    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4777class RegexpReplace(Func):
4778    arg_types = {
4779        "this": True,
4780        "expression": True,
4781        "replacement": True,
4782        "position": False,
4783        "occurrence": False,
4784        "parameters": False,
4785    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4788class RegexpLike(Binary, Func):
4789    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4792class RegexpILike(Func):
4793    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4798class RegexpSplit(Func):
4799    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4802class Repeat(Func):
4803    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4806class Round(Func):
4807    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4810class RowNumber(Func):
4811    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4814class SafeDivide(Func):
4815    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4818class SetAgg(AggFunc):
4819    pass
key = 'setagg'
class SHA(Func):
4822class SHA(Func):
4823    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4826class SHA2(Func):
4827    _sql_names = ["SHA2"]
4828    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4831class SortArray(Func):
4832    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4835class Split(Func):
4836    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4841class Substring(Func):
4842    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4845class StandardHash(Func):
4846    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4849class StartsWith(Func):
4850    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4851    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4854class StrPosition(Func):
4855    arg_types = {
4856        "this": True,
4857        "substr": True,
4858        "position": False,
4859        "instance": False,
4860    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4863class StrToDate(Func):
4864    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4867class StrToTime(Func):
4868    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4873class StrToUnix(Func):
4874    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
4879class StrToMap(Func):
4880    arg_types = {
4881        "this": True,
4882        "pair_delim": False,
4883        "key_value_delim": False,
4884        "duplicate_resolution_callback": False,
4885    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
4888class NumberToStr(Func):
4889    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
4892class FromBase(Func):
4893    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4896class Struct(Func):
4897    arg_types = {"expressions": True}
4898    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4901class StructExtract(Func):
4902    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Stuff(Func):
4907class Stuff(Func):
4908    _sql_names = ["STUFF", "INSERT"]
4909    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):
4912class Sum(AggFunc):
4913    pass
key = 'sum'
class Sqrt(Func):
4916class Sqrt(Func):
4917    pass
key = 'sqrt'
class Stddev(AggFunc):
4920class Stddev(AggFunc):
4921    pass
key = 'stddev'
class StddevPop(AggFunc):
4924class StddevPop(AggFunc):
4925    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4928class StddevSamp(AggFunc):
4929    pass
key = 'stddevsamp'
class TimeToStr(Func):
4932class TimeToStr(Func):
4933    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
4936class TimeToTimeStr(Func):
4937    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4940class TimeToUnix(Func):
4941    pass
key = 'timetounix'
class TimeStrToDate(Func):
4944class TimeStrToDate(Func):
4945    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4948class TimeStrToTime(Func):
4949    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4952class TimeStrToUnix(Func):
4953    pass
key = 'timestrtounix'
class Trim(Func):
4956class Trim(Func):
4957    arg_types = {
4958        "this": True,
4959        "expression": False,
4960        "position": False,
4961        "collation": False,
4962    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4965class TsOrDsAdd(Func, TimeUnit):
4966    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4969class TsOrDsToDateStr(Func):
4970    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4973class TsOrDsToDate(Func):
4974    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4977class TsOrDiToDi(Func):
4978    pass
key = 'tsorditodi'
class Unhex(Func):
4981class Unhex(Func):
4982    pass
key = 'unhex'
class UnixToStr(Func):
4985class UnixToStr(Func):
4986    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4991class UnixToTime(Func):
4992    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4993
4994    SECONDS = Literal.string("seconds")
4995    MILLIS = Literal.string("millis")
4996    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):
4999class UnixToTimeStr(Func):
5000    pass
key = 'unixtotimestr'
class Upper(Func):
5003class Upper(Func):
5004    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
5007class Variance(AggFunc):
5008    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
5011class VariancePop(AggFunc):
5012    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
5015class Week(Func):
5016    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
5019class XMLTable(Func):
5020    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):
5023class Year(Func):
5024    pass
key = 'year'
class Use(Expression):
5027class Use(Expression):
5028    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
5031class Merge(Expression):
5032    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):
5035class When(Func):
5036    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):
5041class NextValueFor(Func):
5042    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 'ParseJSON'>, <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 'Timestamp'>, <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:
5079def maybe_parse(
5080    sql_or_expression: ExpOrStr,
5081    *,
5082    into: t.Optional[IntoType] = None,
5083    dialect: DialectType = None,
5084    prefix: t.Optional[str] = None,
5085    copy: bool = False,
5086    **opts,
5087) -> Expression:
5088    """Gracefully handle a possible string or expression.
5089
5090    Example:
5091        >>> maybe_parse("1")
5092        (LITERAL this: 1, is_string: False)
5093        >>> maybe_parse(to_identifier("x"))
5094        (IDENTIFIER this: x, quoted: False)
5095
5096    Args:
5097        sql_or_expression: the SQL code string or an expression
5098        into: the SQLGlot Expression to parse into
5099        dialect: the dialect used to parse the input expressions (in the case that an
5100            input expression is a SQL string).
5101        prefix: a string to prefix the sql with before it gets parsed
5102            (automatically includes a space)
5103        copy: whether or not to copy the expression.
5104        **opts: other options to use to parse the input expressions (again, in the case
5105            that an input expression is a SQL string).
5106
5107    Returns:
5108        Expression: the parsed or given expression.
5109    """
5110    if isinstance(sql_or_expression, Expression):
5111        if copy:
5112            return sql_or_expression.copy()
5113        return sql_or_expression
5114
5115    if sql_or_expression is None:
5116        raise ParseError(f"SQL cannot be None")
5117
5118    import sqlglot
5119
5120    sql = str(sql_or_expression)
5121    if prefix:
5122        sql = f"{prefix} {sql}"
5123
5124    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):
5137def maybe_copy(instance, copy=True):
5138    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:
5319def union(
5320    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5321) -> Union:
5322    """
5323    Initializes a syntax tree from one UNION expression.
5324
5325    Example:
5326        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5327        'SELECT * FROM foo UNION 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 Union 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 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:
5347def intersect(
5348    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5349) -> Intersect:
5350    """
5351    Initializes a syntax tree from one INTERSECT expression.
5352
5353    Example:
5354        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5355        'SELECT * FROM foo INTERSECT 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 Intersect 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 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:
5375def except_(
5376    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5377) -> Except:
5378    """
5379    Initializes a syntax tree from one EXCEPT expression.
5380
5381    Example:
5382        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5383        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5384
5385    Args:
5386        left: the SQL code string corresponding to the left-hand side.
5387            If an `Expression` instance is passed, it will be used as-is.
5388        right: the SQL code string corresponding to the right-hand side.
5389            If an `Expression` instance is passed, it will be used as-is.
5390        distinct: set the DISTINCT flag if and only if this is true.
5391        dialect: the dialect used to parse the input expression.
5392        opts: other options to use to parse the input expressions.
5393
5394    Returns:
5395        The new Except instance.
5396    """
5397    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5398    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5399
5400    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:
5403def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5404    """
5405    Initializes a syntax tree from one or multiple SELECT expressions.
5406
5407    Example:
5408        >>> select("col1", "col2").from_("tbl").sql()
5409        'SELECT col1, col2 FROM tbl'
5410
5411    Args:
5412        *expressions: the SQL code string to parse as the expressions of a
5413            SELECT statement. If an Expression instance is passed, this is used as-is.
5414        dialect: the dialect used to parse the input expressions (in the case that an
5415            input expression is a SQL string).
5416        **opts: other options to use to parse the input expressions (again, in the case
5417            that an input expression is a SQL string).
5418
5419    Returns:
5420        Select: the syntax tree for the SELECT statement.
5421    """
5422    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:
5425def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5426    """
5427    Initializes a syntax tree from a FROM expression.
5428
5429    Example:
5430        >>> from_("tbl").select("col1", "col2").sql()
5431        'SELECT col1, col2 FROM tbl'
5432
5433    Args:
5434        *expression: the SQL code string to parse as the FROM expressions of a
5435            SELECT statement. If an Expression instance is passed, this is used as-is.
5436        dialect: the dialect used to parse the input expression (in the case that the
5437            input expression is a SQL string).
5438        **opts: other options to use to parse the input expressions (again, in the case
5439            that the input expression is a SQL string).
5440
5441    Returns:
5442        Select: the syntax tree for the SELECT statement.
5443    """
5444    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:
5447def update(
5448    table: str | Table,
5449    properties: dict,
5450    where: t.Optional[ExpOrStr] = None,
5451    from_: t.Optional[ExpOrStr] = None,
5452    dialect: DialectType = None,
5453    **opts,
5454) -> Update:
5455    """
5456    Creates an update statement.
5457
5458    Example:
5459        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5460        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5461
5462    Args:
5463        *properties: dictionary of properties to set which are
5464            auto converted to sql objects eg None -> NULL
5465        where: sql conditional parsed into a WHERE statement
5466        from_: sql statement parsed into a FROM statement
5467        dialect: the dialect used to parse the input expressions.
5468        **opts: other options to use to parse the input expressions.
5469
5470    Returns:
5471        Update: the syntax tree for the UPDATE statement.
5472    """
5473    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5474    update_expr.set(
5475        "expressions",
5476        [
5477            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5478            for k, v in properties.items()
5479        ],
5480    )
5481    if from_:
5482        update_expr.set(
5483            "from",
5484            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5485        )
5486    if isinstance(where, Condition):
5487        where = Where(this=where)
5488    if where:
5489        update_expr.set(
5490            "where",
5491            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5492        )
5493    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:
5496def delete(
5497    table: ExpOrStr,
5498    where: t.Optional[ExpOrStr] = None,
5499    returning: t.Optional[ExpOrStr] = None,
5500    dialect: DialectType = None,
5501    **opts,
5502) -> Delete:
5503    """
5504    Builds a delete statement.
5505
5506    Example:
5507        >>> delete("my_table", where="id > 1").sql()
5508        'DELETE FROM my_table WHERE id > 1'
5509
5510    Args:
5511        where: sql conditional parsed into a WHERE statement
5512        returning: sql conditional parsed into a RETURNING statement
5513        dialect: the dialect used to parse the input expressions.
5514        **opts: other options to use to parse the input expressions.
5515
5516    Returns:
5517        Delete: the syntax tree for the DELETE statement.
5518    """
5519    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5520    if where:
5521        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5522    if returning:
5523        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5524    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:
5527def insert(
5528    expression: ExpOrStr,
5529    into: ExpOrStr,
5530    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5531    overwrite: t.Optional[bool] = None,
5532    dialect: DialectType = None,
5533    copy: bool = True,
5534    **opts,
5535) -> Insert:
5536    """
5537    Builds an INSERT statement.
5538
5539    Example:
5540        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5541        'INSERT INTO tbl VALUES (1, 2, 3)'
5542
5543    Args:
5544        expression: the sql string or expression of the INSERT statement
5545        into: the tbl to insert data to.
5546        columns: optionally the table's column names.
5547        overwrite: whether to INSERT OVERWRITE or not.
5548        dialect: the dialect used to parse the input expressions.
5549        copy: whether or not to copy the expression.
5550        **opts: other options to use to parse the input expressions.
5551
5552    Returns:
5553        Insert: the syntax tree for the INSERT statement.
5554    """
5555    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5556    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5557
5558    if columns:
5559        this = _apply_list_builder(
5560            *columns,
5561            instance=Schema(this=this),
5562            arg="expressions",
5563            into=Identifier,
5564            copy=False,
5565            dialect=dialect,
5566            **opts,
5567        )
5568
5569    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:
5572def condition(
5573    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5574) -> Condition:
5575    """
5576    Initialize a logical condition expression.
5577
5578    Example:
5579        >>> condition("x=1").sql()
5580        'x = 1'
5581
5582        This is helpful for composing larger logical syntax trees:
5583        >>> where = condition("x=1")
5584        >>> where = where.and_("y=1")
5585        >>> Select().from_("tbl").select("*").where(where).sql()
5586        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5587
5588    Args:
5589        *expression: the SQL code string to parse.
5590            If an Expression instance is passed, this is used as-is.
5591        dialect: the dialect used to parse the input expression (in the case that the
5592            input expression is a SQL string).
5593        copy: Whether or not to copy `expression` (only applies to expressions).
5594        **opts: other options to use to parse the input expressions (again, in the case
5595            that the input expression is a SQL string).
5596
5597    Returns:
5598        The new Condition instance
5599    """
5600    return maybe_parse(
5601        expression,
5602        into=Condition,
5603        dialect=dialect,
5604        copy=copy,
5605        **opts,
5606    )

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:
5609def and_(
5610    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5611) -> Condition:
5612    """
5613    Combine multiple conditions with an AND logical operator.
5614
5615    Example:
5616        >>> and_("x=1", and_("y=1", "z=1")).sql()
5617        'x = 1 AND (y = 1 AND z = 1)'
5618
5619    Args:
5620        *expressions: the SQL code strings to parse.
5621            If an Expression instance is passed, this is used as-is.
5622        dialect: the dialect used to parse the input expression.
5623        copy: whether or not to copy `expressions` (only applies to Expressions).
5624        **opts: other options to use to parse the input expressions.
5625
5626    Returns:
5627        And: the new condition
5628    """
5629    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:
5632def or_(
5633    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5634) -> Condition:
5635    """
5636    Combine multiple conditions with an OR logical operator.
5637
5638    Example:
5639        >>> or_("x=1", or_("y=1", "z=1")).sql()
5640        'x = 1 OR (y = 1 OR z = 1)'
5641
5642    Args:
5643        *expressions: the SQL code strings to parse.
5644            If an Expression instance is passed, this is used as-is.
5645        dialect: the dialect used to parse the input expression.
5646        copy: whether or not to copy `expressions` (only applies to Expressions).
5647        **opts: other options to use to parse the input expressions.
5648
5649    Returns:
5650        Or: the new condition
5651    """
5652    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:
5655def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5656    """
5657    Wrap a condition with a NOT operator.
5658
5659    Example:
5660        >>> not_("this_suit='black'").sql()
5661        "NOT this_suit = 'black'"
5662
5663    Args:
5664        expression: the SQL code string to parse.
5665            If an Expression instance is passed, this is used as-is.
5666        dialect: the dialect used to parse the input expression.
5667        copy: whether to copy the expression or not.
5668        **opts: other options to use to parse the input expressions.
5669
5670    Returns:
5671        The new condition.
5672    """
5673    this = condition(
5674        expression,
5675        dialect=dialect,
5676        copy=copy,
5677        **opts,
5678    )
5679    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:
5682def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5683    """
5684    Wrap an expression in parentheses.
5685
5686    Example:
5687        >>> paren("5 + 3").sql()
5688        '(5 + 3)'
5689
5690    Args:
5691        expression: the SQL code string to parse.
5692            If an Expression instance is passed, this is used as-is.
5693        copy: whether to copy the expression or not.
5694
5695    Returns:
5696        The wrapped expression.
5697    """
5698    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):
5716def to_identifier(name, quoted=None, copy=True):
5717    """Builds an identifier.
5718
5719    Args:
5720        name: The name to turn into an identifier.
5721        quoted: Whether or not force quote the identifier.
5722        copy: Whether or not to copy a passed in Identefier node.
5723
5724    Returns:
5725        The identifier ast node.
5726    """
5727
5728    if name is None:
5729        return None
5730
5731    if isinstance(name, Identifier):
5732        identifier = maybe_copy(name, copy)
5733    elif isinstance(name, str):
5734        identifier = Identifier(
5735            this=name,
5736            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5737        )
5738    else:
5739        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5740    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:
5746def to_interval(interval: str | Literal) -> Interval:
5747    """Builds an interval expression from a string like '1 day' or '5 months'."""
5748    if isinstance(interval, Literal):
5749        if not interval.is_string:
5750            raise ValueError("Invalid interval string.")
5751
5752        interval = interval.this
5753
5754    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5755
5756    if not interval_parts:
5757        raise ValueError("Invalid interval string.")
5758
5759    return Interval(
5760        this=Literal.string(interval_parts.group(1)),
5761        unit=Var(this=interval_parts.group(2)),
5762    )

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

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:
5934def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5935    """Cast an expression to a data type.
5936
5937    Example:
5938        >>> cast('x + 1', 'int').sql()
5939        'CAST(x + 1 AS INT)'
5940
5941    Args:
5942        expression: The expression to cast.
5943        to: The datatype to cast to.
5944
5945    Returns:
5946        The new Cast instance.
5947    """
5948    expression = maybe_parse(expression, **opts)
5949    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:
5952def table_(
5953    table: Identifier | str,
5954    db: t.Optional[Identifier | str] = None,
5955    catalog: t.Optional[Identifier | str] = None,
5956    quoted: t.Optional[bool] = None,
5957    alias: t.Optional[Identifier | str] = None,
5958) -> Table:
5959    """Build a Table.
5960
5961    Args:
5962        table: Table name.
5963        db: Database name.
5964        catalog: Catalog name.
5965        quote: Whether to force quotes on the table's identifiers.
5966        alias: Table's alias.
5967
5968    Returns:
5969        The new Table instance.
5970    """
5971    return Table(
5972        this=to_identifier(table, quoted=quoted) if table else None,
5973        db=to_identifier(db, quoted=quoted) if db else None,
5974        catalog=to_identifier(catalog, quoted=quoted) if catalog else None,
5975        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5976    )

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:
5979def values(
5980    values: t.Iterable[t.Tuple[t.Any, ...]],
5981    alias: t.Optional[str] = None,
5982    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5983) -> Values:
5984    """Build VALUES statement.
5985
5986    Example:
5987        >>> values([(1, '2')]).sql()
5988        "VALUES (1, '2')"
5989
5990    Args:
5991        values: values statements that will be converted to SQL
5992        alias: optional alias
5993        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5994         If either are provided then an alias is also required.
5995
5996    Returns:
5997        Values: the Values expression object
5998    """
5999    if columns and not alias:
6000        raise ValueError("Alias is required when providing columns")
6001
6002    return Values(
6003        expressions=[convert(tup) for tup in values],
6004        alias=(
6005            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
6006            if columns
6007            else (TableAlias(this=to_identifier(alias)) if alias else None)
6008        ),
6009    )

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:
6012def var(name: t.Optional[ExpOrStr]) -> Var:
6013    """Build a SQL variable.
6014
6015    Example:
6016        >>> repr(var('x'))
6017        '(VAR this: x)'
6018
6019        >>> repr(var(column('x', table='y')))
6020        '(VAR this: x)'
6021
6022    Args:
6023        name: The name of the var or an expression who's name will become the var.
6024
6025    Returns:
6026        The new variable node.
6027    """
6028    if not name:
6029        raise ValueError("Cannot convert empty name into var.")
6030
6031    if isinstance(name, Expression):
6032        name = name.name
6033    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:
6036def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
6037    """Build ALTER TABLE... RENAME... expression
6038
6039    Args:
6040        old_name: The old name of the table
6041        new_name: The new name of the table
6042
6043    Returns:
6044        Alter table expression
6045    """
6046    old_table = to_table(old_name)
6047    new_table = to_table(new_name)
6048    return AlterTable(
6049        this=old_table,
6050        actions=[
6051            RenameTable(this=new_table),
6052        ],
6053    )

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:
6056def convert(value: t.Any, copy: bool = False) -> Expression:
6057    """Convert a python value into an expression object.
6058
6059    Raises an error if a conversion is not possible.
6060
6061    Args:
6062        value: A python object.
6063        copy: Whether or not to copy `value` (only applies to Expressions and collections).
6064
6065    Returns:
6066        Expression: the equivalent expression object.
6067    """
6068    if isinstance(value, Expression):
6069        return maybe_copy(value, copy)
6070    if isinstance(value, str):
6071        return Literal.string(value)
6072    if isinstance(value, bool):
6073        return Boolean(this=value)
6074    if value is None or (isinstance(value, float) and math.isnan(value)):
6075        return NULL
6076    if isinstance(value, numbers.Number):
6077        return Literal.number(value)
6078    if isinstance(value, datetime.datetime):
6079        datetime_literal = Literal.string(
6080            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
6081        )
6082        return TimeStrToTime(this=datetime_literal)
6083    if isinstance(value, datetime.date):
6084        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
6085        return DateStrToDate(this=date_literal)
6086    if isinstance(value, tuple):
6087        return Tuple(expressions=[convert(v, copy=copy) for v in value])
6088    if isinstance(value, list):
6089        return Array(expressions=[convert(v, copy=copy) for v in value])
6090    if isinstance(value, dict):
6091        return Map(
6092            keys=Array(expressions=[convert(k, copy=copy) for k in value]),
6093            values=Array(expressions=[convert(v, copy=copy) for v in value.values()]),
6094        )
6095    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:
6098def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
6099    """
6100    Replace children of an expression with the result of a lambda fun(child) -> exp.
6101    """
6102    for k, v in expression.args.items():
6103        is_list_arg = type(v) is list
6104
6105        child_nodes = v if is_list_arg else [v]
6106        new_child_nodes = []
6107
6108        for cn in child_nodes:
6109            if isinstance(cn, Expression):
6110                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
6111                    new_child_nodes.append(child_node)
6112                    child_node.parent = expression
6113                    child_node.arg_key = k
6114            else:
6115                new_child_nodes.append(cn)
6116
6117        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]:
6120def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
6121    """
6122    Return all table names referenced through columns in an expression.
6123
6124    Example:
6125        >>> import sqlglot
6126        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
6127        ['a', 'c']
6128
6129    Args:
6130        expression: expression to find table names.
6131        exclude: a table name to exclude
6132
6133    Returns:
6134        A list of unique names.
6135    """
6136    return {
6137        table
6138        for table in (column.table for column in expression.find_all(Column))
6139        if table and table != exclude
6140    }

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:
6143def table_name(table: Table | str, dialect: DialectType = None) -> str:
6144    """Get the full name of a table as a string.
6145
6146    Args:
6147        table: Table expression node or string.
6148        dialect: The dialect to generate the table name for.
6149
6150    Examples:
6151        >>> from sqlglot import exp, parse_one
6152        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
6153        'a.b.c'
6154
6155    Returns:
6156        The table name.
6157    """
6158
6159    table = maybe_parse(table, into=Table)
6160
6161    if not table:
6162        raise ValueError(f"Cannot parse {table}")
6163
6164    return ".".join(
6165        part.sql(dialect=dialect, identify=True)
6166        if not SAFE_IDENTIFIER_RE.match(part.name)
6167        else part.name
6168        for part in table.parts
6169    )

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

Returns a true Boolean expression.

def false() -> Boolean:
6327def false() -> Boolean:
6328    """
6329    Returns a false Boolean expression.
6330    """
6331    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> Null:
6334def null() -> Null:
6335    """
6336    Returns a Null expression.
6337    """
6338    return Null()

Returns a Null expression.

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