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

Retrieves the argument with key "this".

expression: Any

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        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):
261    def copy(self):
262        """
263        Returns a deep copy of the expression.
264        """
265        new = deepcopy(self)
266        new.parent = self.parent
267        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
269    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
270        if self.comments is None:
271            self.comments = []
272        if comments:
273            for comment in comments:
274                _, *meta = comment.split(SQLGLOT_META)
275                if meta:
276                    for kv in "".join(meta).split(","):
277                        k, *v = kv.split("=")
278                        value = v[0].strip() if v else True
279                        self.meta[k.strip()] = value
280                self.comments.append(comment)
def append(self, arg_key: str, value: Any) -> None:
282    def append(self, arg_key: str, value: t.Any) -> None:
283        """
284        Appends value to arg_key if it's a list or sets it as a new list.
285
286        Args:
287            arg_key (str): name of the list expression arg
288            value (Any): value to append to the list
289        """
290        if not isinstance(self.args.get(arg_key), list):
291            self.args[arg_key] = []
292        self.args[arg_key].append(value)
293        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:
295    def set(self, arg_key: str, value: t.Any) -> None:
296        """
297        Sets arg_key to value.
298
299        Args:
300            arg_key: name of the expression arg.
301            value: value to set the arg to.
302        """
303        if value is None:
304            self.args.pop(arg_key, None)
305            return
306
307        self.args[arg_key] = value
308        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]]:
329    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
330        """Yields the key and expression for all arguments, exploding list args."""
331        for k, vs in self.args.items():
332            if type(vs) is list:
333                for v in vs:
334                    if hasattr(v, "parent"):
335                        yield k, v
336            else:
337                if hasattr(vs, "parent"):
338                    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]:
340    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
341        """
342        Returns the first node in this tree which matches at least one of
343        the specified types.
344
345        Args:
346            expression_types: the expression type(s) to match.
347            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
348
349        Returns:
350            The node which matches the criteria or None if no such node was found.
351        """
352        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]:
354    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
355        """
356        Returns a generator object which visits all nodes in this tree and only
357        yields those that match at least one of the specified expression types.
358
359        Args:
360            expression_types: the expression type(s) to match.
361            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
362
363        Returns:
364            The generator object.
365        """
366        for expression, *_ in self.walk(bfs=bfs):
367            if isinstance(expression, expression_types):
368                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]:
370    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
371        """
372        Returns a nearest parent matching expression_types.
373
374        Args:
375            expression_types: the expression type(s) to match.
376
377        Returns:
378            The parent node.
379        """
380        ancestor = self.parent
381        while ancestor and not isinstance(ancestor, expression_types):
382            ancestor = ancestor.parent
383        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:
397    def root(self) -> Expression:
398        """
399        Returns the root expression of this tree.
400        """
401        expression = self
402        while expression.parent:
403            expression = expression.parent
404        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
406    def walk(self, bfs=True, prune=None):
407        """
408        Returns a generator object which visits all nodes in this tree.
409
410        Args:
411            bfs (bool): if set to True the BFS traversal order will be applied,
412                otherwise the DFS traversal will be used instead.
413            prune ((node, parent, arg_key) -> bool): callable that returns True if
414                the generator should stop traversing this branch of the tree.
415
416        Returns:
417            the generator object.
418        """
419        if bfs:
420            yield from self.bfs(prune=prune)
421        else:
422            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):
424    def dfs(self, parent=None, key=None, prune=None):
425        """
426        Returns a generator object which visits all nodes in this tree in
427        the DFS (Depth-first) order.
428
429        Returns:
430            The generator object.
431        """
432        parent = parent or self.parent
433        yield self, parent, key
434        if prune and prune(self, parent, key):
435            return
436
437        for k, v in self.iter_expressions():
438            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):
440    def bfs(self, prune=None):
441        """
442        Returns a generator object which visits all nodes in this tree in
443        the BFS (Breadth-first) order.
444
445        Returns:
446            The generator object.
447        """
448        queue = deque([(self, self.parent, None)])
449
450        while queue:
451            item, parent, key = queue.popleft()
452
453            yield item, parent, key
454            if prune and prune(item, parent, key):
455                continue
456
457            for k, v in item.iter_expressions():
458                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):
460    def unnest(self):
461        """
462        Returns the first non parenthesis child or self.
463        """
464        expression = self
465        while type(expression) is Paren:
466            expression = expression.this
467        return expression

Returns the first non parenthesis child or self.

def unalias(self):
469    def unalias(self):
470        """
471        Returns the inner expression if this is an Alias.
472        """
473        if isinstance(self, Alias):
474            return self.this
475        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
477    def unnest_operands(self):
478        """
479        Returns unnested operands as a tuple.
480        """
481        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
483    def flatten(self, unnest=True):
484        """
485        Returns a generator which yields child nodes who's parents are the same class.
486
487        A AND B AND C -> [A, B, C]
488        """
489        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
490            if not type(node) is self.__class__:
491                yield node.unnest() if unnest and not isinstance(node, Subquery) 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:
499    def sql(self, dialect: DialectType = None, **opts) -> str:
500        """
501        Returns SQL string representation of this tree.
502
503        Args:
504            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
505            opts: other `sqlglot.generator.Generator` options.
506
507        Returns:
508            The SQL string.
509        """
510        from sqlglot.dialects import Dialect
511
512        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):
538    def transform(self, fun, *args, copy=True, **kwargs):
539        """
540        Recursively visits all tree nodes (excluding already transformed ones)
541        and applies the given transformation function to each node.
542
543        Args:
544            fun (function): a function which takes a node as an argument and returns a
545                new transformed node or the same node without modifications. If the function
546                returns None, then the corresponding node will be removed from the syntax tree.
547            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
548                modified in place.
549
550        Returns:
551            The transformed tree.
552        """
553        node = self.copy() if copy else self
554        new_node = fun(node, *args, **kwargs)
555
556        if new_node is None or not isinstance(new_node, Expression):
557            return new_node
558        if new_node is not node:
559            new_node.parent = node.parent
560            return new_node
561
562        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
563        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):
573    def replace(self, expression):
574        """
575        Swap out this expression with a new expression.
576
577        For example::
578
579            >>> tree = Select().select("x").from_("tbl")
580            >>> tree.find(Column).replace(Column(this="y"))
581            (COLUMN this: y)
582            >>> tree.sql()
583            'SELECT y FROM tbl'
584
585        Args:
586            expression: new node
587
588        Returns:
589            The new expression or expressions.
590        """
591        if not self.parent:
592            return expression
593
594        parent = self.parent
595        self.parent = None
596
597        replace_children(parent, lambda child: expression if child is self else child)
598        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:
600    def pop(self: E) -> E:
601        """
602        Remove this expression from its AST.
603
604        Returns:
605            The popped expression.
606        """
607        self.replace(None)
608        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_: Type[~E]) -> ~E:
610    def assert_is(self, type_: t.Type[E]) -> E:
611        """
612        Assert that this `Expression` is an instance of `type_`.
613
614        If it is NOT an instance of `type_`, this raises an assertion error.
615        Otherwise, this returns this expression.
616
617        Examples:
618            This is useful for type security in chained expressions:
619
620            >>> import sqlglot
621            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
622            'SELECT x, z FROM y'
623        """
624        assert isinstance(self, type_)
625        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]:
627    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
628        """
629        Checks if this expression is valid (e.g. all mandatory args are set).
630
631        Args:
632            args: a sequence of values that were used to instantiate a Func expression. This is used
633                to check that the provided arguments don't exceed the function argument limit.
634
635        Returns:
636            A list of error messages for all possible errors that were found.
637        """
638        errors: t.List[str] = []
639
640        for k in self.args:
641            if k not in self.arg_types:
642                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
643        for k, mandatory in self.arg_types.items():
644            v = self.args.get(k)
645            if mandatory and (v is None or (isinstance(v, list) and not v)):
646                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
647
648        if (
649            args
650            and isinstance(self, Func)
651            and len(args) > len(self.arg_types)
652            and not self.is_var_len_args
653        ):
654            errors.append(
655                f"The number of provided arguments ({len(args)}) is greater than "
656                f"the maximum number of supported arguments ({len(self.arg_types)})"
657            )
658
659        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):
661    def dump(self):
662        """
663        Dump this Expression to a JSON-serializable dict.
664        """
665        from sqlglot.serde import dump
666
667        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
669    @classmethod
670    def load(cls, obj):
671        """
672        Load a dict (as returned by `Expression.dump`) into an Expression instance.
673        """
674        from sqlglot.serde import load
675
676        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:
678    def and_(
679        self,
680        *expressions: t.Optional[ExpOrStr],
681        dialect: DialectType = None,
682        copy: bool = True,
683        **opts,
684    ) -> Condition:
685        """
686        AND this condition with one or multiple expressions.
687
688        Example:
689            >>> condition("x=1").and_("y=1").sql()
690            'x = 1 AND y = 1'
691
692        Args:
693            *expressions: the SQL code strings to parse.
694                If an `Expression` instance is passed, it will be used as-is.
695            dialect: the dialect used to parse the input expression.
696            copy: whether or not to copy the involved expressions (only applies to Expressions).
697            opts: other options to use to parse the input expressions.
698
699        Returns:
700            The new And condition.
701        """
702        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new And condition.

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

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new Or condition.

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

Wrap this condition with NOT.

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

The new Not instance.

def as_( self, alias: str | Identifier, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Alias:
746    def as_(
747        self,
748        alias: str | Identifier,
749        quoted: t.Optional[bool] = None,
750        dialect: DialectType = None,
751        copy: bool = True,
752        **opts,
753    ) -> Alias:
754        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
def isin( self, *expressions: Any, query: Union[str, Expression, NoneType] = None, unnest: Union[str, Expression, NoneType, Collection[Union[str, Expression]]] = None, copy: bool = True, **opts) -> In:
779    def isin(
780        self,
781        *expressions: t.Any,
782        query: t.Optional[ExpOrStr] = None,
783        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
784        copy: bool = True,
785        **opts,
786    ) -> In:
787        return In(
788            this=maybe_copy(self, copy),
789            expressions=[convert(e, copy=copy) for e in expressions],
790            query=maybe_parse(query, copy=copy, **opts) if query else None,
791            unnest=Unnest(
792                expressions=[
793                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
794                ]
795            )
796            if unnest
797            else None,
798        )
def between( self, low: Any, high: Any, copy: bool = True, **opts) -> Between:
800    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
801        return Between(
802            this=maybe_copy(self, copy),
803            low=convert(low, copy=copy, **opts),
804            high=convert(high, copy=copy, **opts),
805        )
def is_( self, other: Union[str, Expression]) -> Is:
807    def is_(self, other: ExpOrStr) -> Is:
808        return self._binop(Is, other)
def like( self, other: Union[str, Expression]) -> Like:
810    def like(self, other: ExpOrStr) -> Like:
811        return self._binop(Like, other)
def ilike( self, other: Union[str, Expression]) -> ILike:
813    def ilike(self, other: ExpOrStr) -> ILike:
814        return self._binop(ILike, other)
def eq(self, other: Any) -> EQ:
816    def eq(self, other: t.Any) -> EQ:
817        return self._binop(EQ, other)
def neq(self, other: Any) -> NEQ:
819    def neq(self, other: t.Any) -> NEQ:
820        return self._binop(NEQ, other)
def rlike( self, other: Union[str, Expression]) -> RegexpLike:
822    def rlike(self, other: ExpOrStr) -> RegexpLike:
823        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):
906class Condition(Expression):
907    """Logical conditions like x AND y, or simply x"""

Logical conditions like x AND y, or simply x

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

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

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

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1206class ColumnPosition(Expression):
1207    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1210class ColumnDef(Expression):
1211    arg_types = {
1212        "this": True,
1213        "kind": False,
1214        "constraints": False,
1215        "exists": False,
1216        "position": False,
1217    }
1218
1219    @property
1220    def constraints(self) -> t.List[ColumnConstraint]:
1221        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):
1224class AlterColumn(Expression):
1225    arg_types = {
1226        "this": True,
1227        "dtype": False,
1228        "collate": False,
1229        "using": False,
1230        "default": False,
1231        "drop": False,
1232    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1235class RenameTable(Expression):
1236    pass
key = 'renametable'
class SwapTable(Expression):
1239class SwapTable(Expression):
1240    pass
key = 'swaptable'
class Comment(Expression):
1243class Comment(Expression):
1244    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):
1247class Comprehension(Expression):
1248    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):
1252class MergeTreeTTLAction(Expression):
1253    arg_types = {
1254        "this": True,
1255        "delete": False,
1256        "recompress": False,
1257        "to_disk": False,
1258        "to_volume": False,
1259    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1263class MergeTreeTTL(Expression):
1264    arg_types = {
1265        "expressions": True,
1266        "where": False,
1267        "group": False,
1268        "aggregates": False,
1269    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class IndexConstraintOption(Expression):
1273class IndexConstraintOption(Expression):
1274    arg_types = {
1275        "key_block_size": False,
1276        "using": False,
1277        "parser": False,
1278        "comment": False,
1279        "visible": False,
1280        "engine_attr": False,
1281        "secondary_engine_attr": False,
1282    }
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):
1285class ColumnConstraint(Expression):
1286    arg_types = {"this": False, "kind": True}
1287
1288    @property
1289    def kind(self) -> ColumnConstraintKind:
1290        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1293class ColumnConstraintKind(Expression):
1294    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1297class AutoIncrementColumnConstraint(ColumnConstraintKind):
1298    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1301class CaseSpecificColumnConstraint(ColumnConstraintKind):
1302    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1305class CharacterSetColumnConstraint(ColumnConstraintKind):
1306    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1309class CheckColumnConstraint(ColumnConstraintKind):
1310    pass
key = 'checkcolumnconstraint'
class ClusteredColumnConstraint(ColumnConstraintKind):
1313class ClusteredColumnConstraint(ColumnConstraintKind):
1314    pass
key = 'clusteredcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1317class CollateColumnConstraint(ColumnConstraintKind):
1318    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1321class CommentColumnConstraint(ColumnConstraintKind):
1322    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1325class CompressColumnConstraint(ColumnConstraintKind):
1326    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1329class DateFormatColumnConstraint(ColumnConstraintKind):
1330    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1333class DefaultColumnConstraint(ColumnConstraintKind):
1334    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1337class EncodeColumnConstraint(ColumnConstraintKind):
1338    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1341class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1342    # this: True -> ALWAYS, this: False -> BY DEFAULT
1343    arg_types = {
1344        "this": False,
1345        "expression": False,
1346        "on_null": False,
1347        "start": False,
1348        "increment": False,
1349        "minvalue": False,
1350        "maxvalue": False,
1351        "cycle": False,
1352    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class IndexColumnConstraint(ColumnConstraintKind):
1356class IndexColumnConstraint(ColumnConstraintKind):
1357    arg_types = {
1358        "this": False,
1359        "schema": True,
1360        "kind": False,
1361        "index_type": False,
1362        "options": False,
1363    }
arg_types = {'this': False, 'schema': True, 'kind': False, 'index_type': False, 'options': False}
key = 'indexcolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1366class InlineLengthColumnConstraint(ColumnConstraintKind):
1367    pass
key = 'inlinelengthcolumnconstraint'
class NonClusteredColumnConstraint(ColumnConstraintKind):
1370class NonClusteredColumnConstraint(ColumnConstraintKind):
1371    pass
key = 'nonclusteredcolumnconstraint'
class NotForReplicationColumnConstraint(ColumnConstraintKind):
1374class NotForReplicationColumnConstraint(ColumnConstraintKind):
1375    arg_types = {}
arg_types = {}
key = 'notforreplicationcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1378class NotNullColumnConstraint(ColumnConstraintKind):
1379    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1383class OnUpdateColumnConstraint(ColumnConstraintKind):
1384    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1387class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1388    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1391class TitleColumnConstraint(ColumnConstraintKind):
1392    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1395class UniqueColumnConstraint(ColumnConstraintKind):
1396    arg_types = {"this": False, "index_type": False}
arg_types = {'this': False, 'index_type': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1399class UppercaseColumnConstraint(ColumnConstraintKind):
1400    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1403class PathColumnConstraint(ColumnConstraintKind):
1404    pass
key = 'pathcolumnconstraint'
class ComputedColumnConstraint(ColumnConstraintKind):
1409class ComputedColumnConstraint(ColumnConstraintKind):
1410    arg_types = {"this": True, "persisted": False, "not_null": False}
arg_types = {'this': True, 'persisted': False, 'not_null': False}
key = 'computedcolumnconstraint'
class Constraint(Expression):
1413class Constraint(Expression):
1414    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1417class Delete(Expression):
1418    arg_types = {
1419        "with": False,
1420        "this": False,
1421        "using": False,
1422        "where": False,
1423        "returning": False,
1424        "limit": False,
1425        "tables": False,  # Multiple-Table Syntax (MySQL)
1426    }
1427
1428    def delete(
1429        self,
1430        table: ExpOrStr,
1431        dialect: DialectType = None,
1432        copy: bool = True,
1433        **opts,
1434    ) -> Delete:
1435        """
1436        Create a DELETE expression or replace the table on an existing DELETE expression.
1437
1438        Example:
1439            >>> delete("tbl").sql()
1440            'DELETE FROM tbl'
1441
1442        Args:
1443            table: the table from which to delete.
1444            dialect: the dialect used to parse the input expression.
1445            copy: if `False`, modify this expression instance in-place.
1446            opts: other options to use to parse the input expressions.
1447
1448        Returns:
1449            Delete: the modified expression.
1450        """
1451        return _apply_builder(
1452            expression=table,
1453            instance=self,
1454            arg="this",
1455            dialect=dialect,
1456            into=Table,
1457            copy=copy,
1458            **opts,
1459        )
1460
1461    def where(
1462        self,
1463        *expressions: t.Optional[ExpOrStr],
1464        append: bool = True,
1465        dialect: DialectType = None,
1466        copy: bool = True,
1467        **opts,
1468    ) -> Delete:
1469        """
1470        Append to or set the WHERE expressions.
1471
1472        Example:
1473            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1474            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1475
1476        Args:
1477            *expressions: the SQL code strings to parse.
1478                If an `Expression` instance is passed, it will be used as-is.
1479                Multiple expressions are combined with an AND operator.
1480            append: if `True`, AND the new expressions to any existing expression.
1481                Otherwise, this resets the expression.
1482            dialect: the dialect used to parse the input expressions.
1483            copy: if `False`, modify this expression instance in-place.
1484            opts: other options to use to parse the input expressions.
1485
1486        Returns:
1487            Delete: the modified expression.
1488        """
1489        return _apply_conjunction_builder(
1490            *expressions,
1491            instance=self,
1492            arg="where",
1493            append=append,
1494            into=Where,
1495            dialect=dialect,
1496            copy=copy,
1497            **opts,
1498        )
1499
1500    def returning(
1501        self,
1502        expression: ExpOrStr,
1503        dialect: DialectType = None,
1504        copy: bool = True,
1505        **opts,
1506    ) -> Delete:
1507        """
1508        Set the RETURNING expression. Not supported by all dialects.
1509
1510        Example:
1511            >>> delete("tbl").returning("*", dialect="postgres").sql()
1512            'DELETE FROM tbl RETURNING *'
1513
1514        Args:
1515            expression: the SQL code strings to parse.
1516                If an `Expression` instance is passed, it will be used as-is.
1517            dialect: the dialect used to parse the input expressions.
1518            copy: if `False`, modify this expression instance in-place.
1519            opts: other options to use to parse the input expressions.
1520
1521        Returns:
1522            Delete: the modified expression.
1523        """
1524        return _apply_builder(
1525            expression=expression,
1526            instance=self,
1527            arg="returning",
1528            prefix="RETURNING",
1529            dialect=dialect,
1530            copy=copy,
1531            into=Returning,
1532            **opts,
1533        )
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:
1428    def delete(
1429        self,
1430        table: ExpOrStr,
1431        dialect: DialectType = None,
1432        copy: bool = True,
1433        **opts,
1434    ) -> Delete:
1435        """
1436        Create a DELETE expression or replace the table on an existing DELETE expression.
1437
1438        Example:
1439            >>> delete("tbl").sql()
1440            'DELETE FROM tbl'
1441
1442        Args:
1443            table: the table from which to delete.
1444            dialect: the dialect used to parse the input expression.
1445            copy: if `False`, modify this expression instance in-place.
1446            opts: other options to use to parse the input expressions.
1447
1448        Returns:
1449            Delete: the modified expression.
1450        """
1451        return _apply_builder(
1452            expression=table,
1453            instance=self,
1454            arg="this",
1455            dialect=dialect,
1456            into=Table,
1457            copy=copy,
1458            **opts,
1459        )

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:
1461    def where(
1462        self,
1463        *expressions: t.Optional[ExpOrStr],
1464        append: bool = True,
1465        dialect: DialectType = None,
1466        copy: bool = True,
1467        **opts,
1468    ) -> Delete:
1469        """
1470        Append to or set the WHERE expressions.
1471
1472        Example:
1473            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1474            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1475
1476        Args:
1477            *expressions: the SQL code strings to parse.
1478                If an `Expression` instance is passed, it will be used as-is.
1479                Multiple expressions are combined with an AND operator.
1480            append: if `True`, AND the new expressions to any existing expression.
1481                Otherwise, this resets the expression.
1482            dialect: the dialect used to parse the input expressions.
1483            copy: if `False`, modify this expression instance in-place.
1484            opts: other options to use to parse the input expressions.
1485
1486        Returns:
1487            Delete: the modified expression.
1488        """
1489        return _apply_conjunction_builder(
1490            *expressions,
1491            instance=self,
1492            arg="where",
1493            append=append,
1494            into=Where,
1495            dialect=dialect,
1496            copy=copy,
1497            **opts,
1498        )

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:
1500    def returning(
1501        self,
1502        expression: ExpOrStr,
1503        dialect: DialectType = None,
1504        copy: bool = True,
1505        **opts,
1506    ) -> Delete:
1507        """
1508        Set the RETURNING expression. Not supported by all dialects.
1509
1510        Example:
1511            >>> delete("tbl").returning("*", dialect="postgres").sql()
1512            'DELETE FROM tbl RETURNING *'
1513
1514        Args:
1515            expression: the SQL code strings to parse.
1516                If an `Expression` instance is passed, it will be used as-is.
1517            dialect: the dialect used to parse the input expressions.
1518            copy: if `False`, modify this expression instance in-place.
1519            opts: other options to use to parse the input expressions.
1520
1521        Returns:
1522            Delete: the modified expression.
1523        """
1524        return _apply_builder(
1525            expression=expression,
1526            instance=self,
1527            arg="returning",
1528            prefix="RETURNING",
1529            dialect=dialect,
1530            copy=copy,
1531            into=Returning,
1532            **opts,
1533        )

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):
1536class Drop(Expression):
1537    arg_types = {
1538        "this": False,
1539        "kind": False,
1540        "exists": False,
1541        "temporary": False,
1542        "materialized": False,
1543        "cascade": False,
1544        "constraints": False,
1545        "purge": False,
1546    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1549class Filter(Expression):
1550    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1553class Check(Expression):
1554    pass
key = 'check'
class Connect(Expression):
1558class Connect(Expression):
1559    arg_types = {"start": False, "connect": True}
arg_types = {'start': False, 'connect': True}
key = 'connect'
class Prior(Expression):
1562class Prior(Expression):
1563    pass
key = 'prior'
class Directory(Expression):
1566class Directory(Expression):
1567    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1568    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1571class ForeignKey(Expression):
1572    arg_types = {
1573        "expressions": True,
1574        "reference": False,
1575        "delete": False,
1576        "update": False,
1577    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class ColumnPrefix(Expression):
1580class ColumnPrefix(Expression):
1581    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'columnprefix'
class PrimaryKey(Expression):
1584class PrimaryKey(Expression):
1585    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1590class Into(Expression):
1591    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1594class From(Expression):
1595    @property
1596    def name(self) -> str:
1597        return self.this.name
1598
1599    @property
1600    def alias_or_name(self) -> str:
1601        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1604class Having(Expression):
1605    pass
key = 'having'
class Hint(Expression):
1608class Hint(Expression):
1609    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1612class JoinHint(Expression):
1613    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1616class Identifier(Expression):
1617    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1618
1619    @property
1620    def quoted(self) -> bool:
1621        return bool(self.args.get("quoted"))
1622
1623    @property
1624    def hashable_args(self) -> t.Any:
1625        return (self.this, self.quoted)
1626
1627    @property
1628    def output_name(self) -> str:
1629        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 Opclass(Expression):
1633class Opclass(Expression):
1634    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'opclass'
class Index(Expression):
1637class Index(Expression):
1638    arg_types = {
1639        "this": False,
1640        "table": False,
1641        "using": False,
1642        "where": False,
1643        "columns": False,
1644        "unique": False,
1645        "primary": False,
1646        "amp": False,  # teradata
1647        "partition_by": False,  # teradata
1648        "where": False,  # postgres partial indexes
1649    }
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):
1652class Insert(DDL):
1653    arg_types = {
1654        "with": False,
1655        "this": True,
1656        "expression": False,
1657        "conflict": False,
1658        "returning": False,
1659        "overwrite": False,
1660        "exists": False,
1661        "partition": False,
1662        "alternative": False,
1663        "where": False,
1664        "ignore": False,
1665        "by_name": False,
1666    }
1667
1668    def with_(
1669        self,
1670        alias: ExpOrStr,
1671        as_: ExpOrStr,
1672        recursive: t.Optional[bool] = None,
1673        append: bool = True,
1674        dialect: DialectType = None,
1675        copy: bool = True,
1676        **opts,
1677    ) -> Insert:
1678        """
1679        Append to or set the common table expressions.
1680
1681        Example:
1682            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1683            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1684
1685        Args:
1686            alias: the SQL code string to parse as the table name.
1687                If an `Expression` instance is passed, this is used as-is.
1688            as_: the SQL code string to parse as the table expression.
1689                If an `Expression` instance is passed, it will be used as-is.
1690            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1691            append: if `True`, add to any existing expressions.
1692                Otherwise, this resets the expressions.
1693            dialect: the dialect used to parse the input expression.
1694            copy: if `False`, modify this expression instance in-place.
1695            opts: other options to use to parse the input expressions.
1696
1697        Returns:
1698            The modified expression.
1699        """
1700        return _apply_cte_builder(
1701            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1702        )
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:
1668    def with_(
1669        self,
1670        alias: ExpOrStr,
1671        as_: ExpOrStr,
1672        recursive: t.Optional[bool] = None,
1673        append: bool = True,
1674        dialect: DialectType = None,
1675        copy: bool = True,
1676        **opts,
1677    ) -> Insert:
1678        """
1679        Append to or set the common table expressions.
1680
1681        Example:
1682            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1683            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1684
1685        Args:
1686            alias: the SQL code string to parse as the table name.
1687                If an `Expression` instance is passed, this is used as-is.
1688            as_: the SQL code string to parse as the table expression.
1689                If an `Expression` instance is passed, it will be used as-is.
1690            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1691            append: if `True`, add to any existing expressions.
1692                Otherwise, this resets the expressions.
1693            dialect: the dialect used to parse the input expression.
1694            copy: if `False`, modify this expression instance in-place.
1695            opts: other options to use to parse the input expressions.
1696
1697        Returns:
1698            The modified expression.
1699        """
1700        return _apply_cte_builder(
1701            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1702        )

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):
1705class OnConflict(Expression):
1706    arg_types = {
1707        "duplicate": False,
1708        "expressions": False,
1709        "nothing": False,
1710        "key": False,
1711        "constraint": False,
1712    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1715class Returning(Expression):
1716    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1720class Introducer(Expression):
1721    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1725class National(Expression):
1726    pass
key = 'national'
class LoadData(Expression):
1729class LoadData(Expression):
1730    arg_types = {
1731        "this": True,
1732        "local": False,
1733        "overwrite": False,
1734        "inpath": True,
1735        "partition": False,
1736        "input_format": False,
1737        "serde": False,
1738    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1741class Partition(Expression):
1742    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1745class Fetch(Expression):
1746    arg_types = {
1747        "direction": False,
1748        "count": False,
1749        "percent": False,
1750        "with_ties": False,
1751    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1754class Group(Expression):
1755    arg_types = {
1756        "expressions": False,
1757        "grouping_sets": False,
1758        "cube": False,
1759        "rollup": False,
1760        "totals": False,
1761        "all": False,
1762    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1765class Lambda(Expression):
1766    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1769class Limit(Expression):
1770    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1773class Literal(Condition):
1774    arg_types = {"this": True, "is_string": True}
1775
1776    @property
1777    def hashable_args(self) -> t.Any:
1778        return (self.this, self.args.get("is_string"))
1779
1780    @classmethod
1781    def number(cls, number) -> Literal:
1782        return cls(this=str(number), is_string=False)
1783
1784    @classmethod
1785    def string(cls, string) -> Literal:
1786        return cls(this=str(string), is_string=True)
1787
1788    @property
1789    def output_name(self) -> str:
1790        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> Literal:
1780    @classmethod
1781    def number(cls, number) -> Literal:
1782        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> Literal:
1784    @classmethod
1785    def string(cls, string) -> Literal:
1786        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):
1793class Join(Expression):
1794    arg_types = {
1795        "this": True,
1796        "on": False,
1797        "side": False,
1798        "kind": False,
1799        "using": False,
1800        "method": False,
1801        "global": False,
1802        "hint": False,
1803    }
1804
1805    @property
1806    def method(self) -> str:
1807        return self.text("method").upper()
1808
1809    @property
1810    def kind(self) -> str:
1811        return self.text("kind").upper()
1812
1813    @property
1814    def side(self) -> str:
1815        return self.text("side").upper()
1816
1817    @property
1818    def hint(self) -> str:
1819        return self.text("hint").upper()
1820
1821    @property
1822    def alias_or_name(self) -> str:
1823        return self.this.alias_or_name
1824
1825    def on(
1826        self,
1827        *expressions: t.Optional[ExpOrStr],
1828        append: bool = True,
1829        dialect: DialectType = None,
1830        copy: bool = True,
1831        **opts,
1832    ) -> Join:
1833        """
1834        Append to or set the ON expressions.
1835
1836        Example:
1837            >>> import sqlglot
1838            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1839            'JOIN x ON y = 1'
1840
1841        Args:
1842            *expressions: the SQL code strings to parse.
1843                If an `Expression` instance is passed, it will be used as-is.
1844                Multiple expressions are combined with an AND operator.
1845            append: if `True`, AND the new expressions to any existing expression.
1846                Otherwise, this resets the expression.
1847            dialect: the dialect used to parse the input expressions.
1848            copy: if `False`, modify this expression instance in-place.
1849            opts: other options to use to parse the input expressions.
1850
1851        Returns:
1852            The modified Join expression.
1853        """
1854        join = _apply_conjunction_builder(
1855            *expressions,
1856            instance=self,
1857            arg="on",
1858            append=append,
1859            dialect=dialect,
1860            copy=copy,
1861            **opts,
1862        )
1863
1864        if join.kind == "CROSS":
1865            join.set("kind", None)
1866
1867        return join
1868
1869    def using(
1870        self,
1871        *expressions: t.Optional[ExpOrStr],
1872        append: bool = True,
1873        dialect: DialectType = None,
1874        copy: bool = True,
1875        **opts,
1876    ) -> Join:
1877        """
1878        Append to or set the USING expressions.
1879
1880        Example:
1881            >>> import sqlglot
1882            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1883            'JOIN x USING (foo, bla)'
1884
1885        Args:
1886            *expressions: the SQL code strings to parse.
1887                If an `Expression` instance is passed, it will be used as-is.
1888            append: if `True`, concatenate the new expressions to the existing "using" list.
1889                Otherwise, this resets the expression.
1890            dialect: the dialect used to parse the input expressions.
1891            copy: if `False`, modify this expression instance in-place.
1892            opts: other options to use to parse the input expressions.
1893
1894        Returns:
1895            The modified Join expression.
1896        """
1897        join = _apply_list_builder(
1898            *expressions,
1899            instance=self,
1900            arg="using",
1901            append=append,
1902            dialect=dialect,
1903            copy=copy,
1904            **opts,
1905        )
1906
1907        if join.kind == "CROSS":
1908            join.set("kind", None)
1909
1910        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:
1825    def on(
1826        self,
1827        *expressions: t.Optional[ExpOrStr],
1828        append: bool = True,
1829        dialect: DialectType = None,
1830        copy: bool = True,
1831        **opts,
1832    ) -> Join:
1833        """
1834        Append to or set the ON expressions.
1835
1836        Example:
1837            >>> import sqlglot
1838            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1839            'JOIN x ON y = 1'
1840
1841        Args:
1842            *expressions: the SQL code strings to parse.
1843                If an `Expression` instance is passed, it will be used as-is.
1844                Multiple expressions are combined with an AND operator.
1845            append: if `True`, AND the new expressions to any existing expression.
1846                Otherwise, this resets the expression.
1847            dialect: the dialect used to parse the input expressions.
1848            copy: if `False`, modify this expression instance in-place.
1849            opts: other options to use to parse the input expressions.
1850
1851        Returns:
1852            The modified Join expression.
1853        """
1854        join = _apply_conjunction_builder(
1855            *expressions,
1856            instance=self,
1857            arg="on",
1858            append=append,
1859            dialect=dialect,
1860            copy=copy,
1861            **opts,
1862        )
1863
1864        if join.kind == "CROSS":
1865            join.set("kind", None)
1866
1867        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:
1869    def using(
1870        self,
1871        *expressions: t.Optional[ExpOrStr],
1872        append: bool = True,
1873        dialect: DialectType = None,
1874        copy: bool = True,
1875        **opts,
1876    ) -> Join:
1877        """
1878        Append to or set the USING expressions.
1879
1880        Example:
1881            >>> import sqlglot
1882            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1883            'JOIN x USING (foo, bla)'
1884
1885        Args:
1886            *expressions: the SQL code strings to parse.
1887                If an `Expression` instance is passed, it will be used as-is.
1888            append: if `True`, concatenate the new expressions to the existing "using" list.
1889                Otherwise, this resets the expression.
1890            dialect: the dialect used to parse the input expressions.
1891            copy: if `False`, modify this expression instance in-place.
1892            opts: other options to use to parse the input expressions.
1893
1894        Returns:
1895            The modified Join expression.
1896        """
1897        join = _apply_list_builder(
1898            *expressions,
1899            instance=self,
1900            arg="using",
1901            append=append,
1902            dialect=dialect,
1903            copy=copy,
1904            **opts,
1905        )
1906
1907        if join.kind == "CROSS":
1908            join.set("kind", None)
1909
1910        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):
1913class Lateral(UDTF):
1914    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):
1917class MatchRecognize(Expression):
1918    arg_types = {
1919        "partition_by": False,
1920        "order": False,
1921        "measures": False,
1922        "rows": False,
1923        "after": False,
1924        "pattern": False,
1925        "define": False,
1926        "alias": False,
1927    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1932class Final(Expression):
1933    pass
key = 'final'
class Offset(Expression):
1936class Offset(Expression):
1937    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1940class Order(Expression):
1941    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1946class Cluster(Order):
1947    pass
key = 'cluster'
class Distribute(Order):
1950class Distribute(Order):
1951    pass
key = 'distribute'
class Sort(Order):
1954class Sort(Order):
1955    pass
key = 'sort'
class Ordered(Expression):
1958class Ordered(Expression):
1959    arg_types = {"this": True, "desc": False, "nulls_first": True}
arg_types = {'this': True, 'desc': False, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1962class Property(Expression):
1963    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1966class AlgorithmProperty(Property):
1967    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1970class AutoIncrementProperty(Property):
1971    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1974class BlockCompressionProperty(Property):
1975    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):
1978class CharacterSetProperty(Property):
1979    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1982class ChecksumProperty(Property):
1983    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1986class CollateProperty(Property):
1987    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1990class CopyGrantsProperty(Property):
1991    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1994class DataBlocksizeProperty(Property):
1995    arg_types = {
1996        "size": False,
1997        "units": False,
1998        "minimum": False,
1999        "maximum": False,
2000        "default": False,
2001    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
2004class DefinerProperty(Property):
2005    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
2008class DistKeyProperty(Property):
2009    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
2012class DistStyleProperty(Property):
2013    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
2016class EngineProperty(Property):
2017    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
2020class HeapProperty(Property):
2021    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
2024class ToTableProperty(Property):
2025    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
2028class ExecuteAsProperty(Property):
2029    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
2032class ExternalProperty(Property):
2033    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
2036class FallbackProperty(Property):
2037    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
2040class FileFormatProperty(Property):
2041    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
2044class FreespaceProperty(Property):
2045    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputModelProperty(Property):
2048class InputModelProperty(Property):
2049    arg_types = {"this": True}
arg_types = {'this': True}
key = 'inputmodelproperty'
class OutputModelProperty(Property):
2052class OutputModelProperty(Property):
2053    arg_types = {"this": True}
arg_types = {'this': True}
key = 'outputmodelproperty'
class IsolatedLoadingProperty(Property):
2056class IsolatedLoadingProperty(Property):
2057    arg_types = {
2058        "no": True,
2059        "concurrent": True,
2060        "for_all": True,
2061        "for_insert": True,
2062        "for_none": True,
2063    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
2066class JournalProperty(Property):
2067    arg_types = {
2068        "no": False,
2069        "dual": False,
2070        "before": False,
2071        "local": False,
2072        "after": False,
2073    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
2076class LanguageProperty(Property):
2077    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
2081class ClusteredByProperty(Property):
2082    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
2085class DictProperty(Property):
2086    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2089class DictSubProperty(Property):
2090    pass
key = 'dictsubproperty'
class DictRange(Property):
2093class DictRange(Property):
2094    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2099class OnCluster(Property):
2100    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2103class LikeProperty(Property):
2104    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2107class LocationProperty(Property):
2108    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2111class LockingProperty(Property):
2112    arg_types = {
2113        "this": False,
2114        "kind": True,
2115        "for_or_in": False,
2116        "lock_type": True,
2117        "override": False,
2118    }
arg_types = {'this': False, 'kind': True, 'for_or_in': False, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2121class LogProperty(Property):
2122    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2125class MaterializedProperty(Property):
2126    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2129class MergeBlockRatioProperty(Property):
2130    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):
2133class NoPrimaryIndexProperty(Property):
2134    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnProperty(Property):
2137class OnProperty(Property):
2138    arg_types = {"this": True}
arg_types = {'this': True}
key = 'onproperty'
class OnCommitProperty(Property):
2141class OnCommitProperty(Property):
2142    arg_types = {"delete": False}
arg_types = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2145class PartitionedByProperty(Property):
2146    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class PartitionBoundSpec(Expression):
2150class PartitionBoundSpec(Expression):
2151    # this -> IN / MODULUS, expression -> REMAINDER, from_expressions -> FROM (...), to_expressions -> TO (...)
2152    arg_types = {
2153        "this": False,
2154        "expression": False,
2155        "from_expressions": False,
2156        "to_expressions": False,
2157    }
arg_types = {'this': False, 'expression': False, 'from_expressions': False, 'to_expressions': False}
key = 'partitionboundspec'
class PartitionedOfProperty(Property):
2160class PartitionedOfProperty(Property):
2161    # this -> parent_table (schema), expression -> FOR VALUES ... / DEFAULT
2162    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'partitionedofproperty'
class RemoteWithConnectionModelProperty(Property):
2165class RemoteWithConnectionModelProperty(Property):
2166    arg_types = {"this": True}
arg_types = {'this': True}
key = 'remotewithconnectionmodelproperty'
class ReturnsProperty(Property):
2169class ReturnsProperty(Property):
2170    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2173class RowFormatProperty(Property):
2174    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2177class RowFormatDelimitedProperty(Property):
2178    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2179    arg_types = {
2180        "fields": False,
2181        "escaped": False,
2182        "collection_items": False,
2183        "map_keys": False,
2184        "lines": False,
2185        "null": False,
2186        "serde": False,
2187    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2190class RowFormatSerdeProperty(Property):
2191    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2195class QueryTransform(Expression):
2196    arg_types = {
2197        "expressions": True,
2198        "command_script": True,
2199        "schema": False,
2200        "row_format_before": False,
2201        "record_writer": False,
2202        "row_format_after": False,
2203        "record_reader": False,
2204    }
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 SampleProperty(Property):
2207class SampleProperty(Property):
2208    arg_types = {"this": True}
arg_types = {'this': True}
key = 'sampleproperty'
class SchemaCommentProperty(Property):
2211class SchemaCommentProperty(Property):
2212    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2215class SerdeProperties(Property):
2216    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2219class SetProperty(Property):
2220    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2223class SettingsProperty(Property):
2224    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2227class SortKeyProperty(Property):
2228    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2231class SqlSecurityProperty(Property):
2232    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2235class StabilityProperty(Property):
2236    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2239class TemporaryProperty(Property):
2240    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransformModelProperty(Property):
2243class TransformModelProperty(Property):
2244    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'transformmodelproperty'
class TransientProperty(Property):
2247class TransientProperty(Property):
2248    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2251class VolatileProperty(Property):
2252    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2255class WithDataProperty(Property):
2256    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2259class WithJournalTableProperty(Property):
2260    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2263class Properties(Expression):
2264    arg_types = {"expressions": True}
2265
2266    NAME_TO_PROPERTY = {
2267        "ALGORITHM": AlgorithmProperty,
2268        "AUTO_INCREMENT": AutoIncrementProperty,
2269        "CHARACTER SET": CharacterSetProperty,
2270        "CLUSTERED_BY": ClusteredByProperty,
2271        "COLLATE": CollateProperty,
2272        "COMMENT": SchemaCommentProperty,
2273        "DEFINER": DefinerProperty,
2274        "DISTKEY": DistKeyProperty,
2275        "DISTSTYLE": DistStyleProperty,
2276        "ENGINE": EngineProperty,
2277        "EXECUTE AS": ExecuteAsProperty,
2278        "FORMAT": FileFormatProperty,
2279        "LANGUAGE": LanguageProperty,
2280        "LOCATION": LocationProperty,
2281        "PARTITIONED_BY": PartitionedByProperty,
2282        "RETURNS": ReturnsProperty,
2283        "ROW_FORMAT": RowFormatProperty,
2284        "SORTKEY": SortKeyProperty,
2285    }
2286
2287    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2288
2289    # CREATE property locations
2290    # Form: schema specified
2291    #   create [POST_CREATE]
2292    #     table a [POST_NAME]
2293    #     (b int) [POST_SCHEMA]
2294    #     with ([POST_WITH])
2295    #     index (b) [POST_INDEX]
2296    #
2297    # Form: alias selection
2298    #   create [POST_CREATE]
2299    #     table a [POST_NAME]
2300    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2301    #     index (c) [POST_INDEX]
2302    class Location(AutoName):
2303        POST_CREATE = auto()
2304        POST_NAME = auto()
2305        POST_SCHEMA = auto()
2306        POST_WITH = auto()
2307        POST_ALIAS = auto()
2308        POST_EXPRESSION = auto()
2309        POST_INDEX = auto()
2310        UNSUPPORTED = auto()
2311
2312    @classmethod
2313    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2314        expressions = []
2315        for key, value in properties_dict.items():
2316            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2317            if property_cls:
2318                expressions.append(property_cls(this=convert(value)))
2319            else:
2320                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2321
2322        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:
2312    @classmethod
2313    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2314        expressions = []
2315        for key, value in properties_dict.items():
2316            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2317            if property_cls:
2318                expressions.append(property_cls(this=convert(value)))
2319            else:
2320                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2321
2322        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2302    class Location(AutoName):
2303        POST_CREATE = auto()
2304        POST_NAME = auto()
2305        POST_SCHEMA = auto()
2306        POST_WITH = auto()
2307        POST_ALIAS = auto()
2308        POST_EXPRESSION = auto()
2309        POST_INDEX = auto()
2310        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):
2325class Qualify(Expression):
2326    pass
key = 'qualify'
class InputOutputFormat(Expression):
2329class InputOutputFormat(Expression):
2330    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class Return(Expression):
2334class Return(Expression):
2335    pass
key = 'return'
class Reference(Expression):
2338class Reference(Expression):
2339    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2342class Tuple(Expression):
2343    arg_types = {"expressions": False}
2344
2345    def isin(
2346        self,
2347        *expressions: t.Any,
2348        query: t.Optional[ExpOrStr] = None,
2349        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2350        copy: bool = True,
2351        **opts,
2352    ) -> In:
2353        return In(
2354            this=maybe_copy(self, copy),
2355            expressions=[convert(e, copy=copy) for e in expressions],
2356            query=maybe_parse(query, copy=copy, **opts) if query else None,
2357            unnest=Unnest(
2358                expressions=[
2359                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2360                ]
2361            )
2362            if unnest
2363            else None,
2364        )
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:
2345    def isin(
2346        self,
2347        *expressions: t.Any,
2348        query: t.Optional[ExpOrStr] = None,
2349        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2350        copy: bool = True,
2351        **opts,
2352    ) -> In:
2353        return In(
2354            this=maybe_copy(self, copy),
2355            expressions=[convert(e, copy=copy) for e in expressions],
2356            query=maybe_parse(query, copy=copy, **opts) if query else None,
2357            unnest=Unnest(
2358                expressions=[
2359                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2360                ]
2361            )
2362            if unnest
2363            else None,
2364        )
key = 'tuple'
class Subqueryable(Unionable):
2367class Subqueryable(Unionable):
2368    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2369        """
2370        Convert this expression to an aliased expression that can be used as a Subquery.
2371
2372        Example:
2373            >>> subquery = Select().select("x").from_("tbl").subquery()
2374            >>> Select().select("x").from_(subquery).sql()
2375            'SELECT x FROM (SELECT x FROM tbl)'
2376
2377        Args:
2378            alias (str | Identifier): an optional alias for the subquery
2379            copy (bool): if `False`, modify this expression instance in-place.
2380
2381        Returns:
2382            Alias: the subquery
2383        """
2384        instance = maybe_copy(self, copy)
2385        if not isinstance(alias, Expression):
2386            alias = TableAlias(this=to_identifier(alias)) if alias else None
2387
2388        return Subquery(this=instance, alias=alias)
2389
2390    def limit(
2391        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2392    ) -> Select:
2393        raise NotImplementedError
2394
2395    @property
2396    def ctes(self):
2397        with_ = self.args.get("with")
2398        if not with_:
2399            return []
2400        return with_.expressions
2401
2402    @property
2403    def selects(self) -> t.List[Expression]:
2404        raise NotImplementedError("Subqueryable objects must implement `selects`")
2405
2406    @property
2407    def named_selects(self) -> t.List[str]:
2408        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2409
2410    def select(
2411        self,
2412        *expressions: t.Optional[ExpOrStr],
2413        append: bool = True,
2414        dialect: DialectType = None,
2415        copy: bool = True,
2416        **opts,
2417    ) -> Subqueryable:
2418        raise NotImplementedError("Subqueryable objects must implement `select`")
2419
2420    def with_(
2421        self,
2422        alias: ExpOrStr,
2423        as_: ExpOrStr,
2424        recursive: t.Optional[bool] = None,
2425        append: bool = True,
2426        dialect: DialectType = None,
2427        copy: bool = True,
2428        **opts,
2429    ) -> Subqueryable:
2430        """
2431        Append to or set the common table expressions.
2432
2433        Example:
2434            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2435            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2436
2437        Args:
2438            alias: the SQL code string to parse as the table name.
2439                If an `Expression` instance is passed, this is used as-is.
2440            as_: the SQL code string to parse as the table expression.
2441                If an `Expression` instance is passed, it will be used as-is.
2442            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2443            append: if `True`, add to any existing expressions.
2444                Otherwise, this resets the expressions.
2445            dialect: the dialect used to parse the input expression.
2446            copy: if `False`, modify this expression instance in-place.
2447            opts: other options to use to parse the input expressions.
2448
2449        Returns:
2450            The modified expression.
2451        """
2452        return _apply_cte_builder(
2453            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2454        )
def subquery( self, alias: Union[str, Expression, NoneType] = None, copy: bool = True) -> Subquery:
2368    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2369        """
2370        Convert this expression to an aliased expression that can be used as a Subquery.
2371
2372        Example:
2373            >>> subquery = Select().select("x").from_("tbl").subquery()
2374            >>> Select().select("x").from_(subquery).sql()
2375            'SELECT x FROM (SELECT x FROM tbl)'
2376
2377        Args:
2378            alias (str | Identifier): an optional alias for the subquery
2379            copy (bool): if `False`, modify this expression instance in-place.
2380
2381        Returns:
2382            Alias: the subquery
2383        """
2384        instance = maybe_copy(self, copy)
2385        if not isinstance(alias, Expression):
2386            alias = TableAlias(this=to_identifier(alias)) if alias else None
2387
2388        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:
2390    def limit(
2391        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2392    ) -> Select:
2393        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:
2410    def select(
2411        self,
2412        *expressions: t.Optional[ExpOrStr],
2413        append: bool = True,
2414        dialect: DialectType = None,
2415        copy: bool = True,
2416        **opts,
2417    ) -> Subqueryable:
2418        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:
2420    def with_(
2421        self,
2422        alias: ExpOrStr,
2423        as_: ExpOrStr,
2424        recursive: t.Optional[bool] = None,
2425        append: bool = True,
2426        dialect: DialectType = None,
2427        copy: bool = True,
2428        **opts,
2429    ) -> Subqueryable:
2430        """
2431        Append to or set the common table expressions.
2432
2433        Example:
2434            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2435            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2436
2437        Args:
2438            alias: the SQL code string to parse as the table name.
2439                If an `Expression` instance is passed, this is used as-is.
2440            as_: the SQL code string to parse as the table expression.
2441                If an `Expression` instance is passed, it will be used as-is.
2442            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2443            append: if `True`, add to any existing expressions.
2444                Otherwise, this resets the expressions.
2445            dialect: the dialect used to parse the input expression.
2446            copy: if `False`, modify this expression instance in-place.
2447            opts: other options to use to parse the input expressions.
2448
2449        Returns:
2450            The modified expression.
2451        """
2452        return _apply_cte_builder(
2453            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2454        )

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):
2482class WithTableHint(Expression):
2483    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2487class IndexTableHint(Expression):
2488    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2491class Table(Expression):
2492    arg_types = {
2493        "this": True,
2494        "alias": False,
2495        "db": False,
2496        "catalog": False,
2497        "laterals": False,
2498        "joins": False,
2499        "pivots": False,
2500        "hints": False,
2501        "system_time": False,
2502        "version": False,
2503        "format": False,
2504        "pattern": False,
2505        "index": False,
2506        "ordinality": False,
2507    }
2508
2509    @property
2510    def name(self) -> str:
2511        if isinstance(self.this, Func):
2512            return ""
2513        return self.this.name
2514
2515    @property
2516    def db(self) -> str:
2517        return self.text("db")
2518
2519    @property
2520    def catalog(self) -> str:
2521        return self.text("catalog")
2522
2523    @property
2524    def selects(self) -> t.List[Expression]:
2525        return []
2526
2527    @property
2528    def named_selects(self) -> t.List[str]:
2529        return []
2530
2531    @property
2532    def parts(self) -> t.List[Expression]:
2533        """Return the parts of a table in order catalog, db, table."""
2534        parts: t.List[Expression] = []
2535
2536        for arg in ("catalog", "db", "this"):
2537            part = self.args.get(arg)
2538
2539            if isinstance(part, Dot):
2540                parts.extend(part.flatten())
2541            elif isinstance(part, Expression):
2542                parts.append(part)
2543
2544        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, 'format': False, 'pattern': False, 'index': False, 'ordinality': False}
name: str
db: str
catalog: str
selects: List[Expression]
named_selects: List[str]
parts: List[Expression]

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

key = 'table'
class Union(Subqueryable):
2547class Union(Subqueryable):
2548    arg_types = {
2549        "with": False,
2550        "this": True,
2551        "expression": True,
2552        "distinct": False,
2553        "by_name": False,
2554        **QUERY_MODIFIERS,
2555    }
2556
2557    def limit(
2558        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2559    ) -> Select:
2560        """
2561        Set the LIMIT expression.
2562
2563        Example:
2564            >>> select("1").union(select("1")).limit(1).sql()
2565            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2566
2567        Args:
2568            expression: the SQL code string to parse.
2569                This can also be an integer.
2570                If a `Limit` instance is passed, this is used as-is.
2571                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2572            dialect: the dialect used to parse the input expression.
2573            copy: if `False`, modify this expression instance in-place.
2574            opts: other options to use to parse the input expressions.
2575
2576        Returns:
2577            The limited subqueryable.
2578        """
2579        return (
2580            select("*")
2581            .from_(self.subquery(alias="_l_0", copy=copy))
2582            .limit(expression, dialect=dialect, copy=False, **opts)
2583        )
2584
2585    def select(
2586        self,
2587        *expressions: t.Optional[ExpOrStr],
2588        append: bool = True,
2589        dialect: DialectType = None,
2590        copy: bool = True,
2591        **opts,
2592    ) -> Union:
2593        """Append to or set the SELECT of the union recursively.
2594
2595        Example:
2596            >>> from sqlglot import parse_one
2597            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2598            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2599
2600        Args:
2601            *expressions: the SQL code strings to parse.
2602                If an `Expression` instance is passed, it will be used as-is.
2603            append: if `True`, add to any existing expressions.
2604                Otherwise, this resets the expressions.
2605            dialect: the dialect used to parse the input expressions.
2606            copy: if `False`, modify this expression instance in-place.
2607            opts: other options to use to parse the input expressions.
2608
2609        Returns:
2610            Union: the modified expression.
2611        """
2612        this = self.copy() if copy else self
2613        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2614        this.expression.unnest().select(
2615            *expressions, append=append, dialect=dialect, copy=False, **opts
2616        )
2617        return this
2618
2619    @property
2620    def named_selects(self) -> t.List[str]:
2621        return self.this.unnest().named_selects
2622
2623    @property
2624    def is_star(self) -> bool:
2625        return self.this.is_star or self.expression.is_star
2626
2627    @property
2628    def selects(self) -> t.List[Expression]:
2629        return self.this.unnest().selects
2630
2631    @property
2632    def left(self) -> Expression:
2633        return self.this
2634
2635    @property
2636    def right(self) -> Expression:
2637        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:
2557    def limit(
2558        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2559    ) -> Select:
2560        """
2561        Set the LIMIT expression.
2562
2563        Example:
2564            >>> select("1").union(select("1")).limit(1).sql()
2565            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2566
2567        Args:
2568            expression: the SQL code string to parse.
2569                This can also be an integer.
2570                If a `Limit` instance is passed, this is used as-is.
2571                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2572            dialect: the dialect used to parse the input expression.
2573            copy: if `False`, modify this expression instance in-place.
2574            opts: other options to use to parse the input expressions.
2575
2576        Returns:
2577            The limited subqueryable.
2578        """
2579        return (
2580            select("*")
2581            .from_(self.subquery(alias="_l_0", copy=copy))
2582            .limit(expression, dialect=dialect, copy=False, **opts)
2583        )

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

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:
2745    def group_by(
2746        self,
2747        *expressions: t.Optional[ExpOrStr],
2748        append: bool = True,
2749        dialect: DialectType = None,
2750        copy: bool = True,
2751        **opts,
2752    ) -> Select:
2753        """
2754        Set the GROUP BY expression.
2755
2756        Example:
2757            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2758            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2759
2760        Args:
2761            *expressions: the SQL code strings to parse.
2762                If a `Group` instance is passed, this is used as-is.
2763                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2764                If nothing is passed in then a group by is not applied to the expression
2765            append: if `True`, add to any existing expressions.
2766                Otherwise, this flattens all the `Group` expression into a single expression.
2767            dialect: the dialect used to parse the input expression.
2768            copy: if `False`, modify this expression instance in-place.
2769            opts: other options to use to parse the input expressions.
2770
2771        Returns:
2772            The modified Select expression.
2773        """
2774        if not expressions:
2775            return self if not copy else self.copy()
2776
2777        return _apply_child_list_builder(
2778            *expressions,
2779            instance=self,
2780            arg="group",
2781            append=append,
2782            copy=copy,
2783            prefix="GROUP BY",
2784            into=Group,
2785            dialect=dialect,
2786            **opts,
2787        )

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

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:
2829    def sort_by(
2830        self,
2831        *expressions: t.Optional[ExpOrStr],
2832        append: bool = True,
2833        dialect: DialectType = None,
2834        copy: bool = True,
2835        **opts,
2836    ) -> Select:
2837        """
2838        Set the SORT BY expression.
2839
2840        Example:
2841            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2842            'SELECT x FROM tbl SORT BY x DESC'
2843
2844        Args:
2845            *expressions: the SQL code strings to parse.
2846                If a `Group` instance is passed, this is used as-is.
2847                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2848            append: if `True`, add to any existing expressions.
2849                Otherwise, this flattens all the `Order` expression into a single expression.
2850            dialect: the dialect used to parse the input expression.
2851            copy: if `False`, modify this expression instance in-place.
2852            opts: other options to use to parse the input expressions.
2853
2854        Returns:
2855            The modified Select expression.
2856        """
2857        return _apply_child_list_builder(
2858            *expressions,
2859            instance=self,
2860            arg="sort",
2861            append=append,
2862            copy=copy,
2863            prefix="SORT BY",
2864            into=Sort,
2865            dialect=dialect,
2866            **opts,
2867        )

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:
2869    def cluster_by(
2870        self,
2871        *expressions: t.Optional[ExpOrStr],
2872        append: bool = True,
2873        dialect: DialectType = None,
2874        copy: bool = True,
2875        **opts,
2876    ) -> Select:
2877        """
2878        Set the CLUSTER BY expression.
2879
2880        Example:
2881            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2882            'SELECT x FROM tbl CLUSTER BY x DESC'
2883
2884        Args:
2885            *expressions: the SQL code strings to parse.
2886                If a `Group` instance is passed, this is used as-is.
2887                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2888            append: if `True`, add to any existing expressions.
2889                Otherwise, this flattens all the `Order` expression into a single expression.
2890            dialect: the dialect used to parse the input expression.
2891            copy: if `False`, modify this expression instance in-place.
2892            opts: other options to use to parse the input expressions.
2893
2894        Returns:
2895            The modified Select expression.
2896        """
2897        return _apply_child_list_builder(
2898            *expressions,
2899            instance=self,
2900            arg="cluster",
2901            append=append,
2902            copy=copy,
2903            prefix="CLUSTER BY",
2904            into=Cluster,
2905            dialect=dialect,
2906            **opts,
2907        )

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:
2909    def limit(
2910        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2911    ) -> Select:
2912        """
2913        Set the LIMIT expression.
2914
2915        Example:
2916            >>> Select().from_("tbl").select("x").limit(10).sql()
2917            'SELECT x FROM tbl LIMIT 10'
2918
2919        Args:
2920            expression: the SQL code string to parse.
2921                This can also be an integer.
2922                If a `Limit` instance is passed, this is used as-is.
2923                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2924            dialect: the dialect used to parse the input expression.
2925            copy: if `False`, modify this expression instance in-place.
2926            opts: other options to use to parse the input expressions.
2927
2928        Returns:
2929            Select: the modified expression.
2930        """
2931        return _apply_builder(
2932            expression=expression,
2933            instance=self,
2934            arg="limit",
2935            into=Limit,
2936            prefix="LIMIT",
2937            dialect=dialect,
2938            copy=copy,
2939            into_arg="expression",
2940            **opts,
2941        )

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:
2943    def offset(
2944        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2945    ) -> Select:
2946        """
2947        Set the OFFSET expression.
2948
2949        Example:
2950            >>> Select().from_("tbl").select("x").offset(10).sql()
2951            'SELECT x FROM tbl OFFSET 10'
2952
2953        Args:
2954            expression: the SQL code string to parse.
2955                This can also be an integer.
2956                If a `Offset` instance is passed, this is used as-is.
2957                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2958            dialect: the dialect used to parse the input expression.
2959            copy: if `False`, modify this expression instance in-place.
2960            opts: other options to use to parse the input expressions.
2961
2962        Returns:
2963            The modified Select expression.
2964        """
2965        return _apply_builder(
2966            expression=expression,
2967            instance=self,
2968            arg="offset",
2969            into=Offset,
2970            prefix="OFFSET",
2971            dialect=dialect,
2972            copy=copy,
2973            into_arg="expression",
2974            **opts,
2975        )

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:
2977    def select(
2978        self,
2979        *expressions: t.Optional[ExpOrStr],
2980        append: bool = True,
2981        dialect: DialectType = None,
2982        copy: bool = True,
2983        **opts,
2984    ) -> Select:
2985        """
2986        Append to or set the SELECT expressions.
2987
2988        Example:
2989            >>> Select().select("x", "y").sql()
2990            'SELECT x, y'
2991
2992        Args:
2993            *expressions: the SQL code strings to parse.
2994                If an `Expression` instance is passed, it will be used as-is.
2995            append: if `True`, add to any existing expressions.
2996                Otherwise, this resets the expressions.
2997            dialect: the dialect used to parse the input expressions.
2998            copy: if `False`, modify this expression instance in-place.
2999            opts: other options to use to parse the input expressions.
3000
3001        Returns:
3002            The modified Select expression.
3003        """
3004        return _apply_list_builder(
3005            *expressions,
3006            instance=self,
3007            arg="expressions",
3008            append=append,
3009            dialect=dialect,
3010            copy=copy,
3011            **opts,
3012        )

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:
3014    def lateral(
3015        self,
3016        *expressions: t.Optional[ExpOrStr],
3017        append: bool = True,
3018        dialect: DialectType = None,
3019        copy: bool = True,
3020        **opts,
3021    ) -> Select:
3022        """
3023        Append to or set the LATERAL expressions.
3024
3025        Example:
3026            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
3027            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
3028
3029        Args:
3030            *expressions: the SQL code strings to parse.
3031                If an `Expression` instance is passed, it will be used as-is.
3032            append: if `True`, add to any existing expressions.
3033                Otherwise, this resets the expressions.
3034            dialect: the dialect used to parse the input expressions.
3035            copy: if `False`, modify this expression instance in-place.
3036            opts: other options to use to parse the input expressions.
3037
3038        Returns:
3039            The modified Select expression.
3040        """
3041        return _apply_list_builder(
3042            *expressions,
3043            instance=self,
3044            arg="laterals",
3045            append=append,
3046            into=Lateral,
3047            prefix="LATERAL VIEW",
3048            dialect=dialect,
3049            copy=copy,
3050            **opts,
3051        )

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:
3053    def join(
3054        self,
3055        expression: ExpOrStr,
3056        on: t.Optional[ExpOrStr] = None,
3057        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
3058        append: bool = True,
3059        join_type: t.Optional[str] = None,
3060        join_alias: t.Optional[Identifier | str] = None,
3061        dialect: DialectType = None,
3062        copy: bool = True,
3063        **opts,
3064    ) -> Select:
3065        """
3066        Append to or set the JOIN expressions.
3067
3068        Example:
3069            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
3070            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
3071
3072            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
3073            'SELECT 1 FROM a JOIN b USING (x, y, z)'
3074
3075            Use `join_type` to change the type of join:
3076
3077            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
3078            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
3079
3080        Args:
3081            expression: the SQL code string to parse.
3082                If an `Expression` instance is passed, it will be used as-is.
3083            on: optionally specify the join "on" criteria as a SQL string.
3084                If an `Expression` instance is passed, it will be used as-is.
3085            using: optionally specify the join "using" criteria as a SQL string.
3086                If an `Expression` instance is passed, it will be used as-is.
3087            append: if `True`, add to any existing expressions.
3088                Otherwise, this resets the expressions.
3089            join_type: if set, alter the parsed join type.
3090            join_alias: an optional alias for the joined source.
3091            dialect: the dialect used to parse the input expressions.
3092            copy: if `False`, modify this expression instance in-place.
3093            opts: other options to use to parse the input expressions.
3094
3095        Returns:
3096            Select: the modified expression.
3097        """
3098        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
3099
3100        try:
3101            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
3102        except ParseError:
3103            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
3104
3105        join = expression if isinstance(expression, Join) else Join(this=expression)
3106
3107        if isinstance(join.this, Select):
3108            join.this.replace(join.this.subquery())
3109
3110        if join_type:
3111            method: t.Optional[Token]
3112            side: t.Optional[Token]
3113            kind: t.Optional[Token]
3114
3115            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
3116
3117            if method:
3118                join.set("method", method.text)
3119            if side:
3120                join.set("side", side.text)
3121            if kind:
3122                join.set("kind", kind.text)
3123
3124        if on:
3125            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
3126            join.set("on", on)
3127
3128        if using:
3129            join = _apply_list_builder(
3130                *ensure_list(using),
3131                instance=join,
3132                arg="using",
3133                append=append,
3134                copy=copy,
3135                into=Identifier,
3136                **opts,
3137            )
3138
3139        if join_alias:
3140            join.set("this", alias_(join.this, join_alias, table=True))
3141
3142        return _apply_list_builder(
3143            join,
3144            instance=self,
3145            arg="joins",
3146            append=append,
3147            copy=copy,
3148            **opts,
3149        )

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:
3151    def where(
3152        self,
3153        *expressions: t.Optional[ExpOrStr],
3154        append: bool = True,
3155        dialect: DialectType = None,
3156        copy: bool = True,
3157        **opts,
3158    ) -> Select:
3159        """
3160        Append to or set the WHERE expressions.
3161
3162        Example:
3163            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3164            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3165
3166        Args:
3167            *expressions: the SQL code strings to parse.
3168                If an `Expression` instance is passed, it will be used as-is.
3169                Multiple expressions are combined with an AND operator.
3170            append: if `True`, AND the new expressions to any existing expression.
3171                Otherwise, this resets the expression.
3172            dialect: the dialect used to parse the input expressions.
3173            copy: if `False`, modify this expression instance in-place.
3174            opts: other options to use to parse the input expressions.
3175
3176        Returns:
3177            Select: the modified expression.
3178        """
3179        return _apply_conjunction_builder(
3180            *expressions,
3181            instance=self,
3182            arg="where",
3183            append=append,
3184            into=Where,
3185            dialect=dialect,
3186            copy=copy,
3187            **opts,
3188        )

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:
3190    def having(
3191        self,
3192        *expressions: t.Optional[ExpOrStr],
3193        append: bool = True,
3194        dialect: DialectType = None,
3195        copy: bool = True,
3196        **opts,
3197    ) -> Select:
3198        """
3199        Append to or set the HAVING expressions.
3200
3201        Example:
3202            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3203            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3204
3205        Args:
3206            *expressions: the SQL code strings to parse.
3207                If an `Expression` instance is passed, it will be used as-is.
3208                Multiple expressions are combined with an AND operator.
3209            append: if `True`, AND the new expressions to any existing expression.
3210                Otherwise, this resets the expression.
3211            dialect: the dialect used to parse the input expressions.
3212            copy: if `False`, modify this expression instance in-place.
3213            opts: other options to use to parse the input expressions.
3214
3215        Returns:
3216            The modified Select expression.
3217        """
3218        return _apply_conjunction_builder(
3219            *expressions,
3220            instance=self,
3221            arg="having",
3222            append=append,
3223            into=Having,
3224            dialect=dialect,
3225            copy=copy,
3226            **opts,
3227        )

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:
3229    def window(
3230        self,
3231        *expressions: t.Optional[ExpOrStr],
3232        append: bool = True,
3233        dialect: DialectType = None,
3234        copy: bool = True,
3235        **opts,
3236    ) -> Select:
3237        return _apply_list_builder(
3238            *expressions,
3239            instance=self,
3240            arg="windows",
3241            append=append,
3242            into=Window,
3243            dialect=dialect,
3244            copy=copy,
3245            **opts,
3246        )
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:
3248    def qualify(
3249        self,
3250        *expressions: t.Optional[ExpOrStr],
3251        append: bool = True,
3252        dialect: DialectType = None,
3253        copy: bool = True,
3254        **opts,
3255    ) -> Select:
3256        return _apply_conjunction_builder(
3257            *expressions,
3258            instance=self,
3259            arg="qualify",
3260            append=append,
3261            into=Qualify,
3262            dialect=dialect,
3263            copy=copy,
3264            **opts,
3265        )
def distinct( self, *ons: Union[str, Expression, NoneType], distinct: bool = True, copy: bool = True) -> Select:
3267    def distinct(
3268        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3269    ) -> Select:
3270        """
3271        Set the OFFSET expression.
3272
3273        Example:
3274            >>> Select().from_("tbl").select("x").distinct().sql()
3275            'SELECT DISTINCT x FROM tbl'
3276
3277        Args:
3278            ons: the expressions to distinct on
3279            distinct: whether the Select should be distinct
3280            copy: if `False`, modify this expression instance in-place.
3281
3282        Returns:
3283            Select: the modified expression.
3284        """
3285        instance = maybe_copy(self, copy)
3286        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3287        instance.set("distinct", Distinct(on=on) if distinct else None)
3288        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:
3290    def ctas(
3291        self,
3292        table: ExpOrStr,
3293        properties: t.Optional[t.Dict] = None,
3294        dialect: DialectType = None,
3295        copy: bool = True,
3296        **opts,
3297    ) -> Create:
3298        """
3299        Convert this expression to a CREATE TABLE AS statement.
3300
3301        Example:
3302            >>> Select().select("*").from_("tbl").ctas("x").sql()
3303            'CREATE TABLE x AS SELECT * FROM tbl'
3304
3305        Args:
3306            table: the SQL code string to parse as the table name.
3307                If another `Expression` instance is passed, it will be used as-is.
3308            properties: an optional mapping of table properties
3309            dialect: the dialect used to parse the input table.
3310            copy: if `False`, modify this expression instance in-place.
3311            opts: other options to use to parse the input table.
3312
3313        Returns:
3314            The new Create expression.
3315        """
3316        instance = maybe_copy(self, copy)
3317        table_expression = maybe_parse(
3318            table,
3319            into=Table,
3320            dialect=dialect,
3321            **opts,
3322        )
3323        properties_expression = None
3324        if properties:
3325            properties_expression = Properties.from_dict(properties)
3326
3327        return Create(
3328            this=table_expression,
3329            kind="table",
3330            expression=instance,
3331            properties=properties_expression,
3332        )

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:
3334    def lock(self, update: bool = True, copy: bool = True) -> Select:
3335        """
3336        Set the locking read mode for this expression.
3337
3338        Examples:
3339            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3340            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3341
3342            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3343            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3344
3345        Args:
3346            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3347            copy: if `False`, modify this expression instance in-place.
3348
3349        Returns:
3350            The modified expression.
3351        """
3352        inst = maybe_copy(self, copy)
3353        inst.set("locks", [Lock(update=update)])
3354
3355        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:
3357    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3358        """
3359        Set hints for this expression.
3360
3361        Examples:
3362            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3363            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3364
3365        Args:
3366            hints: The SQL code strings to parse as the hints.
3367                If an `Expression` instance is passed, it will be used as-is.
3368            dialect: The dialect used to parse the hints.
3369            copy: If `False`, modify this expression instance in-place.
3370
3371        Returns:
3372            The modified expression.
3373        """
3374        inst = maybe_copy(self, copy)
3375        inst.set(
3376            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3377        )
3378
3379        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):
3394class Subquery(DerivedTable, Unionable):
3395    arg_types = {
3396        "this": True,
3397        "alias": False,
3398        "with": False,
3399        **QUERY_MODIFIERS,
3400    }
3401
3402    def unnest(self):
3403        """
3404        Returns the first non subquery.
3405        """
3406        expression = self
3407        while isinstance(expression, Subquery):
3408            expression = expression.this
3409        return expression
3410
3411    def unwrap(self) -> Subquery:
3412        expression = self
3413        while expression.same_parent and expression.is_wrapper:
3414            expression = t.cast(Subquery, expression.parent)
3415        return expression
3416
3417    @property
3418    def is_wrapper(self) -> bool:
3419        """
3420        Whether this Subquery acts as a simple wrapper around another expression.
3421
3422        SELECT * FROM (((SELECT * FROM t)))
3423                      ^
3424                      This corresponds to a "wrapper" Subquery node
3425        """
3426        return all(v is None for k, v in self.args.items() if k != "this")
3427
3428    @property
3429    def is_star(self) -> bool:
3430        return self.this.is_star
3431
3432    @property
3433    def output_name(self) -> str:
3434        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):
3402    def unnest(self):
3403        """
3404        Returns the first non subquery.
3405        """
3406        expression = self
3407        while isinstance(expression, Subquery):
3408            expression = expression.this
3409        return expression

Returns the first non subquery.

def unwrap(self) -> Subquery:
3411    def unwrap(self) -> Subquery:
3412        expression = self
3413        while expression.same_parent and expression.is_wrapper:
3414            expression = t.cast(Subquery, expression.parent)
3415        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):
3437class TableSample(Expression):
3438    arg_types = {
3439        "this": False,
3440        "expressions": False,
3441        "method": False,
3442        "bucket_numerator": False,
3443        "bucket_denominator": False,
3444        "bucket_field": False,
3445        "percent": False,
3446        "rows": False,
3447        "size": False,
3448        "seed": False,
3449        "kind": False,
3450    }
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):
3453class Tag(Expression):
3454    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3455
3456    arg_types = {
3457        "this": False,
3458        "prefix": False,
3459        "postfix": False,
3460    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3465class Pivot(Expression):
3466    arg_types = {
3467        "this": False,
3468        "alias": False,
3469        "expressions": False,
3470        "field": False,
3471        "unpivot": False,
3472        "using": False,
3473        "group": False,
3474        "columns": False,
3475        "include_nulls": False,
3476    }
arg_types = {'this': False, 'alias': False, 'expressions': False, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False, 'include_nulls': False}
key = 'pivot'
class Window(Condition):
3479class Window(Condition):
3480    arg_types = {
3481        "this": True,
3482        "partition_by": False,
3483        "order": False,
3484        "spec": False,
3485        "alias": False,
3486        "over": False,
3487        "first": False,
3488    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3491class WindowSpec(Expression):
3492    arg_types = {
3493        "kind": False,
3494        "start": False,
3495        "start_side": False,
3496        "end": False,
3497        "end_side": False,
3498    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3501class Where(Expression):
3502    pass
key = 'where'
class Star(Expression):
3505class Star(Expression):
3506    arg_types = {"except": False, "replace": False}
3507
3508    @property
3509    def name(self) -> str:
3510        return "*"
3511
3512    @property
3513    def output_name(self) -> str:
3514        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):
3517class Parameter(Condition):
3518    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'parameter'
class SessionParameter(Condition):
3521class SessionParameter(Condition):
3522    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3525class Placeholder(Condition):
3526    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3529class Null(Condition):
3530    arg_types: t.Dict[str, t.Any] = {}
3531
3532    @property
3533    def name(self) -> str:
3534        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3537class Boolean(Condition):
3538    pass
key = 'boolean'
class DataTypeParam(Expression):
3541class DataTypeParam(Expression):
3542    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypeparam'
class DataType(Expression):
3545class DataType(Expression):
3546    arg_types = {
3547        "this": True,
3548        "expressions": False,
3549        "nested": False,
3550        "values": False,
3551        "prefix": False,
3552        "kind": False,
3553    }
3554
3555    class Type(AutoName):
3556        ARRAY = auto()
3557        BIGDECIMAL = auto()
3558        BIGINT = auto()
3559        BIGSERIAL = auto()
3560        BINARY = auto()
3561        BIT = auto()
3562        BOOLEAN = auto()
3563        CHAR = auto()
3564        DATE = auto()
3565        DATEMULTIRANGE = auto()
3566        DATERANGE = auto()
3567        DATETIME = auto()
3568        DATETIME64 = auto()
3569        DECIMAL = auto()
3570        DOUBLE = auto()
3571        ENUM = auto()
3572        ENUM8 = auto()
3573        ENUM16 = auto()
3574        FIXEDSTRING = auto()
3575        FLOAT = auto()
3576        GEOGRAPHY = auto()
3577        GEOMETRY = auto()
3578        HLLSKETCH = auto()
3579        HSTORE = auto()
3580        IMAGE = auto()
3581        INET = auto()
3582        INT = auto()
3583        INT128 = auto()
3584        INT256 = auto()
3585        INT4MULTIRANGE = auto()
3586        INT4RANGE = auto()
3587        INT8MULTIRANGE = auto()
3588        INT8RANGE = auto()
3589        INTERVAL = auto()
3590        IPADDRESS = auto()
3591        IPPREFIX = auto()
3592        JSON = auto()
3593        JSONB = auto()
3594        LONGBLOB = auto()
3595        LONGTEXT = auto()
3596        LOWCARDINALITY = auto()
3597        MAP = auto()
3598        MEDIUMBLOB = auto()
3599        MEDIUMINT = auto()
3600        MEDIUMTEXT = auto()
3601        MONEY = auto()
3602        NCHAR = auto()
3603        NESTED = auto()
3604        NULL = auto()
3605        NULLABLE = auto()
3606        NUMMULTIRANGE = auto()
3607        NUMRANGE = auto()
3608        NVARCHAR = auto()
3609        OBJECT = auto()
3610        ROWVERSION = auto()
3611        SERIAL = auto()
3612        SET = auto()
3613        SMALLINT = auto()
3614        SMALLMONEY = auto()
3615        SMALLSERIAL = auto()
3616        STRUCT = auto()
3617        SUPER = auto()
3618        TEXT = auto()
3619        TINYBLOB = auto()
3620        TINYTEXT = auto()
3621        TIME = auto()
3622        TIMETZ = auto()
3623        TIMESTAMP = auto()
3624        TIMESTAMPLTZ = auto()
3625        TIMESTAMPTZ = auto()
3626        TIMESTAMP_S = auto()
3627        TIMESTAMP_MS = auto()
3628        TIMESTAMP_NS = auto()
3629        TINYINT = auto()
3630        TSMULTIRANGE = auto()
3631        TSRANGE = auto()
3632        TSTZMULTIRANGE = auto()
3633        TSTZRANGE = auto()
3634        UBIGINT = auto()
3635        UINT = auto()
3636        UINT128 = auto()
3637        UINT256 = auto()
3638        UMEDIUMINT = auto()
3639        UDECIMAL = auto()
3640        UNIQUEIDENTIFIER = auto()
3641        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3642        USERDEFINED = "USER-DEFINED"
3643        USMALLINT = auto()
3644        UTINYINT = auto()
3645        UUID = auto()
3646        VARBINARY = auto()
3647        VARCHAR = auto()
3648        VARIANT = auto()
3649        XML = auto()
3650        YEAR = auto()
3651
3652    TEXT_TYPES = {
3653        Type.CHAR,
3654        Type.NCHAR,
3655        Type.VARCHAR,
3656        Type.NVARCHAR,
3657        Type.TEXT,
3658    }
3659
3660    INTEGER_TYPES = {
3661        Type.INT,
3662        Type.TINYINT,
3663        Type.SMALLINT,
3664        Type.BIGINT,
3665        Type.INT128,
3666        Type.INT256,
3667    }
3668
3669    FLOAT_TYPES = {
3670        Type.FLOAT,
3671        Type.DOUBLE,
3672    }
3673
3674    NUMERIC_TYPES = {
3675        *INTEGER_TYPES,
3676        *FLOAT_TYPES,
3677    }
3678
3679    TEMPORAL_TYPES = {
3680        Type.TIME,
3681        Type.TIMETZ,
3682        Type.TIMESTAMP,
3683        Type.TIMESTAMPTZ,
3684        Type.TIMESTAMPLTZ,
3685        Type.TIMESTAMP_S,
3686        Type.TIMESTAMP_MS,
3687        Type.TIMESTAMP_NS,
3688        Type.DATE,
3689        Type.DATETIME,
3690        Type.DATETIME64,
3691    }
3692
3693    @classmethod
3694    def build(
3695        cls,
3696        dtype: str | DataType | DataType.Type,
3697        dialect: DialectType = None,
3698        udt: bool = False,
3699        **kwargs,
3700    ) -> DataType:
3701        """
3702        Constructs a DataType object.
3703
3704        Args:
3705            dtype: the data type of interest.
3706            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3707            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3708                DataType, thus creating a user-defined type.
3709            kawrgs: additional arguments to pass in the constructor of DataType.
3710
3711        Returns:
3712            The constructed DataType object.
3713        """
3714        from sqlglot import parse_one
3715
3716        if isinstance(dtype, str):
3717            if dtype.upper() == "UNKNOWN":
3718                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3719
3720            try:
3721                data_type_exp = parse_one(
3722                    dtype, read=dialect, into=DataType, error_level=ErrorLevel.IGNORE
3723                )
3724            except ParseError:
3725                if udt:
3726                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3727                raise
3728        elif isinstance(dtype, DataType.Type):
3729            data_type_exp = DataType(this=dtype)
3730        elif isinstance(dtype, DataType):
3731            return dtype
3732        else:
3733            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3734
3735        return DataType(**{**data_type_exp.args, **kwargs})
3736
3737    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3738        """
3739        Checks whether this DataType matches one of the provided data types. Nested types or precision
3740        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3741
3742        Args:
3743            dtypes: the data types to compare this DataType to.
3744
3745        Returns:
3746            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3747        """
3748        for dtype in dtypes:
3749            other = DataType.build(dtype, udt=True)
3750
3751            if (
3752                other.expressions
3753                or self.this == DataType.Type.USERDEFINED
3754                or other.this == DataType.Type.USERDEFINED
3755            ):
3756                matches = self == other
3757            else:
3758                matches = self.this == other.this
3759
3760            if matches:
3761                return True
3762        return False
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False, 'kind': False}
TEXT_TYPES = {<Type.TEXT: 'TEXT'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.CHAR: 'CHAR'>}
INTEGER_TYPES = {<Type.INT256: 'INT256'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.BIGINT: 'BIGINT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.INT256: 'INT256'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT: 'INT'>, <Type.INT128: 'INT128'>, <Type.BIGINT: 'BIGINT'>, <Type.TINYINT: 'TINYINT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
TEMPORAL_TYPES = {<Type.TIMESTAMP_NS: 'TIMESTAMP_NS'>, <Type.DATE: 'DATE'>, <Type.TIME: 'TIME'>, <Type.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.TIMETZ: 'TIMETZ'>, <Type.TIMESTAMP_S: 'TIMESTAMP_S'>, <Type.DATETIME: 'DATETIME'>, <Type.DATETIME64: 'DATETIME64'>}
@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:
3693    @classmethod
3694    def build(
3695        cls,
3696        dtype: str | DataType | DataType.Type,
3697        dialect: DialectType = None,
3698        udt: bool = False,
3699        **kwargs,
3700    ) -> DataType:
3701        """
3702        Constructs a DataType object.
3703
3704        Args:
3705            dtype: the data type of interest.
3706            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3707            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3708                DataType, thus creating a user-defined type.
3709            kawrgs: additional arguments to pass in the constructor of DataType.
3710
3711        Returns:
3712            The constructed DataType object.
3713        """
3714        from sqlglot import parse_one
3715
3716        if isinstance(dtype, str):
3717            if dtype.upper() == "UNKNOWN":
3718                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3719
3720            try:
3721                data_type_exp = parse_one(
3722                    dtype, read=dialect, into=DataType, error_level=ErrorLevel.IGNORE
3723                )
3724            except ParseError:
3725                if udt:
3726                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3727                raise
3728        elif isinstance(dtype, DataType.Type):
3729            data_type_exp = DataType(this=dtype)
3730        elif isinstance(dtype, DataType):
3731            return dtype
3732        else:
3733            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3734
3735        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:
3737    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3738        """
3739        Checks whether this DataType matches one of the provided data types. Nested types or precision
3740        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3741
3742        Args:
3743            dtypes: the data types to compare this DataType to.
3744
3745        Returns:
3746            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3747        """
3748        for dtype in dtypes:
3749            other = DataType.build(dtype, udt=True)
3750
3751            if (
3752                other.expressions
3753                or self.this == DataType.Type.USERDEFINED
3754                or other.this == DataType.Type.USERDEFINED
3755            ):
3756                matches = self == other
3757            else:
3758                matches = self.this == other.this
3759
3760            if matches:
3761                return True
3762        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):
3555    class Type(AutoName):
3556        ARRAY = auto()
3557        BIGDECIMAL = auto()
3558        BIGINT = auto()
3559        BIGSERIAL = auto()
3560        BINARY = auto()
3561        BIT = auto()
3562        BOOLEAN = auto()
3563        CHAR = auto()
3564        DATE = auto()
3565        DATEMULTIRANGE = auto()
3566        DATERANGE = auto()
3567        DATETIME = auto()
3568        DATETIME64 = auto()
3569        DECIMAL = auto()
3570        DOUBLE = auto()
3571        ENUM = auto()
3572        ENUM8 = auto()
3573        ENUM16 = auto()
3574        FIXEDSTRING = auto()
3575        FLOAT = auto()
3576        GEOGRAPHY = auto()
3577        GEOMETRY = auto()
3578        HLLSKETCH = auto()
3579        HSTORE = auto()
3580        IMAGE = auto()
3581        INET = auto()
3582        INT = auto()
3583        INT128 = auto()
3584        INT256 = auto()
3585        INT4MULTIRANGE = auto()
3586        INT4RANGE = auto()
3587        INT8MULTIRANGE = auto()
3588        INT8RANGE = auto()
3589        INTERVAL = auto()
3590        IPADDRESS = auto()
3591        IPPREFIX = auto()
3592        JSON = auto()
3593        JSONB = auto()
3594        LONGBLOB = auto()
3595        LONGTEXT = auto()
3596        LOWCARDINALITY = auto()
3597        MAP = auto()
3598        MEDIUMBLOB = auto()
3599        MEDIUMINT = auto()
3600        MEDIUMTEXT = auto()
3601        MONEY = auto()
3602        NCHAR = auto()
3603        NESTED = auto()
3604        NULL = auto()
3605        NULLABLE = auto()
3606        NUMMULTIRANGE = auto()
3607        NUMRANGE = auto()
3608        NVARCHAR = auto()
3609        OBJECT = auto()
3610        ROWVERSION = auto()
3611        SERIAL = auto()
3612        SET = auto()
3613        SMALLINT = auto()
3614        SMALLMONEY = auto()
3615        SMALLSERIAL = auto()
3616        STRUCT = auto()
3617        SUPER = auto()
3618        TEXT = auto()
3619        TINYBLOB = auto()
3620        TINYTEXT = auto()
3621        TIME = auto()
3622        TIMETZ = auto()
3623        TIMESTAMP = auto()
3624        TIMESTAMPLTZ = auto()
3625        TIMESTAMPTZ = auto()
3626        TIMESTAMP_S = auto()
3627        TIMESTAMP_MS = auto()
3628        TIMESTAMP_NS = auto()
3629        TINYINT = auto()
3630        TSMULTIRANGE = auto()
3631        TSRANGE = auto()
3632        TSTZMULTIRANGE = auto()
3633        TSTZRANGE = auto()
3634        UBIGINT = auto()
3635        UINT = auto()
3636        UINT128 = auto()
3637        UINT256 = auto()
3638        UMEDIUMINT = auto()
3639        UDECIMAL = auto()
3640        UNIQUEIDENTIFIER = auto()
3641        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3642        USERDEFINED = "USER-DEFINED"
3643        USMALLINT = auto()
3644        UTINYINT = auto()
3645        UUID = auto()
3646        VARBINARY = auto()
3647        VARCHAR = auto()
3648        VARIANT = auto()
3649        XML = auto()
3650        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'>
TIMESTAMP_S = <Type.TIMESTAMP_S: 'TIMESTAMP_S'>
TIMESTAMP_MS = <Type.TIMESTAMP_MS: 'TIMESTAMP_MS'>
TIMESTAMP_NS = <Type.TIMESTAMP_NS: 'TIMESTAMP_NS'>
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'>
UDECIMAL = <Type.UDECIMAL: 'UDECIMAL'>
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(DataType):
3766class PseudoType(DataType):
3767    arg_types = {"this": True}
arg_types = {'this': True}
key = 'pseudotype'
class ObjectIdentifier(DataType):
3771class ObjectIdentifier(DataType):
3772    arg_types = {"this": True}
arg_types = {'this': True}
key = 'objectidentifier'
class SubqueryPredicate(Predicate):
3776class SubqueryPredicate(Predicate):
3777    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3780class All(SubqueryPredicate):
3781    pass
key = 'all'
class Any(SubqueryPredicate):
3784class Any(SubqueryPredicate):
3785    pass
key = 'any'
class Exists(SubqueryPredicate):
3788class Exists(SubqueryPredicate):
3789    pass
key = 'exists'
class Command(Expression):
3794class Command(Expression):
3795    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3798class Transaction(Expression):
3799    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3802class Commit(Expression):
3803    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3806class Rollback(Expression):
3807    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3810class AlterTable(Expression):
3811    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):
3814class AddConstraint(Expression):
3815    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3818class DropPartition(Expression):
3819    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3823class Binary(Condition):
3824    arg_types = {"this": True, "expression": True}
3825
3826    @property
3827    def left(self) -> Expression:
3828        return self.this
3829
3830    @property
3831    def right(self) -> Expression:
3832        return self.expression
arg_types = {'this': True, 'expression': True}
left: Expression
right: Expression
key = 'binary'
class Add(Binary):
3835class Add(Binary):
3836    pass
key = 'add'
class Connector(Binary):
3839class Connector(Binary):
3840    pass
key = 'connector'
class And(Connector):
3843class And(Connector):
3844    pass
key = 'and'
class Or(Connector):
3847class Or(Connector):
3848    pass
key = 'or'
class BitwiseAnd(Binary):
3851class BitwiseAnd(Binary):
3852    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3855class BitwiseLeftShift(Binary):
3856    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3859class BitwiseOr(Binary):
3860    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3863class BitwiseRightShift(Binary):
3864    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3867class BitwiseXor(Binary):
3868    pass
key = 'bitwisexor'
class Div(Binary):
3871class Div(Binary):
3872    pass
key = 'div'
class Overlaps(Binary):
3875class Overlaps(Binary):
3876    pass
key = 'overlaps'
class Dot(Binary):
3879class Dot(Binary):
3880    @property
3881    def name(self) -> str:
3882        return self.expression.name
3883
3884    @property
3885    def output_name(self) -> str:
3886        return self.name
3887
3888    @classmethod
3889    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3890        """Build a Dot object with a sequence of expressions."""
3891        if len(expressions) < 2:
3892            raise ValueError(f"Dot requires >= 2 expressions.")
3893
3894        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:
3888    @classmethod
3889    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3890        """Build a Dot object with a sequence of expressions."""
3891        if len(expressions) < 2:
3892            raise ValueError(f"Dot requires >= 2 expressions.")
3893
3894        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):
3897class DPipe(Binary):
3898    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3901class SafeDPipe(DPipe):
3902    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3905class EQ(Binary, Predicate):
3906    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3909class NullSafeEQ(Binary, Predicate):
3910    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3913class NullSafeNEQ(Binary, Predicate):
3914    pass
key = 'nullsafeneq'
class Distance(Binary):
3917class Distance(Binary):
3918    pass
key = 'distance'
class Escape(Binary):
3921class Escape(Binary):
3922    pass
key = 'escape'
class Glob(Binary, Predicate):
3925class Glob(Binary, Predicate):
3926    pass
key = 'glob'
class GT(Binary, Predicate):
3929class GT(Binary, Predicate):
3930    pass
key = 'gt'
class GTE(Binary, Predicate):
3933class GTE(Binary, Predicate):
3934    pass
key = 'gte'
class ILike(Binary, Predicate):
3937class ILike(Binary, Predicate):
3938    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3941class ILikeAny(Binary, Predicate):
3942    pass
key = 'ilikeany'
class IntDiv(Binary):
3945class IntDiv(Binary):
3946    pass
key = 'intdiv'
class Is(Binary, Predicate):
3949class Is(Binary, Predicate):
3950    pass
key = 'is'
class Kwarg(Binary):
3953class Kwarg(Binary):
3954    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3957class Like(Binary, Predicate):
3958    pass
key = 'like'
class LikeAny(Binary, Predicate):
3961class LikeAny(Binary, Predicate):
3962    pass
key = 'likeany'
class LT(Binary, Predicate):
3965class LT(Binary, Predicate):
3966    pass
key = 'lt'
class LTE(Binary, Predicate):
3969class LTE(Binary, Predicate):
3970    pass
key = 'lte'
class Mod(Binary):
3973class Mod(Binary):
3974    pass
key = 'mod'
class Mul(Binary):
3977class Mul(Binary):
3978    pass
key = 'mul'
class NEQ(Binary, Predicate):
3981class NEQ(Binary, Predicate):
3982    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3985class SimilarTo(Binary, Predicate):
3986    pass
key = 'similarto'
class Slice(Binary):
3989class Slice(Binary):
3990    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3993class Sub(Binary):
3994    pass
key = 'sub'
class ArrayOverlaps(Binary):
3997class ArrayOverlaps(Binary):
3998    pass
key = 'arrayoverlaps'
class Unary(Condition):
4003class Unary(Condition):
4004    pass
key = 'unary'
class BitwiseNot(Unary):
4007class BitwiseNot(Unary):
4008    pass
key = 'bitwisenot'
class Not(Unary):
4011class Not(Unary):
4012    pass
key = 'not'
class Paren(Unary):
4015class Paren(Unary):
4016    arg_types = {"this": True, "with": False}
4017
4018    @property
4019    def output_name(self) -> str:
4020        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):
4023class Neg(Unary):
4024    pass
key = 'neg'
class Alias(Expression):
4027class Alias(Expression):
4028    arg_types = {"this": True, "alias": False}
4029
4030    @property
4031    def output_name(self) -> str:
4032        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):
4035class Aliases(Expression):
4036    arg_types = {"this": True, "expressions": True}
4037
4038    @property
4039    def aliases(self):
4040        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
4043class AtTimeZone(Expression):
4044    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
4047class Between(Predicate):
4048    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
4051class Bracket(Condition):
4052    arg_types = {"this": True, "expressions": True}
4053
4054    @property
4055    def output_name(self) -> str:
4056        if len(self.expressions) == 1:
4057            return self.expressions[0].output_name
4058
4059        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):
4062class SafeBracket(Bracket):
4063    """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):
4066class Distinct(Expression):
4067    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
4070class In(Predicate):
4071    arg_types = {
4072        "this": True,
4073        "expressions": False,
4074        "query": False,
4075        "unnest": False,
4076        "field": False,
4077        "is_global": False,
4078    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
4081class TimeUnit(Expression):
4082    """Automatically converts unit arg into a var."""
4083
4084    arg_types = {"unit": False}
4085
4086    UNABBREVIATED_UNIT_NAME = {
4087        "d": "day",
4088        "h": "hour",
4089        "m": "minute",
4090        "ms": "millisecond",
4091        "ns": "nanosecond",
4092        "q": "quarter",
4093        "s": "second",
4094        "us": "microsecond",
4095        "w": "week",
4096        "y": "year",
4097    }
4098
4099    VAR_LIKE = (Column, Literal, Var)
4100
4101    def __init__(self, **args):
4102        unit = args.get("unit")
4103        if isinstance(unit, self.VAR_LIKE):
4104            args["unit"] = Var(this=self.UNABBREVIATED_UNIT_NAME.get(unit.name) or unit.name)
4105        elif isinstance(unit, Week):
4106            unit.set("this", Var(this=unit.this.name))
4107
4108        super().__init__(**args)
4109
4110    @property
4111    def unit(self) -> t.Optional[Var]:
4112        return self.args.get("unit")

Automatically converts unit arg into a var.

TimeUnit(**args)
4101    def __init__(self, **args):
4102        unit = args.get("unit")
4103        if isinstance(unit, self.VAR_LIKE):
4104            args["unit"] = Var(this=self.UNABBREVIATED_UNIT_NAME.get(unit.name) or unit.name)
4105        elif isinstance(unit, Week):
4106            unit.set("this", Var(this=unit.this.name))
4107
4108        super().__init__(**args)
arg_types = {'unit': False}
UNABBREVIATED_UNIT_NAME = {'d': 'day', 'h': 'hour', 'm': 'minute', 'ms': 'millisecond', 'ns': 'nanosecond', 'q': 'quarter', 's': 'second', 'us': 'microsecond', 'w': 'week', 'y': 'year'}
VAR_LIKE = (<class 'Column'>, <class 'Literal'>, <class 'Var'>)
unit: Optional[Var]
key = 'timeunit'
class IntervalOp(TimeUnit):
4115class IntervalOp(TimeUnit):
4116    arg_types = {"unit": True, "expression": True}
4117
4118    def interval(self):
4119        return Interval(
4120            this=self.expression.copy(),
4121            unit=self.unit.copy(),
4122        )
arg_types = {'unit': True, 'expression': True}
def interval(self):
4118    def interval(self):
4119        return Interval(
4120            this=self.expression.copy(),
4121            unit=self.unit.copy(),
4122        )
key = 'intervalop'
class IntervalSpan(DataType):
4128class IntervalSpan(DataType):
4129    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'intervalspan'
class Interval(TimeUnit):
4132class Interval(TimeUnit):
4133    arg_types = {"this": False, "unit": False}
arg_types = {'this': False, 'unit': False}
key = 'interval'
class IgnoreNulls(Expression):
4136class IgnoreNulls(Expression):
4137    pass
key = 'ignorenulls'
class RespectNulls(Expression):
4140class RespectNulls(Expression):
4141    pass
key = 'respectnulls'
class Func(Condition):
4145class Func(Condition):
4146    """
4147    The base class for all function expressions.
4148
4149    Attributes:
4150        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
4151            treated as a variable length argument and the argument's value will be stored as a list.
4152        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
4153            for this function expression. These values are used to map this node to a name during parsing
4154            as well as to provide the function's name during SQL string generation. By default the SQL
4155            name is set to the expression's class name transformed to snake case.
4156    """
4157
4158    is_var_len_args = False
4159
4160    @classmethod
4161    def from_arg_list(cls, args):
4162        if cls.is_var_len_args:
4163            all_arg_keys = list(cls.arg_types)
4164            # If this function supports variable length argument treat the last argument as such.
4165            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4166            num_non_var = len(non_var_len_arg_keys)
4167
4168            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4169            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4170        else:
4171            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4172
4173        return cls(**args_dict)
4174
4175    @classmethod
4176    def sql_names(cls):
4177        if cls is Func:
4178            raise NotImplementedError(
4179                "SQL name is only supported by concrete function implementations"
4180            )
4181        if "_sql_names" not in cls.__dict__:
4182            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4183        return cls._sql_names
4184
4185    @classmethod
4186    def sql_name(cls):
4187        return cls.sql_names()[0]
4188
4189    @classmethod
4190    def default_parser_mappings(cls):
4191        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):
4160    @classmethod
4161    def from_arg_list(cls, args):
4162        if cls.is_var_len_args:
4163            all_arg_keys = list(cls.arg_types)
4164            # If this function supports variable length argument treat the last argument as such.
4165            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4166            num_non_var = len(non_var_len_arg_keys)
4167
4168            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4169            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4170        else:
4171            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4172
4173        return cls(**args_dict)
@classmethod
def sql_names(cls):
4175    @classmethod
4176    def sql_names(cls):
4177        if cls is Func:
4178            raise NotImplementedError(
4179                "SQL name is only supported by concrete function implementations"
4180            )
4181        if "_sql_names" not in cls.__dict__:
4182            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4183        return cls._sql_names
@classmethod
def sql_name(cls):
4185    @classmethod
4186    def sql_name(cls):
4187        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
4189    @classmethod
4190    def default_parser_mappings(cls):
4191        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
4194class AggFunc(Func):
4195    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
4198class ParameterizedAgg(AggFunc):
4199    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
4202class Abs(Func):
4203    pass
key = 'abs'
class ArgMax(AggFunc):
4206class ArgMax(AggFunc):
4207    arg_types = {"this": True, "expression": True, "count": False}
4208    _sql_names = ["ARG_MAX", "ARGMAX", "MAX_BY"]
arg_types = {'this': True, 'expression': True, 'count': False}
key = 'argmax'
class ArgMin(AggFunc):
4211class ArgMin(AggFunc):
4212    arg_types = {"this": True, "expression": True, "count": False}
4213    _sql_names = ["ARG_MIN", "ARGMIN", "MIN_BY"]
arg_types = {'this': True, 'expression': True, 'count': False}
key = 'argmin'
class ApproxTopK(AggFunc):
4216class ApproxTopK(AggFunc):
4217    arg_types = {"this": True, "expression": False, "counters": False}
arg_types = {'this': True, 'expression': False, 'counters': False}
key = 'approxtopk'
class Flatten(Func):
4220class Flatten(Func):
4221    pass
key = 'flatten'
class Transform(Func):
4225class Transform(Func):
4226    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
4229class Anonymous(Func):
4230    arg_types = {"this": True, "expressions": False}
4231    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
4236class Hll(AggFunc):
4237    arg_types = {"this": True, "expressions": False}
4238    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
4241class ApproxDistinct(AggFunc):
4242    arg_types = {"this": True, "accuracy": False}
4243    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
4246class Array(Func):
4247    arg_types = {"expressions": False}
4248    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
4252class ToChar(Func):
4253    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
4256class GenerateSeries(Func):
4257    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
4260class ArrayAgg(AggFunc):
4261    pass
key = 'arrayagg'
class ArrayAll(Func):
4264class ArrayAll(Func):
4265    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4268class ArrayAny(Func):
4269    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4272class ArrayConcat(Func):
4273    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4274    arg_types = {"this": True, "expressions": False}
4275    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4278class ArrayContains(Binary, Func):
4279    pass
key = 'arraycontains'
class ArrayContained(Binary):
4282class ArrayContained(Binary):
4283    pass
key = 'arraycontained'
class ArrayFilter(Func):
4286class ArrayFilter(Func):
4287    arg_types = {"this": True, "expression": True}
4288    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4291class ArrayJoin(Func):
4292    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4295class ArraySize(Func):
4296    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4299class ArraySort(Func):
4300    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4303class ArraySum(Func):
4304    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4307class ArrayUnionAgg(AggFunc):
4308    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4311class Avg(AggFunc):
4312    pass
key = 'avg'
class AnyValue(AggFunc):
4315class AnyValue(AggFunc):
4316    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):
4319class First(Func):
4320    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4323class Last(Func):
4324    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4327class Case(Func):
4328    arg_types = {"this": False, "ifs": True, "default": False}
4329
4330    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4331        instance = maybe_copy(self, copy)
4332        instance.append(
4333            "ifs",
4334            If(
4335                this=maybe_parse(condition, copy=copy, **opts),
4336                true=maybe_parse(then, copy=copy, **opts),
4337            ),
4338        )
4339        return instance
4340
4341    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4342        instance = maybe_copy(self, copy)
4343        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4344        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:
4330    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4331        instance = maybe_copy(self, copy)
4332        instance.append(
4333            "ifs",
4334            If(
4335                this=maybe_parse(condition, copy=copy, **opts),
4336                true=maybe_parse(then, copy=copy, **opts),
4337            ),
4338        )
4339        return instance
def else_( self, condition: Union[str, Expression], copy: bool = True, **opts) -> Case:
4341    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4342        instance = maybe_copy(self, copy)
4343        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4344        return instance
key = 'case'
class Cast(Func):
4347class Cast(Func):
4348    arg_types = {"this": True, "to": True, "format": False, "safe": False}
4349
4350    @property
4351    def name(self) -> str:
4352        return self.this.name
4353
4354    @property
4355    def to(self) -> DataType:
4356        return self.args["to"]
4357
4358    @property
4359    def output_name(self) -> str:
4360        return self.name
4361
4362    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4363        """
4364        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4365        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4366        array<int> != array<float>.
4367
4368        Args:
4369            dtypes: the data types to compare this Cast's DataType to.
4370
4371        Returns:
4372            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4373        """
4374        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True, 'format': False, 'safe': 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:
4362    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4363        """
4364        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4365        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4366        array<int> != array<float>.
4367
4368        Args:
4369            dtypes: the data types to compare this Cast's DataType to.
4370
4371        Returns:
4372            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4373        """
4374        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):
4377class TryCast(Cast):
4378    pass
key = 'trycast'
class CastToStrType(Func):
4381class CastToStrType(Func):
4382    arg_types = {"this": True, "to": True}
arg_types = {'this': True, 'to': True}
key = 'casttostrtype'
class Collate(Binary, Func):
4385class Collate(Binary, Func):
4386    pass
key = 'collate'
class Ceil(Func):
4389class Ceil(Func):
4390    arg_types = {"this": True, "decimals": False}
4391    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4394class Coalesce(Func):
4395    arg_types = {"this": True, "expressions": False}
4396    is_var_len_args = True
4397    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Chr(Func):
4400class Chr(Func):
4401    arg_types = {"this": True, "charset": False, "expressions": False}
4402    is_var_len_args = True
4403    _sql_names = ["CHR", "CHAR"]
arg_types = {'this': True, 'charset': False, 'expressions': False}
is_var_len_args = True
key = 'chr'
class Concat(Func):
4406class Concat(Func):
4407    arg_types = {"expressions": True}
4408    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4411class SafeConcat(Concat):
4412    pass
key = 'safeconcat'
class ConcatWs(Concat):
4415class ConcatWs(Concat):
4416    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4419class Count(AggFunc):
4420    arg_types = {"this": False, "expressions": False}
4421    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4424class CountIf(AggFunc):
4425    pass
key = 'countif'
class CurrentDate(Func):
4428class CurrentDate(Func):
4429    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4432class CurrentDatetime(Func):
4433    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4436class CurrentTime(Func):
4437    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4440class CurrentTimestamp(Func):
4441    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4444class CurrentUser(Func):
4445    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, IntervalOp):
4448class DateAdd(Func, IntervalOp):
4449    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, IntervalOp):
4452class DateSub(Func, IntervalOp):
4453    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4456class DateDiff(Func, TimeUnit):
4457    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4458    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4461class DateTrunc(Func):
4462    arg_types = {"unit": True, "this": True, "zone": False}
4463
4464    @property
4465    def unit(self) -> Expression:
4466        return self.args["unit"]
arg_types = {'unit': True, 'this': True, 'zone': False}
unit: Expression
key = 'datetrunc'
class DatetimeAdd(Func, IntervalOp):
4469class DatetimeAdd(Func, IntervalOp):
4470    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, IntervalOp):
4473class DatetimeSub(Func, IntervalOp):
4474    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4477class DatetimeDiff(Func, TimeUnit):
4478    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4481class DatetimeTrunc(Func, TimeUnit):
4482    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4485class DayOfWeek(Func):
4486    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4489class DayOfMonth(Func):
4490    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4493class DayOfYear(Func):
4494    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class ToDays(Func):
4497class ToDays(Func):
4498    pass
key = 'todays'
class WeekOfYear(Func):
4501class WeekOfYear(Func):
4502    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4505class MonthsBetween(Func):
4506    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4509class LastDateOfMonth(Func):
4510    pass
key = 'lastdateofmonth'
class Extract(Func):
4513class Extract(Func):
4514    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class Timestamp(Func):
4517class Timestamp(Func):
4518    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'timestamp'
class TimestampAdd(Func, TimeUnit):
4521class TimestampAdd(Func, TimeUnit):
4522    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4525class TimestampSub(Func, TimeUnit):
4526    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4529class TimestampDiff(Func, TimeUnit):
4530    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4533class TimestampTrunc(Func, TimeUnit):
4534    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4537class TimeAdd(Func, TimeUnit):
4538    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4541class TimeSub(Func, TimeUnit):
4542    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4545class TimeDiff(Func, TimeUnit):
4546    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4549class TimeTrunc(Func, TimeUnit):
4550    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4553class DateFromParts(Func):
4554    _sql_names = ["DATEFROMPARTS"]
4555    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4558class DateStrToDate(Func):
4559    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4562class DateToDateStr(Func):
4563    pass
key = 'datetodatestr'
class DateToDi(Func):
4566class DateToDi(Func):
4567    pass
key = 'datetodi'
class Date(Func):
4571class Date(Func):
4572    arg_types = {"this": False, "zone": False, "expressions": False}
4573    is_var_len_args = True
arg_types = {'this': False, 'zone': False, 'expressions': False}
is_var_len_args = True
key = 'date'
class Day(Func):
4576class Day(Func):
4577    pass
key = 'day'
class Decode(Func):
4580class Decode(Func):
4581    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4584class DiToDate(Func):
4585    pass
key = 'ditodate'
class Encode(Func):
4588class Encode(Func):
4589    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4592class Exp(Func):
4593    pass
key = 'exp'
class Explode(Func):
4597class Explode(Func):
4598    arg_types = {"this": True, "expressions": False}
4599    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'explode'
class ExplodeOuter(Explode):
4602class ExplodeOuter(Explode):
4603    pass
key = 'explodeouter'
class Posexplode(Explode):
4606class Posexplode(Explode):
4607    pass
key = 'posexplode'
class PosexplodeOuter(Posexplode):
4610class PosexplodeOuter(Posexplode):
4611    pass
key = 'posexplodeouter'
class Floor(Func):
4614class Floor(Func):
4615    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4618class FromBase64(Func):
4619    pass
key = 'frombase64'
class ToBase64(Func):
4622class ToBase64(Func):
4623    pass
key = 'tobase64'
class Greatest(Func):
4626class Greatest(Func):
4627    arg_types = {"this": True, "expressions": False}
4628    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(AggFunc):
4631class GroupConcat(AggFunc):
4632    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4635class Hex(Func):
4636    pass
key = 'hex'
class Xor(Connector, Func):
4639class Xor(Connector, Func):
4640    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4643class If(Func):
4644    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4647class Initcap(Func):
4648    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4651class IsNan(Func):
4652    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class FormatJson(Expression):
4655class FormatJson(Expression):
4656    pass
key = 'formatjson'
class JSONKeyValue(Expression):
4659class JSONKeyValue(Expression):
4660    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4663class JSONObject(Func):
4664    arg_types = {
4665        "expressions": False,
4666        "null_handling": False,
4667        "unique_keys": False,
4668        "return_type": False,
4669        "encoding": False,
4670    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'encoding': False}
key = 'jsonobject'
class JSONArray(Func):
4674class JSONArray(Func):
4675    arg_types = {
4676        "expressions": True,
4677        "null_handling": False,
4678        "return_type": False,
4679        "strict": False,
4680    }
arg_types = {'expressions': True, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarray'
class JSONArrayAgg(Func):
4684class JSONArrayAgg(Func):
4685    arg_types = {
4686        "this": True,
4687        "order": False,
4688        "null_handling": False,
4689        "return_type": False,
4690        "strict": False,
4691    }
arg_types = {'this': True, 'order': False, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarrayagg'
class JSONColumnDef(Expression):
4696class JSONColumnDef(Expression):
4697    arg_types = {"this": False, "kind": False, "path": False, "nested_schema": False}
arg_types = {'this': False, 'kind': False, 'path': False, 'nested_schema': False}
key = 'jsoncolumndef'
class JSONSchema(Expression):
4700class JSONSchema(Expression):
4701    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'jsonschema'
class JSONTable(Func):
4705class JSONTable(Func):
4706    arg_types = {
4707        "this": True,
4708        "schema": True,
4709        "path": False,
4710        "error_handling": False,
4711        "empty_handling": False,
4712    }
arg_types = {'this': True, 'schema': True, 'path': False, 'error_handling': False, 'empty_handling': False}
key = 'jsontable'
class OpenJSONColumnDef(Expression):
4715class OpenJSONColumnDef(Expression):
4716    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):
4719class OpenJSON(Func):
4720    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4723class JSONBContains(Binary):
4724    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4727class JSONExtract(Binary, Func):
4728    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4731class JSONExtractScalar(JSONExtract):
4732    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4735class JSONBExtract(JSONExtract):
4736    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4739class JSONBExtractScalar(JSONExtract):
4740    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4743class JSONFormat(Func):
4744    arg_types = {"this": False, "options": False}
4745    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4749class JSONArrayContains(Binary, Predicate, Func):
4750    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class ParseJSON(Func):
4753class ParseJSON(Func):
4754    # BigQuery, Snowflake have PARSE_JSON, Presto has JSON_PARSE
4755    _sql_names = ["PARSE_JSON", "JSON_PARSE"]
4756    arg_types = {"this": True, "expressions": False}
4757    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'parsejson'
class Least(Func):
4760class Least(Func):
4761    arg_types = {"this": True, "expressions": False}
4762    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4765class Left(Func):
4766    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4773class Length(Func):
4774    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4777class Levenshtein(Func):
4778    arg_types = {
4779        "this": True,
4780        "expression": False,
4781        "ins_cost": False,
4782        "del_cost": False,
4783        "sub_cost": False,
4784    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4787class Ln(Func):
4788    pass
key = 'ln'
class Log(Func):
4791class Log(Func):
4792    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4795class Log2(Func):
4796    pass
key = 'log2'
class Log10(Func):
4799class Log10(Func):
4800    pass
key = 'log10'
class LogicalOr(AggFunc):
4803class LogicalOr(AggFunc):
4804    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4807class LogicalAnd(AggFunc):
4808    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4811class Lower(Func):
4812    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4815class Map(Func):
4816    arg_types = {"keys": False, "values": False}
4817
4818    @property
4819    def keys(self) -> t.List[Expression]:
4820        keys = self.args.get("keys")
4821        return keys.expressions if keys else []
4822
4823    @property
4824    def values(self) -> t.List[Expression]:
4825        values = self.args.get("values")
4826        return values.expressions if values else []
arg_types = {'keys': False, 'values': False}
keys: List[Expression]
values: List[Expression]
key = 'map'
class MapFromEntries(Func):
4829class MapFromEntries(Func):
4830    pass
key = 'mapfromentries'
class StarMap(Func):
4833class StarMap(Func):
4834    pass
key = 'starmap'
class VarMap(Func):
4837class VarMap(Func):
4838    arg_types = {"keys": True, "values": True}
4839    is_var_len_args = True
4840
4841    @property
4842    def keys(self) -> t.List[Expression]:
4843        return self.args["keys"].expressions
4844
4845    @property
4846    def values(self) -> t.List[Expression]:
4847        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):
4851class MatchAgainst(Func):
4852    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4855class Max(AggFunc):
4856    arg_types = {"this": True, "expressions": False}
4857    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4860class MD5(Func):
4861    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4865class MD5Digest(Func):
4866    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4869class Min(AggFunc):
4870    arg_types = {"this": True, "expressions": False}
4871    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4874class Month(Func):
4875    pass
key = 'month'
class Nvl2(Func):
4878class Nvl2(Func):
4879    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Predict(Func):
4883class Predict(Func):
4884    arg_types = {"this": True, "expression": True, "params_struct": False}
arg_types = {'this': True, 'expression': True, 'params_struct': False}
key = 'predict'
class Pow(Binary, Func):
4887class Pow(Binary, Func):
4888    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4891class PercentileCont(AggFunc):
4892    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4895class PercentileDisc(AggFunc):
4896    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4899class Quantile(AggFunc):
4900    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4903class ApproxQuantile(Quantile):
4904    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):
4907class RangeN(Func):
4908    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4911class ReadCSV(Func):
4912    _sql_names = ["READ_CSV"]
4913    is_var_len_args = True
4914    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4917class Reduce(Func):
4918    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):
4921class RegexpExtract(Func):
4922    arg_types = {
4923        "this": True,
4924        "expression": True,
4925        "position": False,
4926        "occurrence": False,
4927        "parameters": False,
4928        "group": False,
4929    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4932class RegexpReplace(Func):
4933    arg_types = {
4934        "this": True,
4935        "expression": True,
4936        "replacement": True,
4937        "position": False,
4938        "occurrence": False,
4939        "parameters": False,
4940        "modifiers": False,
4941    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False, 'modifiers': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4944class RegexpLike(Binary, Func):
4945    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Binary, Func):
4948class RegexpILike(Binary, Func):
4949    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4954class RegexpSplit(Func):
4955    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4958class Repeat(Func):
4959    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4962class Round(Func):
4963    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4966class RowNumber(Func):
4967    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4970class SafeDivide(Func):
4971    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4974class SetAgg(AggFunc):
4975    pass
key = 'setagg'
class SHA(Func):
4978class SHA(Func):
4979    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4982class SHA2(Func):
4983    _sql_names = ["SHA2"]
4984    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4987class SortArray(Func):
4988    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4991class Split(Func):
4992    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4997class Substring(Func):
4998    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
5001class StandardHash(Func):
5002    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
5005class StartsWith(Func):
5006    _sql_names = ["STARTS_WITH", "STARTSWITH"]
5007    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
5010class StrPosition(Func):
5011    arg_types = {
5012        "this": True,
5013        "substr": True,
5014        "position": False,
5015        "instance": False,
5016    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
5019class StrToDate(Func):
5020    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
5023class StrToTime(Func):
5024    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
5029class StrToUnix(Func):
5030    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
5035class StrToMap(Func):
5036    arg_types = {
5037        "this": True,
5038        "pair_delim": False,
5039        "key_value_delim": False,
5040        "duplicate_resolution_callback": False,
5041    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
5044class NumberToStr(Func):
5045    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
5048class FromBase(Func):
5049    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
5052class Struct(Func):
5053    arg_types = {"expressions": False}
5054    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
5057class StructExtract(Func):
5058    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Stuff(Func):
5063class Stuff(Func):
5064    _sql_names = ["STUFF", "INSERT"]
5065    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):
5068class Sum(AggFunc):
5069    pass
key = 'sum'
class Sqrt(Func):
5072class Sqrt(Func):
5073    pass
key = 'sqrt'
class Stddev(AggFunc):
5076class Stddev(AggFunc):
5077    pass
key = 'stddev'
class StddevPop(AggFunc):
5080class StddevPop(AggFunc):
5081    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
5084class StddevSamp(AggFunc):
5085    pass
key = 'stddevsamp'
class TimeToStr(Func):
5088class TimeToStr(Func):
5089    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
5092class TimeToTimeStr(Func):
5093    pass
key = 'timetotimestr'
class TimeToUnix(Func):
5096class TimeToUnix(Func):
5097    pass
key = 'timetounix'
class TimeStrToDate(Func):
5100class TimeStrToDate(Func):
5101    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
5104class TimeStrToTime(Func):
5105    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
5108class TimeStrToUnix(Func):
5109    pass
key = 'timestrtounix'
class Trim(Func):
5112class Trim(Func):
5113    arg_types = {
5114        "this": True,
5115        "expression": False,
5116        "position": False,
5117        "collation": False,
5118    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
5121class TsOrDsAdd(Func, TimeUnit):
5122    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
5125class TsOrDsToDateStr(Func):
5126    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
5129class TsOrDsToDate(Func):
5130    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
5133class TsOrDiToDi(Func):
5134    pass
key = 'tsorditodi'
class Unhex(Func):
5137class Unhex(Func):
5138    pass
key = 'unhex'
class UnixToStr(Func):
5141class UnixToStr(Func):
5142    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
5147class UnixToTime(Func):
5148    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
5149
5150    SECONDS = Literal.string("seconds")
5151    MILLIS = Literal.string("millis")
5152    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):
5155class UnixToTimeStr(Func):
5156    pass
key = 'unixtotimestr'
class Upper(Func):
5159class Upper(Func):
5160    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
5163class Variance(AggFunc):
5164    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
5167class VariancePop(AggFunc):
5168    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
5171class Week(Func):
5172    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
5175class XMLTable(Func):
5176    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):
5179class Year(Func):
5180    pass
key = 'year'
class Use(Expression):
5183class Use(Expression):
5184    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
5187class Merge(Expression):
5188    arg_types = {"this": True, "using": True, "on": True, "expressions": True, "with": False}
arg_types = {'this': True, 'using': True, 'on': True, 'expressions': True, 'with': False}
key = 'merge'
class When(Func):
5191class When(Func):
5192    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):
5197class NextValueFor(Func):
5198    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 'ApproxTopK'>, <class 'ArgMax'>, <class 'ArgMin'>, <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 'Chr'>, <class 'Coalesce'>, <class 'Collate'>, <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 'ExplodeOuter'>, <class 'Extract'>, <class 'First'>, <class 'Flatten'>, <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 'PosexplodeOuter'>, <class 'Pow'>, <class 'Predict'>, <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 'ToDays'>, <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:
5235def maybe_parse(
5236    sql_or_expression: ExpOrStr,
5237    *,
5238    into: t.Optional[IntoType] = None,
5239    dialect: DialectType = None,
5240    prefix: t.Optional[str] = None,
5241    copy: bool = False,
5242    **opts,
5243) -> Expression:
5244    """Gracefully handle a possible string or expression.
5245
5246    Example:
5247        >>> maybe_parse("1")
5248        (LITERAL this: 1, is_string: False)
5249        >>> maybe_parse(to_identifier("x"))
5250        (IDENTIFIER this: x, quoted: False)
5251
5252    Args:
5253        sql_or_expression: the SQL code string or an expression
5254        into: the SQLGlot Expression to parse into
5255        dialect: the dialect used to parse the input expressions (in the case that an
5256            input expression is a SQL string).
5257        prefix: a string to prefix the sql with before it gets parsed
5258            (automatically includes a space)
5259        copy: whether or not to copy the expression.
5260        **opts: other options to use to parse the input expressions (again, in the case
5261            that an input expression is a SQL string).
5262
5263    Returns:
5264        Expression: the parsed or given expression.
5265    """
5266    if isinstance(sql_or_expression, Expression):
5267        if copy:
5268            return sql_or_expression.copy()
5269        return sql_or_expression
5270
5271    if sql_or_expression is None:
5272        raise ParseError(f"SQL cannot be None")
5273
5274    import sqlglot
5275
5276    sql = str(sql_or_expression)
5277    if prefix:
5278        sql = f"{prefix} {sql}"
5279
5280    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):
5293def maybe_copy(instance, copy=True):
5294    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, copy: bool = True, **opts) -> Union:
5475def union(
5476    left: ExpOrStr,
5477    right: ExpOrStr,
5478    distinct: bool = True,
5479    dialect: DialectType = None,
5480    copy: bool = True,
5481    **opts,
5482) -> Union:
5483    """
5484    Initializes a syntax tree from one UNION expression.
5485
5486    Example:
5487        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5488        'SELECT * FROM foo UNION SELECT * FROM bla'
5489
5490    Args:
5491        left: the SQL code string corresponding to the left-hand side.
5492            If an `Expression` instance is passed, it will be used as-is.
5493        right: the SQL code string corresponding to the right-hand side.
5494            If an `Expression` instance is passed, it will be used as-is.
5495        distinct: set the DISTINCT flag if and only if this is true.
5496        dialect: the dialect used to parse the input expression.
5497        copy: whether or not to copy the expression.
5498        opts: other options to use to parse the input expressions.
5499
5500    Returns:
5501        The new Union instance.
5502    """
5503    left = maybe_parse(sql_or_expression=left, dialect=dialect, copy=copy, **opts)
5504    right = maybe_parse(sql_or_expression=right, dialect=dialect, copy=copy, **opts)
5505
5506    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.
  • copy: whether or not to copy the 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, copy: bool = True, **opts) -> Intersect:
5509def intersect(
5510    left: ExpOrStr,
5511    right: ExpOrStr,
5512    distinct: bool = True,
5513    dialect: DialectType = None,
5514    copy: bool = True,
5515    **opts,
5516) -> Intersect:
5517    """
5518    Initializes a syntax tree from one INTERSECT expression.
5519
5520    Example:
5521        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5522        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5523
5524    Args:
5525        left: the SQL code string corresponding to the left-hand side.
5526            If an `Expression` instance is passed, it will be used as-is.
5527        right: the SQL code string corresponding to the right-hand side.
5528            If an `Expression` instance is passed, it will be used as-is.
5529        distinct: set the DISTINCT flag if and only if this is true.
5530        dialect: the dialect used to parse the input expression.
5531        copy: whether or not to copy the expression.
5532        opts: other options to use to parse the input expressions.
5533
5534    Returns:
5535        The new Intersect instance.
5536    """
5537    left = maybe_parse(sql_or_expression=left, dialect=dialect, copy=copy, **opts)
5538    right = maybe_parse(sql_or_expression=right, dialect=dialect, copy=copy, **opts)
5539
5540    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.
  • copy: whether or not to copy the 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, copy: bool = True, **opts) -> Except:
5543def except_(
5544    left: ExpOrStr,
5545    right: ExpOrStr,
5546    distinct: bool = True,
5547    dialect: DialectType = None,
5548    copy: bool = True,
5549    **opts,
5550) -> Except:
5551    """
5552    Initializes a syntax tree from one EXCEPT expression.
5553
5554    Example:
5555        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5556        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5557
5558    Args:
5559        left: the SQL code string corresponding to the left-hand side.
5560            If an `Expression` instance is passed, it will be used as-is.
5561        right: the SQL code string corresponding to the right-hand side.
5562            If an `Expression` instance is passed, it will be used as-is.
5563        distinct: set the DISTINCT flag if and only if this is true.
5564        dialect: the dialect used to parse the input expression.
5565        copy: whether or not to copy the expression.
5566        opts: other options to use to parse the input expressions.
5567
5568    Returns:
5569        The new Except instance.
5570    """
5571    left = maybe_parse(sql_or_expression=left, dialect=dialect, copy=copy, **opts)
5572    right = maybe_parse(sql_or_expression=right, dialect=dialect, copy=copy, **opts)
5573
5574    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.
  • copy: whether or not to copy the 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:
5577def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5578    """
5579    Initializes a syntax tree from one or multiple SELECT expressions.
5580
5581    Example:
5582        >>> select("col1", "col2").from_("tbl").sql()
5583        'SELECT col1, col2 FROM tbl'
5584
5585    Args:
5586        *expressions: the SQL code string to parse as the expressions of a
5587            SELECT statement. If an Expression instance is passed, this is used as-is.
5588        dialect: the dialect used to parse the input expressions (in the case that an
5589            input expression is a SQL string).
5590        **opts: other options to use to parse the input expressions (again, in the case
5591            that an input expression is a SQL string).
5592
5593    Returns:
5594        Select: the syntax tree for the SELECT statement.
5595    """
5596    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:
5599def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5600    """
5601    Initializes a syntax tree from a FROM expression.
5602
5603    Example:
5604        >>> from_("tbl").select("col1", "col2").sql()
5605        'SELECT col1, col2 FROM tbl'
5606
5607    Args:
5608        *expression: the SQL code string to parse as the FROM expressions of a
5609            SELECT statement. If an Expression instance is passed, this is used as-is.
5610        dialect: the dialect used to parse the input expression (in the case that the
5611            input expression is a SQL string).
5612        **opts: other options to use to parse the input expressions (again, in the case
5613            that the input expression is a SQL string).
5614
5615    Returns:
5616        Select: the syntax tree for the SELECT statement.
5617    """
5618    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:
5621def update(
5622    table: str | Table,
5623    properties: dict,
5624    where: t.Optional[ExpOrStr] = None,
5625    from_: t.Optional[ExpOrStr] = None,
5626    dialect: DialectType = None,
5627    **opts,
5628) -> Update:
5629    """
5630    Creates an update statement.
5631
5632    Example:
5633        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5634        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5635
5636    Args:
5637        *properties: dictionary of properties to set which are
5638            auto converted to sql objects eg None -> NULL
5639        where: sql conditional parsed into a WHERE statement
5640        from_: sql statement parsed into a FROM statement
5641        dialect: the dialect used to parse the input expressions.
5642        **opts: other options to use to parse the input expressions.
5643
5644    Returns:
5645        Update: the syntax tree for the UPDATE statement.
5646    """
5647    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5648    update_expr.set(
5649        "expressions",
5650        [
5651            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5652            for k, v in properties.items()
5653        ],
5654    )
5655    if from_:
5656        update_expr.set(
5657            "from",
5658            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5659        )
5660    if isinstance(where, Condition):
5661        where = Where(this=where)
5662    if where:
5663        update_expr.set(
5664            "where",
5665            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5666        )
5667    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:
5670def delete(
5671    table: ExpOrStr,
5672    where: t.Optional[ExpOrStr] = None,
5673    returning: t.Optional[ExpOrStr] = None,
5674    dialect: DialectType = None,
5675    **opts,
5676) -> Delete:
5677    """
5678    Builds a delete statement.
5679
5680    Example:
5681        >>> delete("my_table", where="id > 1").sql()
5682        'DELETE FROM my_table WHERE id > 1'
5683
5684    Args:
5685        where: sql conditional parsed into a WHERE statement
5686        returning: sql conditional parsed into a RETURNING statement
5687        dialect: the dialect used to parse the input expressions.
5688        **opts: other options to use to parse the input expressions.
5689
5690    Returns:
5691        Delete: the syntax tree for the DELETE statement.
5692    """
5693    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5694    if where:
5695        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5696    if returning:
5697        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5698    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:
5701def insert(
5702    expression: ExpOrStr,
5703    into: ExpOrStr,
5704    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5705    overwrite: t.Optional[bool] = None,
5706    dialect: DialectType = None,
5707    copy: bool = True,
5708    **opts,
5709) -> Insert:
5710    """
5711    Builds an INSERT statement.
5712
5713    Example:
5714        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5715        'INSERT INTO tbl VALUES (1, 2, 3)'
5716
5717    Args:
5718        expression: the sql string or expression of the INSERT statement
5719        into: the tbl to insert data to.
5720        columns: optionally the table's column names.
5721        overwrite: whether to INSERT OVERWRITE or not.
5722        dialect: the dialect used to parse the input expressions.
5723        copy: whether or not to copy the expression.
5724        **opts: other options to use to parse the input expressions.
5725
5726    Returns:
5727        Insert: the syntax tree for the INSERT statement.
5728    """
5729    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5730    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5731
5732    if columns:
5733        this = _apply_list_builder(
5734            *columns,
5735            instance=Schema(this=this),
5736            arg="expressions",
5737            into=Identifier,
5738            copy=False,
5739            dialect=dialect,
5740            **opts,
5741        )
5742
5743    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:
5746def condition(
5747    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5748) -> Condition:
5749    """
5750    Initialize a logical condition expression.
5751
5752    Example:
5753        >>> condition("x=1").sql()
5754        'x = 1'
5755
5756        This is helpful for composing larger logical syntax trees:
5757        >>> where = condition("x=1")
5758        >>> where = where.and_("y=1")
5759        >>> Select().from_("tbl").select("*").where(where).sql()
5760        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5761
5762    Args:
5763        *expression: the SQL code string to parse.
5764            If an Expression instance is passed, this is used as-is.
5765        dialect: the dialect used to parse the input expression (in the case that the
5766            input expression is a SQL string).
5767        copy: Whether or not to copy `expression` (only applies to expressions).
5768        **opts: other options to use to parse the input expressions (again, in the case
5769            that the input expression is a SQL string).
5770
5771    Returns:
5772        The new Condition instance
5773    """
5774    return maybe_parse(
5775        expression,
5776        into=Condition,
5777        dialect=dialect,
5778        copy=copy,
5779        **opts,
5780    )

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:
5783def and_(
5784    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5785) -> Condition:
5786    """
5787    Combine multiple conditions with an AND logical operator.
5788
5789    Example:
5790        >>> and_("x=1", and_("y=1", "z=1")).sql()
5791        'x = 1 AND (y = 1 AND z = 1)'
5792
5793    Args:
5794        *expressions: the SQL code strings to parse.
5795            If an Expression instance is passed, this is used as-is.
5796        dialect: the dialect used to parse the input expression.
5797        copy: whether or not to copy `expressions` (only applies to Expressions).
5798        **opts: other options to use to parse the input expressions.
5799
5800    Returns:
5801        And: the new condition
5802    """
5803    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:
5806def or_(
5807    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5808) -> Condition:
5809    """
5810    Combine multiple conditions with an OR logical operator.
5811
5812    Example:
5813        >>> or_("x=1", or_("y=1", "z=1")).sql()
5814        'x = 1 OR (y = 1 OR z = 1)'
5815
5816    Args:
5817        *expressions: the SQL code strings to parse.
5818            If an Expression instance is passed, this is used as-is.
5819        dialect: the dialect used to parse the input expression.
5820        copy: whether or not to copy `expressions` (only applies to Expressions).
5821        **opts: other options to use to parse the input expressions.
5822
5823    Returns:
5824        Or: the new condition
5825    """
5826    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:
5829def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5830    """
5831    Wrap a condition with a NOT operator.
5832
5833    Example:
5834        >>> not_("this_suit='black'").sql()
5835        "NOT this_suit = 'black'"
5836
5837    Args:
5838        expression: the SQL code string to parse.
5839            If an Expression instance is passed, this is used as-is.
5840        dialect: the dialect used to parse the input expression.
5841        copy: whether to copy the expression or not.
5842        **opts: other options to use to parse the input expressions.
5843
5844    Returns:
5845        The new condition.
5846    """
5847    this = condition(
5848        expression,
5849        dialect=dialect,
5850        copy=copy,
5851        **opts,
5852    )
5853    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:
5856def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5857    """
5858    Wrap an expression in parentheses.
5859
5860    Example:
5861        >>> paren("5 + 3").sql()
5862        '(5 + 3)'
5863
5864    Args:
5865        expression: the SQL code string to parse.
5866            If an Expression instance is passed, this is used as-is.
5867        copy: whether to copy the expression or not.
5868
5869    Returns:
5870        The wrapped expression.
5871    """
5872    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):
5890def to_identifier(name, quoted=None, copy=True):
5891    """Builds an identifier.
5892
5893    Args:
5894        name: The name to turn into an identifier.
5895        quoted: Whether or not force quote the identifier.
5896        copy: Whether or not to copy a passed in Identefier node.
5897
5898    Returns:
5899        The identifier ast node.
5900    """
5901
5902    if name is None:
5903        return None
5904
5905    if isinstance(name, Identifier):
5906        identifier = maybe_copy(name, copy)
5907    elif isinstance(name, str):
5908        identifier = Identifier(
5909            this=name,
5910            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5911        )
5912    else:
5913        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5914    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:
5920def to_interval(interval: str | Literal) -> Interval:
5921    """Builds an interval expression from a string like '1 day' or '5 months'."""
5922    if isinstance(interval, Literal):
5923        if not interval.is_string:
5924            raise ValueError("Invalid interval string.")
5925
5926        interval = interval.this
5927
5928    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5929
5930    if not interval_parts:
5931        raise ValueError("Invalid interval string.")
5932
5933    return Interval(
5934        this=Literal.string(interval_parts.group(1)),
5935        unit=Var(this=interval_parts.group(2)),
5936    )

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]:
5949def to_table(
5950    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5951) -> t.Optional[Table]:
5952    """
5953    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5954    If a table is passed in then that table is returned.
5955
5956    Args:
5957        sql_path: a `[catalog].[schema].[table]` string.
5958        dialect: the source dialect according to which the table name will be parsed.
5959        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5960
5961    Returns:
5962        A table expression.
5963    """
5964    if sql_path is None or isinstance(sql_path, Table):
5965        return sql_path
5966    if not isinstance(sql_path, str):
5967        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5968
5969    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5970    if table:
5971        for k, v in kwargs.items():
5972            table.set(k, v)
5973
5974    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:
5977def to_column(sql_path: str | Column, **kwargs) -> Column:
5978    """
5979    Create a column from a `[table].[column]` sql path. Schema is optional.
5980
5981    If a column is passed in then that column is returned.
5982
5983    Args:
5984        sql_path: `[table].[column]` string
5985    Returns:
5986        Table: A column expression
5987    """
5988    if sql_path is None or isinstance(sql_path, Column):
5989        return sql_path
5990    if not isinstance(sql_path, str):
5991        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5992    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):
5995def alias_(
5996    expression: ExpOrStr,
5997    alias: str | Identifier,
5998    table: bool | t.Sequence[str | Identifier] = False,
5999    quoted: t.Optional[bool] = None,
6000    dialect: DialectType = None,
6001    copy: bool = True,
6002    **opts,
6003):
6004    """Create an Alias expression.
6005
6006    Example:
6007        >>> alias_('foo', 'bar').sql()
6008        'foo AS bar'
6009
6010        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
6011        '(SELECT 1, 2) AS bar(a, b)'
6012
6013    Args:
6014        expression: the SQL code strings to parse.
6015            If an Expression instance is passed, this is used as-is.
6016        alias: the alias name to use. If the name has
6017            special characters it is quoted.
6018        table: Whether or not to create a table alias, can also be a list of columns.
6019        quoted: whether or not to quote the alias
6020        dialect: the dialect used to parse the input expression.
6021        copy: Whether or not to copy the expression.
6022        **opts: other options to use to parse the input expressions.
6023
6024    Returns:
6025        Alias: the aliased expression
6026    """
6027    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
6028    alias = to_identifier(alias, quoted=quoted)
6029
6030    if table:
6031        table_alias = TableAlias(this=alias)
6032        exp.set("alias", table_alias)
6033
6034        if not isinstance(table, bool):
6035            for column in table:
6036                table_alias.append("columns", to_identifier(column, quoted=quoted))
6037
6038        return exp
6039
6040    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
6041    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
6042    # for the complete Window expression.
6043    #
6044    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
6045
6046    if "alias" in exp.arg_types and not isinstance(exp, Window):
6047        exp.set("alias", alias)
6048        return exp
6049    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:
6052def subquery(
6053    expression: ExpOrStr,
6054    alias: t.Optional[Identifier | str] = None,
6055    dialect: DialectType = None,
6056    **opts,
6057) -> Select:
6058    """
6059    Build a subquery expression.
6060
6061    Example:
6062        >>> subquery('select x from tbl', 'bar').select('x').sql()
6063        'SELECT x FROM (SELECT x FROM tbl) AS bar'
6064
6065    Args:
6066        expression: the SQL code strings to parse.
6067            If an Expression instance is passed, this is used as-is.
6068        alias: the alias name to use.
6069        dialect: the dialect used to parse the input expression.
6070        **opts: other options to use to parse the input expressions.
6071
6072    Returns:
6073        A new Select instance with the subquery expression included.
6074    """
6075
6076    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
6077    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:
6080def column(
6081    col: str | Identifier,
6082    table: t.Optional[str | Identifier] = None,
6083    db: t.Optional[str | Identifier] = None,
6084    catalog: t.Optional[str | Identifier] = None,
6085    quoted: t.Optional[bool] = None,
6086) -> Column:
6087    """
6088    Build a Column.
6089
6090    Args:
6091        col: Column name.
6092        table: Table name.
6093        db: Database name.
6094        catalog: Catalog name.
6095        quoted: Whether to force quotes on the column's identifiers.
6096
6097    Returns:
6098        The new Column instance.
6099    """
6100    return Column(
6101        this=to_identifier(col, quoted=quoted),
6102        table=to_identifier(table, quoted=quoted),
6103        db=to_identifier(db, quoted=quoted),
6104        catalog=to_identifier(catalog, quoted=quoted),
6105    )

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:
6108def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
6109    """Cast an expression to a data type.
6110
6111    Example:
6112        >>> cast('x + 1', 'int').sql()
6113        'CAST(x + 1 AS INT)'
6114
6115    Args:
6116        expression: The expression to cast.
6117        to: The datatype to cast to.
6118
6119    Returns:
6120        The new Cast instance.
6121    """
6122    expression = maybe_parse(expression, **opts)
6123    data_type = DataType.build(to, **opts)
6124    expression = Cast(this=expression, to=data_type)
6125    expression.type = data_type
6126    return expression

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:
6129def table_(
6130    table: Identifier | str,
6131    db: t.Optional[Identifier | str] = None,
6132    catalog: t.Optional[Identifier | str] = None,
6133    quoted: t.Optional[bool] = None,
6134    alias: t.Optional[Identifier | str] = None,
6135) -> Table:
6136    """Build a Table.
6137
6138    Args:
6139        table: Table name.
6140        db: Database name.
6141        catalog: Catalog name.
6142        quote: Whether to force quotes on the table's identifiers.
6143        alias: Table's alias.
6144
6145    Returns:
6146        The new Table instance.
6147    """
6148    return Table(
6149        this=to_identifier(table, quoted=quoted) if table else None,
6150        db=to_identifier(db, quoted=quoted) if db else None,
6151        catalog=to_identifier(catalog, quoted=quoted) if catalog else None,
6152        alias=TableAlias(this=to_identifier(alias)) if alias else None,
6153    )

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:
6156def values(
6157    values: t.Iterable[t.Tuple[t.Any, ...]],
6158    alias: t.Optional[str] = None,
6159    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
6160) -> Values:
6161    """Build VALUES statement.
6162
6163    Example:
6164        >>> values([(1, '2')]).sql()
6165        "VALUES (1, '2')"
6166
6167    Args:
6168        values: values statements that will be converted to SQL
6169        alias: optional alias
6170        columns: Optional list of ordered column names or ordered dictionary of column names to types.
6171         If either are provided then an alias is also required.
6172
6173    Returns:
6174        Values: the Values expression object
6175    """
6176    if columns and not alias:
6177        raise ValueError("Alias is required when providing columns")
6178
6179    return Values(
6180        expressions=[convert(tup) for tup in values],
6181        alias=(
6182            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
6183            if columns
6184            else (TableAlias(this=to_identifier(alias)) if alias else None)
6185        ),
6186    )

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:
6189def var(name: t.Optional[ExpOrStr]) -> Var:
6190    """Build a SQL variable.
6191
6192    Example:
6193        >>> repr(var('x'))
6194        '(VAR this: x)'
6195
6196        >>> repr(var(column('x', table='y')))
6197        '(VAR this: x)'
6198
6199    Args:
6200        name: The name of the var or an expression who's name will become the var.
6201
6202    Returns:
6203        The new variable node.
6204    """
6205    if not name:
6206        raise ValueError("Cannot convert empty name into var.")
6207
6208    if isinstance(name, Expression):
6209        name = name.name
6210    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:
6213def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
6214    """Build ALTER TABLE... RENAME... expression
6215
6216    Args:
6217        old_name: The old name of the table
6218        new_name: The new name of the table
6219
6220    Returns:
6221        Alter table expression
6222    """
6223    old_table = to_table(old_name)
6224    new_table = to_table(new_name)
6225    return AlterTable(
6226        this=old_table,
6227        actions=[
6228            RenameTable(this=new_table),
6229        ],
6230    )

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:
6233def convert(value: t.Any, copy: bool = False) -> Expression:
6234    """Convert a python value into an expression object.
6235
6236    Raises an error if a conversion is not possible.
6237
6238    Args:
6239        value: A python object.
6240        copy: Whether or not to copy `value` (only applies to Expressions and collections).
6241
6242    Returns:
6243        Expression: the equivalent expression object.
6244    """
6245    if isinstance(value, Expression):
6246        return maybe_copy(value, copy)
6247    if isinstance(value, str):
6248        return Literal.string(value)
6249    if isinstance(value, bool):
6250        return Boolean(this=value)
6251    if value is None or (isinstance(value, float) and math.isnan(value)):
6252        return NULL
6253    if isinstance(value, numbers.Number):
6254        return Literal.number(value)
6255    if isinstance(value, datetime.datetime):
6256        datetime_literal = Literal.string(
6257            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
6258        )
6259        return TimeStrToTime(this=datetime_literal)
6260    if isinstance(value, datetime.date):
6261        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
6262        return DateStrToDate(this=date_literal)
6263    if isinstance(value, tuple):
6264        return Tuple(expressions=[convert(v, copy=copy) for v in value])
6265    if isinstance(value, list):
6266        return Array(expressions=[convert(v, copy=copy) for v in value])
6267    if isinstance(value, dict):
6268        return Map(
6269            keys=Array(expressions=[convert(k, copy=copy) for k in value]),
6270            values=Array(expressions=[convert(v, copy=copy) for v in value.values()]),
6271        )
6272    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:
6275def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
6276    """
6277    Replace children of an expression with the result of a lambda fun(child) -> exp.
6278    """
6279    for k, v in expression.args.items():
6280        is_list_arg = type(v) is list
6281
6282        child_nodes = v if is_list_arg else [v]
6283        new_child_nodes = []
6284
6285        for cn in child_nodes:
6286            if isinstance(cn, Expression):
6287                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
6288                    new_child_nodes.append(child_node)
6289                    child_node.parent = expression
6290                    child_node.arg_key = k
6291            else:
6292                new_child_nodes.append(cn)
6293
6294        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]:
6297def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
6298    """
6299    Return all table names referenced through columns in an expression.
6300
6301    Example:
6302        >>> import sqlglot
6303        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
6304        ['a', 'c']
6305
6306    Args:
6307        expression: expression to find table names.
6308        exclude: a table name to exclude
6309
6310    Returns:
6311        A list of unique names.
6312    """
6313    return {
6314        table
6315        for table in (column.table for column in expression.find_all(Column))
6316        if table and table != exclude
6317    }

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:
6320def table_name(table: Table | str, dialect: DialectType = None) -> str:
6321    """Get the full name of a table as a string.
6322
6323    Args:
6324        table: Table expression node or string.
6325        dialect: The dialect to generate the table name for.
6326
6327    Examples:
6328        >>> from sqlglot import exp, parse_one
6329        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
6330        'a.b.c'
6331
6332    Returns:
6333        The table name.
6334    """
6335
6336    table = maybe_parse(table, into=Table, dialect=dialect)
6337
6338    if not table:
6339        raise ValueError(f"Cannot parse {table}")
6340
6341    return ".".join(
6342        part.sql(dialect=dialect, identify=True)
6343        if not SAFE_IDENTIFIER_RE.match(part.name)
6344        else part.name
6345        for part in table.parts
6346    )

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:
6349def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
6350    """Replace all tables in expression according to the mapping.
6351
6352    Args:
6353        expression: expression node to be transformed and replaced.
6354        mapping: mapping of table names.
6355        copy: whether or not to copy the expression.
6356
6357    Examples:
6358        >>> from sqlglot import exp, parse_one
6359        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
6360        'SELECT * FROM c'
6361
6362    Returns:
6363        The mapped expression.
6364    """
6365
6366    def _replace_tables(node: Expression) -> Expression:
6367        if isinstance(node, Table):
6368            new_name = mapping.get(table_name(node))
6369            if new_name:
6370                return to_table(
6371                    new_name,
6372                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
6373                )
6374        return node
6375
6376    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:
6379def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
6380    """Replace placeholders in an expression.
6381
6382    Args:
6383        expression: expression node to be transformed and replaced.
6384        args: positional names that will substitute unnamed placeholders in the given order.
6385        kwargs: keyword arguments that will substitute named placeholders.
6386
6387    Examples:
6388        >>> from sqlglot import exp, parse_one
6389        >>> replace_placeholders(
6390        ...     parse_one("select * from :tbl where ? = ?"),
6391        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
6392        ... ).sql()
6393        "SELECT * FROM foo WHERE str_col = 'b'"
6394
6395    Returns:
6396        The mapped expression.
6397    """
6398
6399    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
6400        if isinstance(node, Placeholder):
6401            if node.name:
6402                new_name = kwargs.get(node.name)
6403                if new_name:
6404                    return convert(new_name)
6405            else:
6406                try:
6407                    return convert(next(args))
6408                except StopIteration:
6409                    pass
6410        return node
6411
6412    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:
6415def expand(
6416    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
6417) -> Expression:
6418    """Transforms an expression by expanding all referenced sources into subqueries.
6419
6420    Examples:
6421        >>> from sqlglot import parse_one
6422        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
6423        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
6424
6425        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
6426        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
6427
6428    Args:
6429        expression: The expression to expand.
6430        sources: A dictionary of name to Subqueryables.
6431        copy: Whether or not to copy the expression during transformation. Defaults to True.
6432
6433    Returns:
6434        The transformed expression.
6435    """
6436
6437    def _expand(node: Expression):
6438        if isinstance(node, Table):
6439            name = table_name(node)
6440            source = sources.get(name)
6441            if source:
6442                subquery = source.subquery(node.alias or name)
6443                subquery.comments = [f"source: {name}"]
6444                return subquery.transform(_expand, copy=False)
6445        return node
6446
6447    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:
6450def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6451    """
6452    Returns a Func expression.
6453
6454    Examples:
6455        >>> func("abs", 5).sql()
6456        'ABS(5)'
6457
6458        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6459        'CAST(5 AS DOUBLE)'
6460
6461    Args:
6462        name: the name of the function to build.
6463        args: the args used to instantiate the function of interest.
6464        dialect: the source dialect.
6465        kwargs: the kwargs used to instantiate the function of interest.
6466
6467    Note:
6468        The arguments `args` and `kwargs` are mutually exclusive.
6469
6470    Returns:
6471        An instance of the function of interest, or an anonymous function, if `name` doesn't
6472        correspond to an existing `sqlglot.expressions.Func` class.
6473    """
6474    if args and kwargs:
6475        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6476
6477    from sqlglot.dialects.dialect import Dialect
6478
6479    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6480    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6481
6482    parser = Dialect.get_or_raise(dialect)().parser()
6483    from_args_list = parser.FUNCTIONS.get(name.upper())
6484
6485    if from_args_list:
6486        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6487    else:
6488        kwargs = kwargs or {"expressions": converted}
6489        function = Anonymous(this=name, **kwargs)
6490
6491    for error_message in function.error_messages(converted):
6492        raise ValueError(error_message)
6493
6494    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:
6497def true() -> Boolean:
6498    """
6499    Returns a true Boolean expression.
6500    """
6501    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> Boolean:
6504def false() -> Boolean:
6505    """
6506    Returns a false Boolean expression.
6507    """
6508    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> Null:
6511def null() -> Null:
6512    """
6513    Returns a Null expression.
6514    """
6515    return Null()

Returns a Null expression.

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