Edit on GitHub

Expressions

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

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


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

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
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 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        "clone": False,
1051    }
arg_types = {'with': False, 'this': True, 'kind': True, 'expression': False, 'exists': False, 'properties': False, 'replace': False, 'unique': False, 'indexes': False, 'no_schema_binding': False, 'begin': False, 'clone': False}
key = 'create'
class Clone(Expression):
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    }
arg_types = {'this': True, 'when': False, 'kind': False, 'shallow': False, 'expression': False, 'copy': False}
key = 'clone'
class Describe(Expression):
1068class Describe(Expression):
1069    arg_types = {"this": True, "kind": False, "expressions": False}
arg_types = {'this': True, 'kind': False, 'expressions': False}
key = 'describe'
class Kill(Expression):
1072class Kill(Expression):
1073    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'kill'
class Pragma(Expression):
1076class Pragma(Expression):
1077    pass
key = 'pragma'
class Set(Expression):
1080class Set(Expression):
1081    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
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    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
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    }
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):
1116class UserDefinedFunction(Expression):
1117    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1120class CharacterSet(Expression):
1121    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
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"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1132class WithinGroup(Expression):
1133    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1136class CTE(DerivedTable):
1137    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1140class TableAlias(Expression):
1141    arg_types = {"this": False, "columns": False}
1142
1143    @property
1144    def columns(self):
1145        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1148class BitString(Condition):
1149    pass
key = 'bitstring'
class HexString(Condition):
1152class HexString(Condition):
1153    pass
key = 'hexstring'
class ByteString(Condition):
1156class ByteString(Condition):
1157    pass
key = 'bytestring'
class RawString(Condition):
1160class RawString(Condition):
1161    pass
key = 'rawstring'
class Column(Condition):
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]
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:
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]

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1205class ColumnPosition(Expression):
1206    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
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 []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
constraints: List[ColumnConstraint]
key = 'columndef'
class AlterColumn(Expression):
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    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1234class RenameTable(Expression):
1235    pass
key = 'renametable'
class Comment(Expression):
1238class Comment(Expression):
1239    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):
1242class Comprehension(Expression):
1243    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):
1247class MergeTreeTTLAction(Expression):
1248    arg_types = {
1249        "this": True,
1250        "delete": False,
1251        "recompress": False,
1252        "to_disk": False,
1253        "to_volume": False,
1254    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1258class MergeTreeTTL(Expression):
1259    arg_types = {
1260        "expressions": True,
1261        "where": False,
1262        "group": False,
1263        "aggregates": False,
1264    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class IndexConstraintOption(Expression):
1268class IndexConstraintOption(Expression):
1269    arg_types = {
1270        "key_block_size": False,
1271        "using": False,
1272        "parser": False,
1273        "comment": False,
1274        "visible": False,
1275        "engine_attr": False,
1276        "secondary_engine_attr": False,
1277    }
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):
1280class ColumnConstraint(Expression):
1281    arg_types = {"this": False, "kind": True}
1282
1283    @property
1284    def kind(self) -> ColumnConstraintKind:
1285        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1288class ColumnConstraintKind(Expression):
1289    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1292class AutoIncrementColumnConstraint(ColumnConstraintKind):
1293    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1296class CaseSpecificColumnConstraint(ColumnConstraintKind):
1297    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1300class CharacterSetColumnConstraint(ColumnConstraintKind):
1301    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1304class CheckColumnConstraint(ColumnConstraintKind):
1305    pass
key = 'checkcolumnconstraint'
class ClusteredColumnConstraint(ColumnConstraintKind):
1308class ClusteredColumnConstraint(ColumnConstraintKind):
1309    pass
key = 'clusteredcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1312class CollateColumnConstraint(ColumnConstraintKind):
1313    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1316class CommentColumnConstraint(ColumnConstraintKind):
1317    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1320class CompressColumnConstraint(ColumnConstraintKind):
1321    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1324class DateFormatColumnConstraint(ColumnConstraintKind):
1325    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1328class DefaultColumnConstraint(ColumnConstraintKind):
1329    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1332class EncodeColumnConstraint(ColumnConstraintKind):
1333    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1336class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1337    # this: True -> ALWAYS, this: False -> BY DEFAULT
1338    arg_types = {
1339        "this": False,
1340        "expression": False,
1341        "on_null": False,
1342        "start": False,
1343        "increment": False,
1344        "minvalue": False,
1345        "maxvalue": False,
1346        "cycle": False,
1347    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class IndexColumnConstraint(ColumnConstraintKind):
1351class IndexColumnConstraint(ColumnConstraintKind):
1352    arg_types = {
1353        "this": False,
1354        "schema": True,
1355        "kind": False,
1356        "index_type": False,
1357        "options": False,
1358    }
arg_types = {'this': False, 'schema': True, 'kind': False, 'index_type': False, 'options': False}
key = 'indexcolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1361class InlineLengthColumnConstraint(ColumnConstraintKind):
1362    pass
key = 'inlinelengthcolumnconstraint'
class NonClusteredColumnConstraint(ColumnConstraintKind):
1365class NonClusteredColumnConstraint(ColumnConstraintKind):
1366    pass
key = 'nonclusteredcolumnconstraint'
class NotForReplicationColumnConstraint(ColumnConstraintKind):
1369class NotForReplicationColumnConstraint(ColumnConstraintKind):
1370    arg_types = {}
arg_types = {}
key = 'notforreplicationcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1373class NotNullColumnConstraint(ColumnConstraintKind):
1374    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1378class OnUpdateColumnConstraint(ColumnConstraintKind):
1379    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1382class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1383    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1386class TitleColumnConstraint(ColumnConstraintKind):
1387    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1390class UniqueColumnConstraint(ColumnConstraintKind):
1391    arg_types = {"this": False, "index_type": False}
arg_types = {'this': False, 'index_type': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1394class UppercaseColumnConstraint(ColumnConstraintKind):
1395    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1398class PathColumnConstraint(ColumnConstraintKind):
1399    pass
key = 'pathcolumnconstraint'
class ComputedColumnConstraint(ColumnConstraintKind):
1404class ComputedColumnConstraint(ColumnConstraintKind):
1405    arg_types = {"this": True, "persisted": False, "not_null": False}
arg_types = {'this': True, 'persisted': False, 'not_null': False}
key = 'computedcolumnconstraint'
class Constraint(Expression):
1408class Constraint(Expression):
1409    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1412class Delete(Expression):
1413    arg_types = {
1414        "with": False,
1415        "this": False,
1416        "using": False,
1417        "where": False,
1418        "returning": False,
1419        "limit": False,
1420        "tables": False,  # Multiple-Table Syntax (MySQL)
1421    }
1422
1423    def delete(
1424        self,
1425        table: ExpOrStr,
1426        dialect: DialectType = None,
1427        copy: bool = True,
1428        **opts,
1429    ) -> Delete:
1430        """
1431        Create a DELETE expression or replace the table on an existing DELETE expression.
1432
1433        Example:
1434            >>> delete("tbl").sql()
1435            'DELETE FROM tbl'
1436
1437        Args:
1438            table: the table from which to delete.
1439            dialect: the dialect used to parse the input expression.
1440            copy: if `False`, modify this expression instance in-place.
1441            opts: other options to use to parse the input expressions.
1442
1443        Returns:
1444            Delete: the modified expression.
1445        """
1446        return _apply_builder(
1447            expression=table,
1448            instance=self,
1449            arg="this",
1450            dialect=dialect,
1451            into=Table,
1452            copy=copy,
1453            **opts,
1454        )
1455
1456    def where(
1457        self,
1458        *expressions: t.Optional[ExpOrStr],
1459        append: bool = True,
1460        dialect: DialectType = None,
1461        copy: bool = True,
1462        **opts,
1463    ) -> Delete:
1464        """
1465        Append to or set the WHERE expressions.
1466
1467        Example:
1468            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1469            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1470
1471        Args:
1472            *expressions: the SQL code strings to parse.
1473                If an `Expression` instance is passed, it will be used as-is.
1474                Multiple expressions are combined with an AND operator.
1475            append: if `True`, AND the new expressions to any existing expression.
1476                Otherwise, this resets the expression.
1477            dialect: the dialect used to parse the input expressions.
1478            copy: if `False`, modify this expression instance in-place.
1479            opts: other options to use to parse the input expressions.
1480
1481        Returns:
1482            Delete: the modified expression.
1483        """
1484        return _apply_conjunction_builder(
1485            *expressions,
1486            instance=self,
1487            arg="where",
1488            append=append,
1489            into=Where,
1490            dialect=dialect,
1491            copy=copy,
1492            **opts,
1493        )
1494
1495    def returning(
1496        self,
1497        expression: ExpOrStr,
1498        dialect: DialectType = None,
1499        copy: bool = True,
1500        **opts,
1501    ) -> Delete:
1502        """
1503        Set the RETURNING expression. Not supported by all dialects.
1504
1505        Example:
1506            >>> delete("tbl").returning("*", dialect="postgres").sql()
1507            'DELETE FROM tbl RETURNING *'
1508
1509        Args:
1510            expression: the SQL code strings to parse.
1511                If an `Expression` instance is passed, it will be used as-is.
1512            dialect: the dialect used to parse the input expressions.
1513            copy: if `False`, modify this expression instance in-place.
1514            opts: other options to use to parse the input expressions.
1515
1516        Returns:
1517            Delete: the modified expression.
1518        """
1519        return _apply_builder(
1520            expression=expression,
1521            instance=self,
1522            arg="returning",
1523            prefix="RETURNING",
1524            dialect=dialect,
1525            copy=copy,
1526            into=Returning,
1527            **opts,
1528        )
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:
1423    def delete(
1424        self,
1425        table: ExpOrStr,
1426        dialect: DialectType = None,
1427        copy: bool = True,
1428        **opts,
1429    ) -> Delete:
1430        """
1431        Create a DELETE expression or replace the table on an existing DELETE expression.
1432
1433        Example:
1434            >>> delete("tbl").sql()
1435            'DELETE FROM tbl'
1436
1437        Args:
1438            table: the table from which to delete.
1439            dialect: the dialect used to parse the input expression.
1440            copy: if `False`, modify this expression instance in-place.
1441            opts: other options to use to parse the input expressions.
1442
1443        Returns:
1444            Delete: the modified expression.
1445        """
1446        return _apply_builder(
1447            expression=table,
1448            instance=self,
1449            arg="this",
1450            dialect=dialect,
1451            into=Table,
1452            copy=copy,
1453            **opts,
1454        )

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

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

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

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

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

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:
2546    def select(
2547        self,
2548        *expressions: t.Optional[ExpOrStr],
2549        append: bool = True,
2550        dialect: DialectType = None,
2551        copy: bool = True,
2552        **opts,
2553    ) -> Union:
2554        """Append to or set the SELECT of the union recursively.
2555
2556        Example:
2557            >>> from sqlglot import parse_one
2558            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2559            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2560
2561        Args:
2562            *expressions: the SQL code strings to parse.
2563                If an `Expression` instance is passed, it will be used as-is.
2564            append: if `True`, add to any existing expressions.
2565                Otherwise, this resets the expressions.
2566            dialect: the dialect used to parse the input expressions.
2567            copy: if `False`, modify this expression instance in-place.
2568            opts: other options to use to parse the input expressions.
2569
2570        Returns:
2571            Union: the modified expression.
2572        """
2573        this = self.copy() if copy else self
2574        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2575        this.expression.unnest().select(
2576            *expressions, append=append, dialect=dialect, copy=False, **opts
2577        )
2578        return this

Append to or set the SELECT of the union recursively.

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

Union: the modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

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

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

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

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

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

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:
2874    def limit(
2875        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2876    ) -> Select:
2877        """
2878        Set the LIMIT expression.
2879
2880        Example:
2881            >>> Select().from_("tbl").select("x").limit(10).sql()
2882            'SELECT x FROM tbl LIMIT 10'
2883
2884        Args:
2885            expression: the SQL code string to parse.
2886                This can also be an integer.
2887                If a `Limit` instance is passed, this is used as-is.
2888                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
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            Select: the modified expression.
2895        """
2896        return _apply_builder(
2897            expression=expression,
2898            instance=self,
2899            arg="limit",
2900            into=Limit,
2901            prefix="LIMIT",
2902            dialect=dialect,
2903            copy=copy,
2904            into_arg="expression",
2905            **opts,
2906        )

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

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

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

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

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

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

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:
3194    def window(
3195        self,
3196        *expressions: t.Optional[ExpOrStr],
3197        append: bool = True,
3198        dialect: DialectType = None,
3199        copy: bool = True,
3200        **opts,
3201    ) -> Select:
3202        return _apply_list_builder(
3203            *expressions,
3204            instance=self,
3205            arg="windows",
3206            append=append,
3207            into=Window,
3208            dialect=dialect,
3209            copy=copy,
3210            **opts,
3211        )
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:
3213    def qualify(
3214        self,
3215        *expressions: t.Optional[ExpOrStr],
3216        append: bool = True,
3217        dialect: DialectType = None,
3218        copy: bool = True,
3219        **opts,
3220    ) -> Select:
3221        return _apply_conjunction_builder(
3222            *expressions,
3223            instance=self,
3224            arg="qualify",
3225            append=append,
3226            into=Qualify,
3227            dialect=dialect,
3228            copy=copy,
3229            **opts,
3230        )
def distinct( self, *ons: Union[str, Expression, NoneType], distinct: bool = True, copy: bool = True) -> Select:
3232    def distinct(
3233        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3234    ) -> Select:
3235        """
3236        Set the OFFSET expression.
3237
3238        Example:
3239            >>> Select().from_("tbl").select("x").distinct().sql()
3240            'SELECT DISTINCT x FROM tbl'
3241
3242        Args:
3243            ons: the expressions to distinct on
3244            distinct: whether the Select should be distinct
3245            copy: if `False`, modify this expression instance in-place.
3246
3247        Returns:
3248            Select: the modified expression.
3249        """
3250        instance = maybe_copy(self, copy)
3251        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3252        instance.set("distinct", Distinct(on=on) if distinct else None)
3253        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:
3255    def ctas(
3256        self,
3257        table: ExpOrStr,
3258        properties: t.Optional[t.Dict] = None,
3259        dialect: DialectType = None,
3260        copy: bool = True,
3261        **opts,
3262    ) -> Create:
3263        """
3264        Convert this expression to a CREATE TABLE AS statement.
3265
3266        Example:
3267            >>> Select().select("*").from_("tbl").ctas("x").sql()
3268            'CREATE TABLE x AS SELECT * FROM tbl'
3269
3270        Args:
3271            table: the SQL code string to parse as the table name.
3272                If another `Expression` instance is passed, it will be used as-is.
3273            properties: an optional mapping of table properties
3274            dialect: the dialect used to parse the input table.
3275            copy: if `False`, modify this expression instance in-place.
3276            opts: other options to use to parse the input table.
3277
3278        Returns:
3279            The new Create expression.
3280        """
3281        instance = maybe_copy(self, copy)
3282        table_expression = maybe_parse(
3283            table,
3284            into=Table,
3285            dialect=dialect,
3286            **opts,
3287        )
3288        properties_expression = None
3289        if properties:
3290            properties_expression = Properties.from_dict(properties)
3291
3292        return Create(
3293            this=table_expression,
3294            kind="table",
3295            expression=instance,
3296            properties=properties_expression,
3297        )

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:
3299    def lock(self, update: bool = True, copy: bool = True) -> Select:
3300        """
3301        Set the locking read mode for this expression.
3302
3303        Examples:
3304            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3305            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3306
3307            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3308            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3309
3310        Args:
3311            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3312            copy: if `False`, modify this expression instance in-place.
3313
3314        Returns:
3315            The modified expression.
3316        """
3317        inst = maybe_copy(self, copy)
3318        inst.set("locks", [Lock(update=update)])
3319
3320        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:
3322    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3323        """
3324        Set hints for this expression.
3325
3326        Examples:
3327            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3328            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3329
3330        Args:
3331            hints: The SQL code strings to parse as the hints.
3332                If an `Expression` instance is passed, it will be used as-is.
3333            dialect: The dialect used to parse the hints.
3334            copy: If `False`, modify this expression instance in-place.
3335
3336        Returns:
3337            The modified expression.
3338        """
3339        inst = maybe_copy(self, copy)
3340        inst.set(
3341            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3342        )
3343
3344        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):
3359class Subquery(DerivedTable, Unionable):
3360    arg_types = {
3361        "this": True,
3362        "alias": False,
3363        "with": False,
3364        **QUERY_MODIFIERS,
3365    }
3366
3367    def unnest(self):
3368        """
3369        Returns the first non subquery.
3370        """
3371        expression = self
3372        while isinstance(expression, Subquery):
3373            expression = expression.this
3374        return expression
3375
3376    def unwrap(self) -> Subquery:
3377        expression = self
3378        while expression.same_parent and expression.is_wrapper:
3379            expression = t.cast(Subquery, expression.parent)
3380        return expression
3381
3382    @property
3383    def is_wrapper(self) -> bool:
3384        """
3385        Whether this Subquery acts as a simple wrapper around another expression.
3386
3387        SELECT * FROM (((SELECT * FROM t)))
3388                      ^
3389                      This corresponds to a "wrapper" Subquery node
3390        """
3391        return all(v is None for k, v in self.args.items() if k != "this")
3392
3393    @property
3394    def is_star(self) -> bool:
3395        return self.this.is_star
3396
3397    @property
3398    def output_name(self) -> str:
3399        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):
3367    def unnest(self):
3368        """
3369        Returns the first non subquery.
3370        """
3371        expression = self
3372        while isinstance(expression, Subquery):
3373            expression = expression.this
3374        return expression

Returns the first non subquery.

def unwrap(self) -> Subquery:
3376    def unwrap(self) -> Subquery:
3377        expression = self
3378        while expression.same_parent and expression.is_wrapper:
3379            expression = t.cast(Subquery, expression.parent)
3380        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):
3402class TableSample(Expression):
3403    arg_types = {
3404        "this": False,
3405        "expressions": False,
3406        "method": False,
3407        "bucket_numerator": False,
3408        "bucket_denominator": False,
3409        "bucket_field": False,
3410        "percent": False,
3411        "rows": False,
3412        "size": False,
3413        "seed": False,
3414        "kind": False,
3415    }
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):
3418class Tag(Expression):
3419    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3420
3421    arg_types = {
3422        "this": False,
3423        "prefix": False,
3424        "postfix": False,
3425    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3430class Pivot(Expression):
3431    arg_types = {
3432        "this": False,
3433        "alias": False,
3434        "expressions": True,
3435        "field": False,
3436        "unpivot": False,
3437        "using": False,
3438        "group": False,
3439        "columns": False,
3440        "include_nulls": False,
3441    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False, 'include_nulls': False}
key = 'pivot'
class Window(Condition):
3444class Window(Condition):
3445    arg_types = {
3446        "this": True,
3447        "partition_by": False,
3448        "order": False,
3449        "spec": False,
3450        "alias": False,
3451        "over": False,
3452        "first": False,
3453    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3456class WindowSpec(Expression):
3457    arg_types = {
3458        "kind": False,
3459        "start": False,
3460        "start_side": False,
3461        "end": False,
3462        "end_side": False,
3463    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3466class Where(Expression):
3467    pass
key = 'where'
class Star(Expression):
3470class Star(Expression):
3471    arg_types = {"except": False, "replace": False}
3472
3473    @property
3474    def name(self) -> str:
3475        return "*"
3476
3477    @property
3478    def output_name(self) -> str:
3479        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):
3482class Parameter(Condition):
3483    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3486class SessionParameter(Condition):
3487    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3490class Placeholder(Condition):
3491    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3494class Null(Condition):
3495    arg_types: t.Dict[str, t.Any] = {}
3496
3497    @property
3498    def name(self) -> str:
3499        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3502class Boolean(Condition):
3503    pass
key = 'boolean'
class DataTypeParam(Expression):
3506class DataTypeParam(Expression):
3507    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypeparam'
class DataType(Expression):
3510class DataType(Expression):
3511    arg_types = {
3512        "this": True,
3513        "expressions": False,
3514        "nested": False,
3515        "values": False,
3516        "prefix": False,
3517        "kind": False,
3518    }
3519
3520    class Type(AutoName):
3521        ARRAY = auto()
3522        BIGDECIMAL = auto()
3523        BIGINT = auto()
3524        BIGSERIAL = auto()
3525        BINARY = auto()
3526        BIT = auto()
3527        BOOLEAN = auto()
3528        CHAR = auto()
3529        DATE = auto()
3530        DATEMULTIRANGE = auto()
3531        DATERANGE = auto()
3532        DATETIME = auto()
3533        DATETIME64 = auto()
3534        DECIMAL = auto()
3535        DOUBLE = auto()
3536        ENUM = auto()
3537        ENUM8 = auto()
3538        ENUM16 = auto()
3539        FIXEDSTRING = auto()
3540        FLOAT = auto()
3541        GEOGRAPHY = auto()
3542        GEOMETRY = auto()
3543        HLLSKETCH = auto()
3544        HSTORE = auto()
3545        IMAGE = auto()
3546        INET = auto()
3547        INT = auto()
3548        INT128 = auto()
3549        INT256 = auto()
3550        INT4MULTIRANGE = auto()
3551        INT4RANGE = auto()
3552        INT8MULTIRANGE = auto()
3553        INT8RANGE = auto()
3554        INTERVAL = auto()
3555        IPADDRESS = auto()
3556        IPPREFIX = auto()
3557        JSON = auto()
3558        JSONB = auto()
3559        LONGBLOB = auto()
3560        LONGTEXT = auto()
3561        LOWCARDINALITY = auto()
3562        MAP = auto()
3563        MEDIUMBLOB = auto()
3564        MEDIUMINT = auto()
3565        MEDIUMTEXT = auto()
3566        MONEY = auto()
3567        NCHAR = auto()
3568        NESTED = auto()
3569        NULL = auto()
3570        NULLABLE = auto()
3571        NUMMULTIRANGE = auto()
3572        NUMRANGE = auto()
3573        NVARCHAR = auto()
3574        OBJECT = auto()
3575        ROWVERSION = auto()
3576        SERIAL = auto()
3577        SET = auto()
3578        SMALLINT = auto()
3579        SMALLMONEY = auto()
3580        SMALLSERIAL = auto()
3581        STRUCT = auto()
3582        SUPER = auto()
3583        TEXT = auto()
3584        TINYBLOB = auto()
3585        TINYTEXT = auto()
3586        TIME = auto()
3587        TIMETZ = auto()
3588        TIMESTAMP = auto()
3589        TIMESTAMPLTZ = auto()
3590        TIMESTAMPTZ = auto()
3591        TINYINT = auto()
3592        TSMULTIRANGE = auto()
3593        TSRANGE = auto()
3594        TSTZMULTIRANGE = auto()
3595        TSTZRANGE = auto()
3596        UBIGINT = auto()
3597        UINT = auto()
3598        UINT128 = auto()
3599        UINT256 = auto()
3600        UMEDIUMINT = auto()
3601        UDECIMAL = auto()
3602        UNIQUEIDENTIFIER = auto()
3603        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3604        USERDEFINED = "USER-DEFINED"
3605        USMALLINT = auto()
3606        UTINYINT = auto()
3607        UUID = auto()
3608        VARBINARY = auto()
3609        VARCHAR = auto()
3610        VARIANT = auto()
3611        XML = auto()
3612        YEAR = auto()
3613
3614    TEXT_TYPES = {
3615        Type.CHAR,
3616        Type.NCHAR,
3617        Type.VARCHAR,
3618        Type.NVARCHAR,
3619        Type.TEXT,
3620    }
3621
3622    INTEGER_TYPES = {
3623        Type.INT,
3624        Type.TINYINT,
3625        Type.SMALLINT,
3626        Type.BIGINT,
3627        Type.INT128,
3628        Type.INT256,
3629    }
3630
3631    FLOAT_TYPES = {
3632        Type.FLOAT,
3633        Type.DOUBLE,
3634    }
3635
3636    NUMERIC_TYPES = {
3637        *INTEGER_TYPES,
3638        *FLOAT_TYPES,
3639    }
3640
3641    TEMPORAL_TYPES = {
3642        Type.TIME,
3643        Type.TIMETZ,
3644        Type.TIMESTAMP,
3645        Type.TIMESTAMPTZ,
3646        Type.TIMESTAMPLTZ,
3647        Type.DATE,
3648        Type.DATETIME,
3649        Type.DATETIME64,
3650    }
3651
3652    @classmethod
3653    def build(
3654        cls,
3655        dtype: str | DataType | DataType.Type,
3656        dialect: DialectType = None,
3657        udt: bool = False,
3658        **kwargs,
3659    ) -> DataType:
3660        """
3661        Constructs a DataType object.
3662
3663        Args:
3664            dtype: the data type of interest.
3665            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3666            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3667                DataType, thus creating a user-defined type.
3668            kawrgs: additional arguments to pass in the constructor of DataType.
3669
3670        Returns:
3671            The constructed DataType object.
3672        """
3673        from sqlglot import parse_one
3674
3675        if isinstance(dtype, str):
3676            if dtype.upper() == "UNKNOWN":
3677                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3678
3679            try:
3680                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3681            except ParseError:
3682                if udt:
3683                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3684                raise
3685        elif isinstance(dtype, DataType.Type):
3686            data_type_exp = DataType(this=dtype)
3687        elif isinstance(dtype, DataType):
3688            return dtype
3689        else:
3690            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3691
3692        return DataType(**{**data_type_exp.args, **kwargs})
3693
3694    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3695        """
3696        Checks whether this DataType matches one of the provided data types. Nested types or precision
3697        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3698
3699        Args:
3700            dtypes: the data types to compare this DataType to.
3701
3702        Returns:
3703            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3704        """
3705        for dtype in dtypes:
3706            other = DataType.build(dtype, udt=True)
3707
3708            if (
3709                other.expressions
3710                or self.this == DataType.Type.USERDEFINED
3711                or other.this == DataType.Type.USERDEFINED
3712            ):
3713                matches = self == other
3714            else:
3715                matches = self.this == other.this
3716
3717            if matches:
3718                return True
3719        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.VARCHAR: 'VARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>}
INTEGER_TYPES = {<Type.INT128: 'INT128'>, <Type.INT: 'INT'>, <Type.INT256: 'INT256'>, <Type.TINYINT: 'TINYINT'>, <Type.BIGINT: 'BIGINT'>, <Type.SMALLINT: 'SMALLINT'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.INT256: 'INT256'>, <Type.FLOAT: 'FLOAT'>, <Type.INT128: 'INT128'>, <Type.INT: 'INT'>, <Type.TINYINT: 'TINYINT'>, <Type.BIGINT: 'BIGINT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.SMALLINT: 'SMALLINT'>}
TEMPORAL_TYPES = {<Type.DATETIME: 'DATETIME'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIME: 'TIME'>, <Type.TIMETZ: 'TIMETZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.DATE: 'DATE'>, <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:
3652    @classmethod
3653    def build(
3654        cls,
3655        dtype: str | DataType | DataType.Type,
3656        dialect: DialectType = None,
3657        udt: bool = False,
3658        **kwargs,
3659    ) -> DataType:
3660        """
3661        Constructs a DataType object.
3662
3663        Args:
3664            dtype: the data type of interest.
3665            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3666            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3667                DataType, thus creating a user-defined type.
3668            kawrgs: additional arguments to pass in the constructor of DataType.
3669
3670        Returns:
3671            The constructed DataType object.
3672        """
3673        from sqlglot import parse_one
3674
3675        if isinstance(dtype, str):
3676            if dtype.upper() == "UNKNOWN":
3677                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3678
3679            try:
3680                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3681            except ParseError:
3682                if udt:
3683                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3684                raise
3685        elif isinstance(dtype, DataType.Type):
3686            data_type_exp = DataType(this=dtype)
3687        elif isinstance(dtype, DataType):
3688            return dtype
3689        else:
3690            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3691
3692        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:
3694    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3695        """
3696        Checks whether this DataType matches one of the provided data types. Nested types or precision
3697        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3698
3699        Args:
3700            dtypes: the data types to compare this DataType to.
3701
3702        Returns:
3703            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3704        """
3705        for dtype in dtypes:
3706            other = DataType.build(dtype, udt=True)
3707
3708            if (
3709                other.expressions
3710                or self.this == DataType.Type.USERDEFINED
3711                or other.this == DataType.Type.USERDEFINED
3712            ):
3713                matches = self == other
3714            else:
3715                matches = self.this == other.this
3716
3717            if matches:
3718                return True
3719        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):
3520    class Type(AutoName):
3521        ARRAY = auto()
3522        BIGDECIMAL = auto()
3523        BIGINT = auto()
3524        BIGSERIAL = auto()
3525        BINARY = auto()
3526        BIT = auto()
3527        BOOLEAN = auto()
3528        CHAR = auto()
3529        DATE = auto()
3530        DATEMULTIRANGE = auto()
3531        DATERANGE = auto()
3532        DATETIME = auto()
3533        DATETIME64 = auto()
3534        DECIMAL = auto()
3535        DOUBLE = auto()
3536        ENUM = auto()
3537        ENUM8 = auto()
3538        ENUM16 = auto()
3539        FIXEDSTRING = auto()
3540        FLOAT = auto()
3541        GEOGRAPHY = auto()
3542        GEOMETRY = auto()
3543        HLLSKETCH = auto()
3544        HSTORE = auto()
3545        IMAGE = auto()
3546        INET = auto()
3547        INT = auto()
3548        INT128 = auto()
3549        INT256 = auto()
3550        INT4MULTIRANGE = auto()
3551        INT4RANGE = auto()
3552        INT8MULTIRANGE = auto()
3553        INT8RANGE = auto()
3554        INTERVAL = auto()
3555        IPADDRESS = auto()
3556        IPPREFIX = auto()
3557        JSON = auto()
3558        JSONB = auto()
3559        LONGBLOB = auto()
3560        LONGTEXT = auto()
3561        LOWCARDINALITY = auto()
3562        MAP = auto()
3563        MEDIUMBLOB = auto()
3564        MEDIUMINT = auto()
3565        MEDIUMTEXT = auto()
3566        MONEY = auto()
3567        NCHAR = auto()
3568        NESTED = auto()
3569        NULL = auto()
3570        NULLABLE = auto()
3571        NUMMULTIRANGE = auto()
3572        NUMRANGE = auto()
3573        NVARCHAR = auto()
3574        OBJECT = auto()
3575        ROWVERSION = auto()
3576        SERIAL = auto()
3577        SET = auto()
3578        SMALLINT = auto()
3579        SMALLMONEY = auto()
3580        SMALLSERIAL = auto()
3581        STRUCT = auto()
3582        SUPER = auto()
3583        TEXT = auto()
3584        TINYBLOB = auto()
3585        TINYTEXT = auto()
3586        TIME = auto()
3587        TIMETZ = auto()
3588        TIMESTAMP = auto()
3589        TIMESTAMPLTZ = auto()
3590        TIMESTAMPTZ = auto()
3591        TINYINT = auto()
3592        TSMULTIRANGE = auto()
3593        TSRANGE = auto()
3594        TSTZMULTIRANGE = auto()
3595        TSTZRANGE = auto()
3596        UBIGINT = auto()
3597        UINT = auto()
3598        UINT128 = auto()
3599        UINT256 = auto()
3600        UMEDIUMINT = auto()
3601        UDECIMAL = auto()
3602        UNIQUEIDENTIFIER = auto()
3603        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3604        USERDEFINED = "USER-DEFINED"
3605        USMALLINT = auto()
3606        UTINYINT = auto()
3607        UUID = auto()
3608        VARBINARY = auto()
3609        VARCHAR = auto()
3610        VARIANT = auto()
3611        XML = auto()
3612        YEAR = auto()

An enumeration.

ARRAY = <Type.ARRAY: 'ARRAY'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <Type.BIGINT: 'BIGINT'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
BINARY = <Type.BINARY: 'BINARY'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
CHAR = <Type.CHAR: 'CHAR'>
DATE = <Type.DATE: 'DATE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
ENUM = <Type.ENUM: 'ENUM'>
ENUM8 = <Type.ENUM8: 'ENUM8'>
ENUM16 = <Type.ENUM16: 'ENUM16'>
FIXEDSTRING = <Type.FIXEDSTRING: 'FIXEDSTRING'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
IPADDRESS = <Type.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <Type.IPPREFIX: 'IPPREFIX'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
LOWCARDINALITY = <Type.LOWCARDINALITY: 'LOWCARDINALITY'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMINT = <Type.MEDIUMINT: 'MEDIUMINT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NESTED = <Type.NESTED: 'NESTED'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TINYBLOB = <Type.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <Type.TINYTEXT: 'TINYTEXT'>
TIME = <Type.TIME: 'TIME'>
TIMETZ = <Type.TIMETZ: 'TIMETZ'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UMEDIUMINT = <Type.UMEDIUMINT: 'UMEDIUMINT'>
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):
3723class PseudoType(DataType):
3724    arg_types = {"this": True}
arg_types = {'this': True}
key = 'pseudotype'
class ObjectIdentifier(DataType):
3728class ObjectIdentifier(DataType):
3729    arg_types = {"this": True}
arg_types = {'this': True}
key = 'objectidentifier'
class SubqueryPredicate(Predicate):
3733class SubqueryPredicate(Predicate):
3734    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3737class All(SubqueryPredicate):
3738    pass
key = 'all'
class Any(SubqueryPredicate):
3741class Any(SubqueryPredicate):
3742    pass
key = 'any'
class Exists(SubqueryPredicate):
3745class Exists(SubqueryPredicate):
3746    pass
key = 'exists'
class Command(Expression):
3751class Command(Expression):
3752    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3755class Transaction(Expression):
3756    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3759class Commit(Expression):
3760    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3763class Rollback(Expression):
3764    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3767class AlterTable(Expression):
3768    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):
3771class AddConstraint(Expression):
3772    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3775class DropPartition(Expression):
3776    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3780class Binary(Condition):
3781    arg_types = {"this": True, "expression": True}
3782
3783    @property
3784    def left(self):
3785        return self.this
3786
3787    @property
3788    def right(self):
3789        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3792class Add(Binary):
3793    pass
key = 'add'
class Connector(Binary):
3796class Connector(Binary):
3797    pass
key = 'connector'
class And(Connector):
3800class And(Connector):
3801    pass
key = 'and'
class Or(Connector):
3804class Or(Connector):
3805    pass
key = 'or'
class BitwiseAnd(Binary):
3808class BitwiseAnd(Binary):
3809    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3812class BitwiseLeftShift(Binary):
3813    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3816class BitwiseOr(Binary):
3817    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3820class BitwiseRightShift(Binary):
3821    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3824class BitwiseXor(Binary):
3825    pass
key = 'bitwisexor'
class Div(Binary):
3828class Div(Binary):
3829    pass
key = 'div'
class Overlaps(Binary):
3832class Overlaps(Binary):
3833    pass
key = 'overlaps'
class Dot(Binary):
3836class Dot(Binary):
3837    @property
3838    def name(self) -> str:
3839        return self.expression.name
3840
3841    @property
3842    def output_name(self) -> str:
3843        return self.name
3844
3845    @classmethod
3846    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3847        """Build a Dot object with a sequence of expressions."""
3848        if len(expressions) < 2:
3849            raise ValueError(f"Dot requires >= 2 expressions.")
3850
3851        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:
3845    @classmethod
3846    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3847        """Build a Dot object with a sequence of expressions."""
3848        if len(expressions) < 2:
3849            raise ValueError(f"Dot requires >= 2 expressions.")
3850
3851        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):
3854class DPipe(Binary):
3855    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3858class SafeDPipe(DPipe):
3859    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3862class EQ(Binary, Predicate):
3863    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3866class NullSafeEQ(Binary, Predicate):
3867    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3870class NullSafeNEQ(Binary, Predicate):
3871    pass
key = 'nullsafeneq'
class Distance(Binary):
3874class Distance(Binary):
3875    pass
key = 'distance'
class Escape(Binary):
3878class Escape(Binary):
3879    pass
key = 'escape'
class Glob(Binary, Predicate):
3882class Glob(Binary, Predicate):
3883    pass
key = 'glob'
class GT(Binary, Predicate):
3886class GT(Binary, Predicate):
3887    pass
key = 'gt'
class GTE(Binary, Predicate):
3890class GTE(Binary, Predicate):
3891    pass
key = 'gte'
class ILike(Binary, Predicate):
3894class ILike(Binary, Predicate):
3895    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3898class ILikeAny(Binary, Predicate):
3899    pass
key = 'ilikeany'
class IntDiv(Binary):
3902class IntDiv(Binary):
3903    pass
key = 'intdiv'
class Is(Binary, Predicate):
3906class Is(Binary, Predicate):
3907    pass
key = 'is'
class Kwarg(Binary):
3910class Kwarg(Binary):
3911    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3914class Like(Binary, Predicate):
3915    pass
key = 'like'
class LikeAny(Binary, Predicate):
3918class LikeAny(Binary, Predicate):
3919    pass
key = 'likeany'
class LT(Binary, Predicate):
3922class LT(Binary, Predicate):
3923    pass
key = 'lt'
class LTE(Binary, Predicate):
3926class LTE(Binary, Predicate):
3927    pass
key = 'lte'
class Mod(Binary):
3930class Mod(Binary):
3931    pass
key = 'mod'
class Mul(Binary):
3934class Mul(Binary):
3935    pass
key = 'mul'
class NEQ(Binary, Predicate):
3938class NEQ(Binary, Predicate):
3939    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3942class SimilarTo(Binary, Predicate):
3943    pass
key = 'similarto'
class Slice(Binary):
3946class Slice(Binary):
3947    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3950class Sub(Binary):
3951    pass
key = 'sub'
class ArrayOverlaps(Binary):
3954class ArrayOverlaps(Binary):
3955    pass
key = 'arrayoverlaps'
class Unary(Condition):
3960class Unary(Condition):
3961    pass
key = 'unary'
class BitwiseNot(Unary):
3964class BitwiseNot(Unary):
3965    pass
key = 'bitwisenot'
class Not(Unary):
3968class Not(Unary):
3969    pass
key = 'not'
class Paren(Unary):
3972class Paren(Unary):
3973    arg_types = {"this": True, "with": False}
3974
3975    @property
3976    def output_name(self) -> str:
3977        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):
3980class Neg(Unary):
3981    pass
key = 'neg'
class Alias(Expression):
3984class Alias(Expression):
3985    arg_types = {"this": True, "alias": False}
3986
3987    @property
3988    def output_name(self) -> str:
3989        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):
3992class Aliases(Expression):
3993    arg_types = {"this": True, "expressions": True}
3994
3995    @property
3996    def aliases(self):
3997        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
4000class AtTimeZone(Expression):
4001    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
4004class Between(Predicate):
4005    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
4008class Bracket(Condition):
4009    arg_types = {"this": True, "expressions": True}
4010
4011    @property
4012    def output_name(self) -> str:
4013        if len(self.expressions) == 1:
4014            return self.expressions[0].output_name
4015
4016        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):
4019class SafeBracket(Bracket):
4020    """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):
4023class Distinct(Expression):
4024    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
4027class In(Predicate):
4028    arg_types = {
4029        "this": True,
4030        "expressions": False,
4031        "query": False,
4032        "unnest": False,
4033        "field": False,
4034        "is_global": False,
4035    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
4038class TimeUnit(Expression):
4039    """Automatically converts unit arg into a var."""
4040
4041    arg_types = {"unit": False}
4042
4043    def __init__(self, **args):
4044        unit = args.get("unit")
4045        if isinstance(unit, (Column, Literal)):
4046            args["unit"] = Var(this=unit.name)
4047        elif isinstance(unit, Week):
4048            unit.set("this", Var(this=unit.this.name))
4049
4050        super().__init__(**args)
4051
4052    @property
4053    def unit(self) -> t.Optional[Var]:
4054        return self.args.get("unit")

Automatically converts unit arg into a var.

TimeUnit(**args)
4043    def __init__(self, **args):
4044        unit = args.get("unit")
4045        if isinstance(unit, (Column, Literal)):
4046            args["unit"] = Var(this=unit.name)
4047        elif isinstance(unit, Week):
4048            unit.set("this", Var(this=unit.this.name))
4049
4050        super().__init__(**args)
arg_types = {'unit': False}
unit: Optional[Var]
key = 'timeunit'
class IntervalOp(TimeUnit):
4057class IntervalOp(TimeUnit):
4058    arg_types = {"unit": True, "expression": True}
4059
4060    def interval(self):
4061        return Interval(
4062            this=self.expression.copy(),
4063            unit=self.unit.copy(),
4064        )
arg_types = {'unit': True, 'expression': True}
def interval(self):
4060    def interval(self):
4061        return Interval(
4062            this=self.expression.copy(),
4063            unit=self.unit.copy(),
4064        )
key = 'intervalop'
class IntervalSpan(DataType):
4070class IntervalSpan(DataType):
4071    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'intervalspan'
class Interval(TimeUnit):
4074class Interval(TimeUnit):
4075    arg_types = {"this": False, "unit": False}
arg_types = {'this': False, 'unit': False}
key = 'interval'
class IgnoreNulls(Expression):
4078class IgnoreNulls(Expression):
4079    pass
key = 'ignorenulls'
class RespectNulls(Expression):
4082class RespectNulls(Expression):
4083    pass
key = 'respectnulls'
class Func(Condition):
4087class Func(Condition):
4088    """
4089    The base class for all function expressions.
4090
4091    Attributes:
4092        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
4093            treated as a variable length argument and the argument's value will be stored as a list.
4094        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
4095            for this function expression. These values are used to map this node to a name during parsing
4096            as well as to provide the function's name during SQL string generation. By default the SQL
4097            name is set to the expression's class name transformed to snake case.
4098    """
4099
4100    is_var_len_args = False
4101
4102    @classmethod
4103    def from_arg_list(cls, args):
4104        if cls.is_var_len_args:
4105            all_arg_keys = list(cls.arg_types)
4106            # If this function supports variable length argument treat the last argument as such.
4107            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4108            num_non_var = len(non_var_len_arg_keys)
4109
4110            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4111            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4112        else:
4113            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4114
4115        return cls(**args_dict)
4116
4117    @classmethod
4118    def sql_names(cls):
4119        if cls is Func:
4120            raise NotImplementedError(
4121                "SQL name is only supported by concrete function implementations"
4122            )
4123        if "_sql_names" not in cls.__dict__:
4124            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4125        return cls._sql_names
4126
4127    @classmethod
4128    def sql_name(cls):
4129        return cls.sql_names()[0]
4130
4131    @classmethod
4132    def default_parser_mappings(cls):
4133        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):
4102    @classmethod
4103    def from_arg_list(cls, args):
4104        if cls.is_var_len_args:
4105            all_arg_keys = list(cls.arg_types)
4106            # If this function supports variable length argument treat the last argument as such.
4107            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4108            num_non_var = len(non_var_len_arg_keys)
4109
4110            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4111            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4112        else:
4113            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4114
4115        return cls(**args_dict)
@classmethod
def sql_names(cls):
4117    @classmethod
4118    def sql_names(cls):
4119        if cls is Func:
4120            raise NotImplementedError(
4121                "SQL name is only supported by concrete function implementations"
4122            )
4123        if "_sql_names" not in cls.__dict__:
4124            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4125        return cls._sql_names
@classmethod
def sql_name(cls):
4127    @classmethod
4128    def sql_name(cls):
4129        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
4131    @classmethod
4132    def default_parser_mappings(cls):
4133        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
4136class AggFunc(Func):
4137    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
4140class ParameterizedAgg(AggFunc):
4141    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
4144class Abs(Func):
4145    pass
key = 'abs'
class Transform(Func):
4149class Transform(Func):
4150    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
4153class Anonymous(Func):
4154    arg_types = {"this": True, "expressions": False}
4155    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
4160class Hll(AggFunc):
4161    arg_types = {"this": True, "expressions": False}
4162    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
4165class ApproxDistinct(AggFunc):
4166    arg_types = {"this": True, "accuracy": False}
4167    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
4170class Array(Func):
4171    arg_types = {"expressions": False}
4172    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
4176class ToChar(Func):
4177    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
4180class GenerateSeries(Func):
4181    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
4184class ArrayAgg(AggFunc):
4185    pass
key = 'arrayagg'
class ArrayAll(Func):
4188class ArrayAll(Func):
4189    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4192class ArrayAny(Func):
4193    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4196class ArrayConcat(Func):
4197    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4198    arg_types = {"this": True, "expressions": False}
4199    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4202class ArrayContains(Binary, Func):
4203    pass
key = 'arraycontains'
class ArrayContained(Binary):
4206class ArrayContained(Binary):
4207    pass
key = 'arraycontained'
class ArrayFilter(Func):
4210class ArrayFilter(Func):
4211    arg_types = {"this": True, "expression": True}
4212    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4215class ArrayJoin(Func):
4216    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4219class ArraySize(Func):
4220    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4223class ArraySort(Func):
4224    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4227class ArraySum(Func):
4228    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4231class ArrayUnionAgg(AggFunc):
4232    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4235class Avg(AggFunc):
4236    pass
key = 'avg'
class AnyValue(AggFunc):
4239class AnyValue(AggFunc):
4240    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):
4243class First(Func):
4244    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4247class Last(Func):
4248    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4251class Case(Func):
4252    arg_types = {"this": False, "ifs": True, "default": False}
4253
4254    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4255        instance = maybe_copy(self, copy)
4256        instance.append(
4257            "ifs",
4258            If(
4259                this=maybe_parse(condition, copy=copy, **opts),
4260                true=maybe_parse(then, copy=copy, **opts),
4261            ),
4262        )
4263        return instance
4264
4265    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4266        instance = maybe_copy(self, copy)
4267        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4268        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:
4254    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4255        instance = maybe_copy(self, copy)
4256        instance.append(
4257            "ifs",
4258            If(
4259                this=maybe_parse(condition, copy=copy, **opts),
4260                true=maybe_parse(then, copy=copy, **opts),
4261            ),
4262        )
4263        return instance
def else_( self, condition: Union[str, Expression], copy: bool = True, **opts) -> Case:
4265    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4266        instance = maybe_copy(self, copy)
4267        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4268        return instance
key = 'case'
class Cast(Func):
4271class Cast(Func):
4272    arg_types = {"this": True, "to": True, "format": False}
4273
4274    @property
4275    def name(self) -> str:
4276        return self.this.name
4277
4278    @property
4279    def to(self) -> DataType:
4280        return self.args["to"]
4281
4282    @property
4283    def output_name(self) -> str:
4284        return self.name
4285
4286    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4287        """
4288        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4289        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4290        array<int> != array<float>.
4291
4292        Args:
4293            dtypes: the data types to compare this Cast's DataType to.
4294
4295        Returns:
4296            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4297        """
4298        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True, 'format': False}
name: str
to: DataType
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
def is_type( self, *dtypes: str | DataType | DataType.Type) -> bool:
4286    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4287        """
4288        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4289        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4290        array<int> != array<float>.
4291
4292        Args:
4293            dtypes: the data types to compare this Cast's DataType to.
4294
4295        Returns:
4296            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4297        """
4298        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):
4301class TryCast(Cast):
4302    pass
key = 'trycast'
class CastToStrType(Func):
4305class CastToStrType(Func):
4306    arg_types = {"this": True, "to": True}
arg_types = {'this': True, 'to': True}
key = 'casttostrtype'
class Collate(Binary, Func):
4309class Collate(Binary, Func):
4310    pass
key = 'collate'
class Ceil(Func):
4313class Ceil(Func):
4314    arg_types = {"this": True, "decimals": False}
4315    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4318class Coalesce(Func):
4319    arg_types = {"this": True, "expressions": False}
4320    is_var_len_args = True
4321    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Chr(Func):
4324class Chr(Func):
4325    arg_types = {"this": True, "charset": False, "expressions": False}
4326    is_var_len_args = True
4327    _sql_names = ["CHR", "CHAR"]
arg_types = {'this': True, 'charset': False, 'expressions': False}
is_var_len_args = True
key = 'chr'
class Concat(Func):
4330class Concat(Func):
4331    arg_types = {"expressions": True}
4332    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4335class SafeConcat(Concat):
4336    pass
key = 'safeconcat'
class ConcatWs(Concat):
4339class ConcatWs(Concat):
4340    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4343class Count(AggFunc):
4344    arg_types = {"this": False, "expressions": False}
4345    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4348class CountIf(AggFunc):
4349    pass
key = 'countif'
class CurrentDate(Func):
4352class CurrentDate(Func):
4353    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4356class CurrentDatetime(Func):
4357    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4360class CurrentTime(Func):
4361    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4364class CurrentTimestamp(Func):
4365    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4368class CurrentUser(Func):
4369    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, IntervalOp):
4372class DateAdd(Func, IntervalOp):
4373    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, IntervalOp):
4376class DateSub(Func, IntervalOp):
4377    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4380class DateDiff(Func, TimeUnit):
4381    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4382    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4385class DateTrunc(Func):
4386    arg_types = {"unit": True, "this": True, "zone": False}
4387
4388    @property
4389    def unit(self) -> Expression:
4390        return self.args["unit"]
arg_types = {'unit': True, 'this': True, 'zone': False}
unit: Expression
key = 'datetrunc'
class DatetimeAdd(Func, IntervalOp):
4393class DatetimeAdd(Func, IntervalOp):
4394    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, IntervalOp):
4397class DatetimeSub(Func, IntervalOp):
4398    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4401class DatetimeDiff(Func, TimeUnit):
4402    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4405class DatetimeTrunc(Func, TimeUnit):
4406    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4409class DayOfWeek(Func):
4410    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4413class DayOfMonth(Func):
4414    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4417class DayOfYear(Func):
4418    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class ToDays(Func):
4421class ToDays(Func):
4422    pass
key = 'todays'
class WeekOfYear(Func):
4425class WeekOfYear(Func):
4426    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4429class MonthsBetween(Func):
4430    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4433class LastDateOfMonth(Func):
4434    pass
key = 'lastdateofmonth'
class Extract(Func):
4437class Extract(Func):
4438    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class Timestamp(Func):
4441class Timestamp(Func):
4442    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'timestamp'
class TimestampAdd(Func, TimeUnit):
4445class TimestampAdd(Func, TimeUnit):
4446    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4449class TimestampSub(Func, TimeUnit):
4450    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4453class TimestampDiff(Func, TimeUnit):
4454    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4457class TimestampTrunc(Func, TimeUnit):
4458    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4461class TimeAdd(Func, TimeUnit):
4462    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4465class TimeSub(Func, TimeUnit):
4466    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4469class TimeDiff(Func, TimeUnit):
4470    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4473class TimeTrunc(Func, TimeUnit):
4474    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4477class DateFromParts(Func):
4478    _sql_names = ["DATEFROMPARTS"]
4479    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4482class DateStrToDate(Func):
4483    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4486class DateToDateStr(Func):
4487    pass
key = 'datetodatestr'
class DateToDi(Func):
4490class DateToDi(Func):
4491    pass
key = 'datetodi'
class Date(Func):
4495class Date(Func):
4496    arg_types = {"this": False, "zone": False, "expressions": False}
4497    is_var_len_args = True
arg_types = {'this': False, 'zone': False, 'expressions': False}
is_var_len_args = True
key = 'date'
class Day(Func):
4500class Day(Func):
4501    pass
key = 'day'
class Decode(Func):
4504class Decode(Func):
4505    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4508class DiToDate(Func):
4509    pass
key = 'ditodate'
class Encode(Func):
4512class Encode(Func):
4513    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4516class Exp(Func):
4517    pass
key = 'exp'
class Explode(Func):
4520class Explode(Func):
4521    pass
key = 'explode'
class Floor(Func):
4524class Floor(Func):
4525    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4528class FromBase64(Func):
4529    pass
key = 'frombase64'
class ToBase64(Func):
4532class ToBase64(Func):
4533    pass
key = 'tobase64'
class Greatest(Func):
4536class Greatest(Func):
4537    arg_types = {"this": True, "expressions": False}
4538    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(AggFunc):
4541class GroupConcat(AggFunc):
4542    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4545class Hex(Func):
4546    pass
key = 'hex'
class Xor(Connector, Func):
4549class Xor(Connector, Func):
4550    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4553class If(Func):
4554    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4557class Initcap(Func):
4558    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4561class IsNan(Func):
4562    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class FormatJson(Expression):
4565class FormatJson(Expression):
4566    pass
key = 'formatjson'
class JSONKeyValue(Expression):
4569class JSONKeyValue(Expression):
4570    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4573class JSONObject(Func):
4574    arg_types = {
4575        "expressions": False,
4576        "null_handling": False,
4577        "unique_keys": False,
4578        "return_type": False,
4579        "encoding": False,
4580    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'encoding': False}
key = 'jsonobject'
class JSONArray(Func):
4584class JSONArray(Func):
4585    arg_types = {
4586        "expressions": True,
4587        "null_handling": False,
4588        "return_type": False,
4589        "strict": False,
4590    }
arg_types = {'expressions': True, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarray'
class JSONArrayAgg(Func):
4594class JSONArrayAgg(Func):
4595    arg_types = {
4596        "this": True,
4597        "order": False,
4598        "null_handling": False,
4599        "return_type": False,
4600        "strict": False,
4601    }
arg_types = {'this': True, 'order': False, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarrayagg'
class JSONColumnDef(Expression):
4606class JSONColumnDef(Expression):
4607    arg_types = {"this": True, "kind": False, "path": False}
arg_types = {'this': True, 'kind': False, 'path': False}
key = 'jsoncolumndef'
class JSONTable(Func):
4611class JSONTable(Func):
4612    arg_types = {
4613        "this": True,
4614        "expressions": True,
4615        "path": False,
4616        "error_handling": False,
4617        "empty_handling": False,
4618    }
arg_types = {'this': True, 'expressions': True, 'path': False, 'error_handling': False, 'empty_handling': False}
key = 'jsontable'
class OpenJSONColumnDef(Expression):
4621class OpenJSONColumnDef(Expression):
4622    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):
4625class OpenJSON(Func):
4626    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4629class JSONBContains(Binary):
4630    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4633class JSONExtract(Binary, Func):
4634    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4637class JSONExtractScalar(JSONExtract):
4638    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4641class JSONBExtract(JSONExtract):
4642    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4645class JSONBExtractScalar(JSONExtract):
4646    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4649class JSONFormat(Func):
4650    arg_types = {"this": False, "options": False}
4651    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4655class JSONArrayContains(Binary, Predicate, Func):
4656    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class ParseJSON(Func):
4659class ParseJSON(Func):
4660    # BigQuery, Snowflake have PARSE_JSON, Presto has JSON_PARSE
4661    _sql_names = ["PARSE_JSON", "JSON_PARSE"]
key = 'parsejson'
class Least(Func):
4664class Least(Func):
4665    arg_types = {"this": True, "expressions": False}
4666    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4669class Left(Func):
4670    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4677class Length(Func):
4678    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4681class Levenshtein(Func):
4682    arg_types = {
4683        "this": True,
4684        "expression": False,
4685        "ins_cost": False,
4686        "del_cost": False,
4687        "sub_cost": False,
4688    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4691class Ln(Func):
4692    pass
key = 'ln'
class Log(Func):
4695class Log(Func):
4696    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4699class Log2(Func):
4700    pass
key = 'log2'
class Log10(Func):
4703class Log10(Func):
4704    pass
key = 'log10'
class LogicalOr(AggFunc):
4707class LogicalOr(AggFunc):
4708    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4711class LogicalAnd(AggFunc):
4712    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4715class Lower(Func):
4716    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4719class Map(Func):
4720    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4723class MapFromEntries(Func):
4724    pass
key = 'mapfromentries'
class StarMap(Func):
4727class StarMap(Func):
4728    pass
key = 'starmap'
class VarMap(Func):
4731class VarMap(Func):
4732    arg_types = {"keys": True, "values": True}
4733    is_var_len_args = True
4734
4735    @property
4736    def keys(self) -> t.List[Expression]:
4737        return self.args["keys"].expressions
4738
4739    @property
4740    def values(self) -> t.List[Expression]:
4741        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):
4745class MatchAgainst(Func):
4746    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4749class Max(AggFunc):
4750    arg_types = {"this": True, "expressions": False}
4751    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4754class MD5(Func):
4755    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4759class MD5Digest(Func):
4760    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4763class Min(AggFunc):
4764    arg_types = {"this": True, "expressions": False}
4765    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4768class Month(Func):
4769    pass
key = 'month'
class Nvl2(Func):
4772class Nvl2(Func):
4773    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4776class Posexplode(Func):
4777    pass
key = 'posexplode'
class Pow(Binary, Func):
4780class Pow(Binary, Func):
4781    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4784class PercentileCont(AggFunc):
4785    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4788class PercentileDisc(AggFunc):
4789    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4792class Quantile(AggFunc):
4793    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4796class ApproxQuantile(Quantile):
4797    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):
4800class RangeN(Func):
4801    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4804class ReadCSV(Func):
4805    _sql_names = ["READ_CSV"]
4806    is_var_len_args = True
4807    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4810class Reduce(Func):
4811    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):
4814class RegexpExtract(Func):
4815    arg_types = {
4816        "this": True,
4817        "expression": True,
4818        "position": False,
4819        "occurrence": False,
4820        "parameters": False,
4821        "group": False,
4822    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4825class RegexpReplace(Func):
4826    arg_types = {
4827        "this": True,
4828        "expression": True,
4829        "replacement": True,
4830        "position": False,
4831        "occurrence": False,
4832        "parameters": False,
4833    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4836class RegexpLike(Binary, Func):
4837    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4840class RegexpILike(Func):
4841    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4846class RegexpSplit(Func):
4847    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4850class Repeat(Func):
4851    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4854class Round(Func):
4855    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4858class RowNumber(Func):
4859    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4862class SafeDivide(Func):
4863    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4866class SetAgg(AggFunc):
4867    pass
key = 'setagg'
class SHA(Func):
4870class SHA(Func):
4871    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4874class SHA2(Func):
4875    _sql_names = ["SHA2"]
4876    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4879class SortArray(Func):
4880    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4883class Split(Func):
4884    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4889class Substring(Func):
4890    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4893class StandardHash(Func):
4894    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4897class StartsWith(Func):
4898    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4899    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4902class StrPosition(Func):
4903    arg_types = {
4904        "this": True,
4905        "substr": True,
4906        "position": False,
4907        "instance": False,
4908    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4911class StrToDate(Func):
4912    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4915class StrToTime(Func):
4916    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4921class StrToUnix(Func):
4922    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
4927class StrToMap(Func):
4928    arg_types = {
4929        "this": True,
4930        "pair_delim": False,
4931        "key_value_delim": False,
4932        "duplicate_resolution_callback": False,
4933    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
4936class NumberToStr(Func):
4937    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
4940class FromBase(Func):
4941    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4944class Struct(Func):
4945    arg_types = {"expressions": True}
4946    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4949class StructExtract(Func):
4950    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Stuff(Func):
4955class Stuff(Func):
4956    _sql_names = ["STUFF", "INSERT"]
4957    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):
4960class Sum(AggFunc):
4961    pass
key = 'sum'
class Sqrt(Func):
4964class Sqrt(Func):
4965    pass
key = 'sqrt'
class Stddev(AggFunc):
4968class Stddev(AggFunc):
4969    pass
key = 'stddev'
class StddevPop(AggFunc):
4972class StddevPop(AggFunc):
4973    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4976class StddevSamp(AggFunc):
4977    pass
key = 'stddevsamp'
class TimeToStr(Func):
4980class TimeToStr(Func):
4981    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
4984class TimeToTimeStr(Func):
4985    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4988class TimeToUnix(Func):
4989    pass
key = 'timetounix'
class TimeStrToDate(Func):
4992class TimeStrToDate(Func):
4993    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4996class TimeStrToTime(Func):
4997    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
5000class TimeStrToUnix(Func):
5001    pass
key = 'timestrtounix'
class Trim(Func):
5004class Trim(Func):
5005    arg_types = {
5006        "this": True,
5007        "expression": False,
5008        "position": False,
5009        "collation": False,
5010    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
5013class TsOrDsAdd(Func, TimeUnit):
5014    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
5017class TsOrDsToDateStr(Func):
5018    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
5021class TsOrDsToDate(Func):
5022    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
5025class TsOrDiToDi(Func):
5026    pass
key = 'tsorditodi'
class Unhex(Func):
5029class Unhex(Func):
5030    pass
key = 'unhex'
class UnixToStr(Func):
5033class UnixToStr(Func):
5034    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
5039class UnixToTime(Func):
5040    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
5041
5042    SECONDS = Literal.string("seconds")
5043    MILLIS = Literal.string("millis")
5044    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):
5047class UnixToTimeStr(Func):
5048    pass
key = 'unixtotimestr'
class Upper(Func):
5051class Upper(Func):
5052    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
5055class Variance(AggFunc):
5056    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
5059class VariancePop(AggFunc):
5060    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
5063class Week(Func):
5064    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
5067class XMLTable(Func):
5068    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):
5071class Year(Func):
5072    pass
key = 'year'
class Use(Expression):
5075class Use(Expression):
5076    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
5079class Merge(Expression):
5080    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
arg_types = {'this': True, 'using': True, 'on': True, 'expressions': True}
key = 'merge'
class When(Func):
5083class When(Func):
5084    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):
5089class NextValueFor(Func):
5090    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'Abs'>, <class 'AnyValue'>, <class 'ApproxDistinct'>, <class 'ApproxQuantile'>, <class 'Array'>, <class 'ArrayAgg'>, <class 'ArrayAll'>, <class 'ArrayAny'>, <class 'ArrayConcat'>, <class 'ArrayContains'>, <class 'ArrayFilter'>, <class 'ArrayJoin'>, <class 'ArraySize'>, <class 'ArraySort'>, <class 'ArraySum'>, <class 'ArrayUnionAgg'>, <class 'Avg'>, <class 'Case'>, <class 'Cast'>, <class 'CastToStrType'>, <class 'Ceil'>, <class '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 'Extract'>, <class 'First'>, <class 'Floor'>, <class 'FromBase'>, <class 'FromBase64'>, <class 'GenerateSeries'>, <class 'Greatest'>, <class 'GroupConcat'>, <class 'Hex'>, <class 'Hll'>, <class 'If'>, <class 'Initcap'>, <class 'IsNan'>, <class 'JSONArray'>, <class 'JSONArrayAgg'>, <class 'JSONArrayContains'>, <class 'JSONBExtract'>, <class 'JSONBExtractScalar'>, <class 'JSONExtract'>, <class 'JSONExtractScalar'>, <class 'JSONFormat'>, <class 'JSONObject'>, <class 'JSONTable'>, <class 'Last'>, <class 'LastDateOfMonth'>, <class 'Least'>, <class 'Left'>, <class 'Length'>, <class 'Levenshtein'>, <class 'Ln'>, <class 'Log'>, <class 'Log10'>, <class 'Log2'>, <class 'LogicalAnd'>, <class 'LogicalOr'>, <class 'Lower'>, <class 'MD5'>, <class 'MD5Digest'>, <class 'Map'>, <class 'MapFromEntries'>, <class 'MatchAgainst'>, <class 'Max'>, <class 'Min'>, <class 'Month'>, <class 'MonthsBetween'>, <class 'NextValueFor'>, <class 'NumberToStr'>, <class 'Nvl2'>, <class 'OpenJSON'>, <class 'ParameterizedAgg'>, <class 'ParseJSON'>, <class 'PercentileCont'>, <class 'PercentileDisc'>, <class 'Posexplode'>, <class 'Pow'>, <class 'Quantile'>, <class 'RangeN'>, <class 'ReadCSV'>, <class 'Reduce'>, <class 'RegexpExtract'>, <class 'RegexpILike'>, <class 'RegexpLike'>, <class 'RegexpReplace'>, <class 'RegexpSplit'>, <class 'Repeat'>, <class 'Right'>, <class 'Round'>, <class 'RowNumber'>, <class 'SHA'>, <class 'SHA2'>, <class 'SafeConcat'>, <class 'SafeDivide'>, <class 'SetAgg'>, <class 'SortArray'>, <class 'Split'>, <class 'Sqrt'>, <class 'StandardHash'>, <class 'StarMap'>, <class 'StartsWith'>, <class 'Stddev'>, <class 'StddevPop'>, <class 'StddevSamp'>, <class 'StrPosition'>, <class 'StrToDate'>, <class 'StrToMap'>, <class 'StrToTime'>, <class 'StrToUnix'>, <class 'Struct'>, <class 'StructExtract'>, <class 'Stuff'>, <class 'Substring'>, <class 'Sum'>, <class 'TimeAdd'>, <class 'TimeDiff'>, <class 'TimeStrToDate'>, <class 'TimeStrToTime'>, <class 'TimeStrToUnix'>, <class 'TimeSub'>, <class 'TimeToStr'>, <class 'TimeToTimeStr'>, <class 'TimeToUnix'>, <class 'TimeTrunc'>, <class 'Timestamp'>, <class 'TimestampAdd'>, <class 'TimestampDiff'>, <class 'TimestampSub'>, <class 'TimestampTrunc'>, <class 'ToBase64'>, <class 'ToChar'>, <class '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:
5127def maybe_parse(
5128    sql_or_expression: ExpOrStr,
5129    *,
5130    into: t.Optional[IntoType] = None,
5131    dialect: DialectType = None,
5132    prefix: t.Optional[str] = None,
5133    copy: bool = False,
5134    **opts,
5135) -> Expression:
5136    """Gracefully handle a possible string or expression.
5137
5138    Example:
5139        >>> maybe_parse("1")
5140        (LITERAL this: 1, is_string: False)
5141        >>> maybe_parse(to_identifier("x"))
5142        (IDENTIFIER this: x, quoted: False)
5143
5144    Args:
5145        sql_or_expression: the SQL code string or an expression
5146        into: the SQLGlot Expression to parse into
5147        dialect: the dialect used to parse the input expressions (in the case that an
5148            input expression is a SQL string).
5149        prefix: a string to prefix the sql with before it gets parsed
5150            (automatically includes a space)
5151        copy: whether or not to copy the expression.
5152        **opts: other options to use to parse the input expressions (again, in the case
5153            that an input expression is a SQL string).
5154
5155    Returns:
5156        Expression: the parsed or given expression.
5157    """
5158    if isinstance(sql_or_expression, Expression):
5159        if copy:
5160            return sql_or_expression.copy()
5161        return sql_or_expression
5162
5163    if sql_or_expression is None:
5164        raise ParseError(f"SQL cannot be None")
5165
5166    import sqlglot
5167
5168    sql = str(sql_or_expression)
5169    if prefix:
5170        sql = f"{prefix} {sql}"
5171
5172    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):
5185def maybe_copy(instance, copy=True):
5186    return instance.copy() if copy and instance else instance
def union( left: Union[str, Expression], right: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Union:
5367def union(
5368    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5369) -> Union:
5370    """
5371    Initializes a syntax tree from one UNION expression.
5372
5373    Example:
5374        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5375        'SELECT * FROM foo UNION SELECT * FROM bla'
5376
5377    Args:
5378        left: the SQL code string corresponding to the left-hand side.
5379            If an `Expression` instance is passed, it will be used as-is.
5380        right: the SQL code string corresponding to the right-hand side.
5381            If an `Expression` instance is passed, it will be used as-is.
5382        distinct: set the DISTINCT flag if and only if this is true.
5383        dialect: the dialect used to parse the input expression.
5384        opts: other options to use to parse the input expressions.
5385
5386    Returns:
5387        The new Union instance.
5388    """
5389    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5390    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5391
5392    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

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

The new Union instance.

def intersect( left: Union[str, Expression], right: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Intersect:
5395def intersect(
5396    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5397) -> Intersect:
5398    """
5399    Initializes a syntax tree from one INTERSECT expression.
5400
5401    Example:
5402        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5403        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5404
5405    Args:
5406        left: the SQL code string corresponding to the left-hand side.
5407            If an `Expression` instance is passed, it will be used as-is.
5408        right: the SQL code string corresponding to the right-hand side.
5409            If an `Expression` instance is passed, it will be used as-is.
5410        distinct: set the DISTINCT flag if and only if this is true.
5411        dialect: the dialect used to parse the input expression.
5412        opts: other options to use to parse the input expressions.
5413
5414    Returns:
5415        The new Intersect instance.
5416    """
5417    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5418    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5419
5420    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

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

The new Intersect instance.

def except_( left: Union[str, Expression], right: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Except:
5423def except_(
5424    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5425) -> Except:
5426    """
5427    Initializes a syntax tree from one EXCEPT expression.
5428
5429    Example:
5430        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5431        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5432
5433    Args:
5434        left: the SQL code string corresponding to the left-hand side.
5435            If an `Expression` instance is passed, it will be used as-is.
5436        right: the SQL code string corresponding to the right-hand side.
5437            If an `Expression` instance is passed, it will be used as-is.
5438        distinct: set the DISTINCT flag if and only if this is true.
5439        dialect: the dialect used to parse the input expression.
5440        opts: other options to use to parse the input expressions.
5441
5442    Returns:
5443        The new Except instance.
5444    """
5445    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5446    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5447
5448    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

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

The new Except instance.

def select( *expressions: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Select:
5451def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5452    """
5453    Initializes a syntax tree from one or multiple SELECT expressions.
5454
5455    Example:
5456        >>> select("col1", "col2").from_("tbl").sql()
5457        'SELECT col1, col2 FROM tbl'
5458
5459    Args:
5460        *expressions: the SQL code string to parse as the expressions of a
5461            SELECT statement. If an Expression instance is passed, this is used as-is.
5462        dialect: the dialect used to parse the input expressions (in the case that an
5463            input expression is a SQL string).
5464        **opts: other options to use to parse the input expressions (again, in the case
5465            that an input expression is a SQL string).
5466
5467    Returns:
5468        Select: the syntax tree for the SELECT statement.
5469    """
5470    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:
5473def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5474    """
5475    Initializes a syntax tree from a FROM expression.
5476
5477    Example:
5478        >>> from_("tbl").select("col1", "col2").sql()
5479        'SELECT col1, col2 FROM tbl'
5480
5481    Args:
5482        *expression: the SQL code string to parse as the FROM expressions of a
5483            SELECT statement. If an Expression instance is passed, this is used as-is.
5484        dialect: the dialect used to parse the input expression (in the case that the
5485            input expression is a SQL string).
5486        **opts: other options to use to parse the input expressions (again, in the case
5487            that the input expression is a SQL string).
5488
5489    Returns:
5490        Select: the syntax tree for the SELECT statement.
5491    """
5492    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:
5495def update(
5496    table: str | Table,
5497    properties: dict,
5498    where: t.Optional[ExpOrStr] = None,
5499    from_: t.Optional[ExpOrStr] = None,
5500    dialect: DialectType = None,
5501    **opts,
5502) -> Update:
5503    """
5504    Creates an update statement.
5505
5506    Example:
5507        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5508        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5509
5510    Args:
5511        *properties: dictionary of properties to set which are
5512            auto converted to sql objects eg None -> NULL
5513        where: sql conditional parsed into a WHERE statement
5514        from_: sql statement parsed into a FROM statement
5515        dialect: the dialect used to parse the input expressions.
5516        **opts: other options to use to parse the input expressions.
5517
5518    Returns:
5519        Update: the syntax tree for the UPDATE statement.
5520    """
5521    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5522    update_expr.set(
5523        "expressions",
5524        [
5525            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5526            for k, v in properties.items()
5527        ],
5528    )
5529    if from_:
5530        update_expr.set(
5531            "from",
5532            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5533        )
5534    if isinstance(where, Condition):
5535        where = Where(this=where)
5536    if where:
5537        update_expr.set(
5538            "where",
5539            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5540        )
5541    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:
5544def delete(
5545    table: ExpOrStr,
5546    where: t.Optional[ExpOrStr] = None,
5547    returning: t.Optional[ExpOrStr] = None,
5548    dialect: DialectType = None,
5549    **opts,
5550) -> Delete:
5551    """
5552    Builds a delete statement.
5553
5554    Example:
5555        >>> delete("my_table", where="id > 1").sql()
5556        'DELETE FROM my_table WHERE id > 1'
5557
5558    Args:
5559        where: sql conditional parsed into a WHERE statement
5560        returning: sql conditional parsed into a RETURNING statement
5561        dialect: the dialect used to parse the input expressions.
5562        **opts: other options to use to parse the input expressions.
5563
5564    Returns:
5565        Delete: the syntax tree for the DELETE statement.
5566    """
5567    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5568    if where:
5569        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5570    if returning:
5571        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5572    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:
5575def insert(
5576    expression: ExpOrStr,
5577    into: ExpOrStr,
5578    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5579    overwrite: t.Optional[bool] = None,
5580    dialect: DialectType = None,
5581    copy: bool = True,
5582    **opts,
5583) -> Insert:
5584    """
5585    Builds an INSERT statement.
5586
5587    Example:
5588        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5589        'INSERT INTO tbl VALUES (1, 2, 3)'
5590
5591    Args:
5592        expression: the sql string or expression of the INSERT statement
5593        into: the tbl to insert data to.
5594        columns: optionally the table's column names.
5595        overwrite: whether to INSERT OVERWRITE or not.
5596        dialect: the dialect used to parse the input expressions.
5597        copy: whether or not to copy the expression.
5598        **opts: other options to use to parse the input expressions.
5599
5600    Returns:
5601        Insert: the syntax tree for the INSERT statement.
5602    """
5603    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5604    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5605
5606    if columns:
5607        this = _apply_list_builder(
5608            *columns,
5609            instance=Schema(this=this),
5610            arg="expressions",
5611            into=Identifier,
5612            copy=False,
5613            dialect=dialect,
5614            **opts,
5615        )
5616
5617    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:
5620def condition(
5621    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5622) -> Condition:
5623    """
5624    Initialize a logical condition expression.
5625
5626    Example:
5627        >>> condition("x=1").sql()
5628        'x = 1'
5629
5630        This is helpful for composing larger logical syntax trees:
5631        >>> where = condition("x=1")
5632        >>> where = where.and_("y=1")
5633        >>> Select().from_("tbl").select("*").where(where).sql()
5634        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5635
5636    Args:
5637        *expression: the SQL code string to parse.
5638            If an Expression instance is passed, this is used as-is.
5639        dialect: the dialect used to parse the input expression (in the case that the
5640            input expression is a SQL string).
5641        copy: Whether or not to copy `expression` (only applies to expressions).
5642        **opts: other options to use to parse the input expressions (again, in the case
5643            that the input expression is a SQL string).
5644
5645    Returns:
5646        The new Condition instance
5647    """
5648    return maybe_parse(
5649        expression,
5650        into=Condition,
5651        dialect=dialect,
5652        copy=copy,
5653        **opts,
5654    )

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:
5657def and_(
5658    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5659) -> Condition:
5660    """
5661    Combine multiple conditions with an AND logical operator.
5662
5663    Example:
5664        >>> and_("x=1", and_("y=1", "z=1")).sql()
5665        'x = 1 AND (y = 1 AND z = 1)'
5666
5667    Args:
5668        *expressions: the SQL code strings to parse.
5669            If an Expression instance is passed, this is used as-is.
5670        dialect: the dialect used to parse the input expression.
5671        copy: whether or not to copy `expressions` (only applies to Expressions).
5672        **opts: other options to use to parse the input expressions.
5673
5674    Returns:
5675        And: the new condition
5676    """
5677    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:
5680def or_(
5681    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5682) -> Condition:
5683    """
5684    Combine multiple conditions with an OR logical operator.
5685
5686    Example:
5687        >>> or_("x=1", or_("y=1", "z=1")).sql()
5688        'x = 1 OR (y = 1 OR z = 1)'
5689
5690    Args:
5691        *expressions: the SQL code strings to parse.
5692            If an Expression instance is passed, this is used as-is.
5693        dialect: the dialect used to parse the input expression.
5694        copy: whether or not to copy `expressions` (only applies to Expressions).
5695        **opts: other options to use to parse the input expressions.
5696
5697    Returns:
5698        Or: the new condition
5699    """
5700    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:
5703def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5704    """
5705    Wrap a condition with a NOT operator.
5706
5707    Example:
5708        >>> not_("this_suit='black'").sql()
5709        "NOT this_suit = 'black'"
5710
5711    Args:
5712        expression: the SQL code string to parse.
5713            If an Expression instance is passed, this is used as-is.
5714        dialect: the dialect used to parse the input expression.
5715        copy: whether to copy the expression or not.
5716        **opts: other options to use to parse the input expressions.
5717
5718    Returns:
5719        The new condition.
5720    """
5721    this = condition(
5722        expression,
5723        dialect=dialect,
5724        copy=copy,
5725        **opts,
5726    )
5727    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:
5730def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5731    """
5732    Wrap an expression in parentheses.
5733
5734    Example:
5735        >>> paren("5 + 3").sql()
5736        '(5 + 3)'
5737
5738    Args:
5739        expression: the SQL code string to parse.
5740            If an Expression instance is passed, this is used as-is.
5741        copy: whether to copy the expression or not.
5742
5743    Returns:
5744        The wrapped expression.
5745    """
5746    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):
5764def to_identifier(name, quoted=None, copy=True):
5765    """Builds an identifier.
5766
5767    Args:
5768        name: The name to turn into an identifier.
5769        quoted: Whether or not force quote the identifier.
5770        copy: Whether or not to copy a passed in Identefier node.
5771
5772    Returns:
5773        The identifier ast node.
5774    """
5775
5776    if name is None:
5777        return None
5778
5779    if isinstance(name, Identifier):
5780        identifier = maybe_copy(name, copy)
5781    elif isinstance(name, str):
5782        identifier = Identifier(
5783            this=name,
5784            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5785        )
5786    else:
5787        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5788    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:
5794def to_interval(interval: str | Literal) -> Interval:
5795    """Builds an interval expression from a string like '1 day' or '5 months'."""
5796    if isinstance(interval, Literal):
5797        if not interval.is_string:
5798            raise ValueError("Invalid interval string.")
5799
5800        interval = interval.this
5801
5802    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5803
5804    if not interval_parts:
5805        raise ValueError("Invalid interval string.")
5806
5807    return Interval(
5808        this=Literal.string(interval_parts.group(1)),
5809        unit=Var(this=interval_parts.group(2)),
5810    )

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]:
5823def to_table(
5824    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5825) -> t.Optional[Table]:
5826    """
5827    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5828    If a table is passed in then that table is returned.
5829
5830    Args:
5831        sql_path: a `[catalog].[schema].[table]` string.
5832        dialect: the source dialect according to which the table name will be parsed.
5833        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5834
5835    Returns:
5836        A table expression.
5837    """
5838    if sql_path is None or isinstance(sql_path, Table):
5839        return sql_path
5840    if not isinstance(sql_path, str):
5841        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5842
5843    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5844    if table:
5845        for k, v in kwargs.items():
5846            table.set(k, v)
5847
5848    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:
5851def to_column(sql_path: str | Column, **kwargs) -> Column:
5852    """
5853    Create a column from a `[table].[column]` sql path. Schema is optional.
5854
5855    If a column is passed in then that column is returned.
5856
5857    Args:
5858        sql_path: `[table].[column]` string
5859    Returns:
5860        Table: A column expression
5861    """
5862    if sql_path is None or isinstance(sql_path, Column):
5863        return sql_path
5864    if not isinstance(sql_path, str):
5865        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5866    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):
5869def alias_(
5870    expression: ExpOrStr,
5871    alias: str | Identifier,
5872    table: bool | t.Sequence[str | Identifier] = False,
5873    quoted: t.Optional[bool] = None,
5874    dialect: DialectType = None,
5875    copy: bool = True,
5876    **opts,
5877):
5878    """Create an Alias expression.
5879
5880    Example:
5881        >>> alias_('foo', 'bar').sql()
5882        'foo AS bar'
5883
5884        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5885        '(SELECT 1, 2) AS bar(a, b)'
5886
5887    Args:
5888        expression: the SQL code strings to parse.
5889            If an Expression instance is passed, this is used as-is.
5890        alias: the alias name to use. If the name has
5891            special characters it is quoted.
5892        table: Whether or not to create a table alias, can also be a list of columns.
5893        quoted: whether or not to quote the alias
5894        dialect: the dialect used to parse the input expression.
5895        copy: Whether or not to copy the expression.
5896        **opts: other options to use to parse the input expressions.
5897
5898    Returns:
5899        Alias: the aliased expression
5900    """
5901    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5902    alias = to_identifier(alias, quoted=quoted)
5903
5904    if table:
5905        table_alias = TableAlias(this=alias)
5906        exp.set("alias", table_alias)
5907
5908        if not isinstance(table, bool):
5909            for column in table:
5910                table_alias.append("columns", to_identifier(column, quoted=quoted))
5911
5912        return exp
5913
5914    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5915    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5916    # for the complete Window expression.
5917    #
5918    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5919
5920    if "alias" in exp.arg_types and not isinstance(exp, Window):
5921        exp.set("alias", alias)
5922        return exp
5923    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:
5926def subquery(
5927    expression: ExpOrStr,
5928    alias: t.Optional[Identifier | str] = None,
5929    dialect: DialectType = None,
5930    **opts,
5931) -> Select:
5932    """
5933    Build a subquery expression.
5934
5935    Example:
5936        >>> subquery('select x from tbl', 'bar').select('x').sql()
5937        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5938
5939    Args:
5940        expression: the SQL code strings to parse.
5941            If an Expression instance is passed, this is used as-is.
5942        alias: the alias name to use.
5943        dialect: the dialect used to parse the input expression.
5944        **opts: other options to use to parse the input expressions.
5945
5946    Returns:
5947        A new Select instance with the subquery expression included.
5948    """
5949
5950    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5951    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:
5954def column(
5955    col: str | Identifier,
5956    table: t.Optional[str | Identifier] = None,
5957    db: t.Optional[str | Identifier] = None,
5958    catalog: t.Optional[str | Identifier] = None,
5959    quoted: t.Optional[bool] = None,
5960) -> Column:
5961    """
5962    Build a Column.
5963
5964    Args:
5965        col: Column name.
5966        table: Table name.
5967        db: Database name.
5968        catalog: Catalog name.
5969        quoted: Whether to force quotes on the column's identifiers.
5970
5971    Returns:
5972        The new Column instance.
5973    """
5974    return Column(
5975        this=to_identifier(col, quoted=quoted),
5976        table=to_identifier(table, quoted=quoted),
5977        db=to_identifier(db, quoted=quoted),
5978        catalog=to_identifier(catalog, quoted=quoted),
5979    )

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:
5982def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5983    """Cast an expression to a data type.
5984
5985    Example:
5986        >>> cast('x + 1', 'int').sql()
5987        'CAST(x + 1 AS INT)'
5988
5989    Args:
5990        expression: The expression to cast.
5991        to: The datatype to cast to.
5992
5993    Returns:
5994        The new Cast instance.
5995    """
5996    expression = maybe_parse(expression, **opts)
5997    data_type = DataType.build(to, **opts)
5998    expression = Cast(this=expression, to=data_type)
5999    expression.type = data_type
6000    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:
6003def table_(
6004    table: Identifier | str,
6005    db: t.Optional[Identifier | str] = None,
6006    catalog: t.Optional[Identifier | str] = None,
6007    quoted: t.Optional[bool] = None,
6008    alias: t.Optional[Identifier | str] = None,
6009) -> Table:
6010    """Build a Table.
6011
6012    Args:
6013        table: Table name.
6014        db: Database name.
6015        catalog: Catalog name.
6016        quote: Whether to force quotes on the table's identifiers.
6017        alias: Table's alias.
6018
6019    Returns:
6020        The new Table instance.
6021    """
6022    return Table(
6023        this=to_identifier(table, quoted=quoted) if table else None,
6024        db=to_identifier(db, quoted=quoted) if db else None,
6025        catalog=to_identifier(catalog, quoted=quoted) if catalog else None,
6026        alias=TableAlias(this=to_identifier(alias)) if alias else None,
6027    )

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:
6030def values(
6031    values: t.Iterable[t.Tuple[t.Any, ...]],
6032    alias: t.Optional[str] = None,
6033    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
6034) -> Values:
6035    """Build VALUES statement.
6036
6037    Example:
6038        >>> values([(1, '2')]).sql()
6039        "VALUES (1, '2')"
6040
6041    Args:
6042        values: values statements that will be converted to SQL
6043        alias: optional alias
6044        columns: Optional list of ordered column names or ordered dictionary of column names to types.
6045         If either are provided then an alias is also required.
6046
6047    Returns:
6048        Values: the Values expression object
6049    """
6050    if columns and not alias:
6051        raise ValueError("Alias is required when providing columns")
6052
6053    return Values(
6054        expressions=[convert(tup) for tup in values],
6055        alias=(
6056            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
6057            if columns
6058            else (TableAlias(this=to_identifier(alias)) if alias else None)
6059        ),
6060    )

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:
6063def var(name: t.Optional[ExpOrStr]) -> Var:
6064    """Build a SQL variable.
6065
6066    Example:
6067        >>> repr(var('x'))
6068        '(VAR this: x)'
6069
6070        >>> repr(var(column('x', table='y')))
6071        '(VAR this: x)'
6072
6073    Args:
6074        name: The name of the var or an expression who's name will become the var.
6075
6076    Returns:
6077        The new variable node.
6078    """
6079    if not name:
6080        raise ValueError("Cannot convert empty name into var.")
6081
6082    if isinstance(name, Expression):
6083        name = name.name
6084    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:
6087def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
6088    """Build ALTER TABLE... RENAME... expression
6089
6090    Args:
6091        old_name: The old name of the table
6092        new_name: The new name of the table
6093
6094    Returns:
6095        Alter table expression
6096    """
6097    old_table = to_table(old_name)
6098    new_table = to_table(new_name)
6099    return AlterTable(
6100        this=old_table,
6101        actions=[
6102            RenameTable(this=new_table),
6103        ],
6104    )

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:
6107def convert(value: t.Any, copy: bool = False) -> Expression:
6108    """Convert a python value into an expression object.
6109
6110    Raises an error if a conversion is not possible.
6111
6112    Args:
6113        value: A python object.
6114        copy: Whether or not to copy `value` (only applies to Expressions and collections).
6115
6116    Returns:
6117        Expression: the equivalent expression object.
6118    """
6119    if isinstance(value, Expression):
6120        return maybe_copy(value, copy)
6121    if isinstance(value, str):
6122        return Literal.string(value)
6123    if isinstance(value, bool):
6124        return Boolean(this=value)
6125    if value is None or (isinstance(value, float) and math.isnan(value)):
6126        return NULL
6127    if isinstance(value, numbers.Number):
6128        return Literal.number(value)
6129    if isinstance(value, datetime.datetime):
6130        datetime_literal = Literal.string(
6131            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
6132        )
6133        return TimeStrToTime(this=datetime_literal)
6134    if isinstance(value, datetime.date):
6135        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
6136        return DateStrToDate(this=date_literal)
6137    if isinstance(value, tuple):
6138        return Tuple(expressions=[convert(v, copy=copy) for v in value])
6139    if isinstance(value, list):
6140        return Array(expressions=[convert(v, copy=copy) for v in value])
6141    if isinstance(value, dict):
6142        return Map(
6143            keys=Array(expressions=[convert(k, copy=copy) for k in value]),
6144            values=Array(expressions=[convert(v, copy=copy) for v in value.values()]),
6145        )
6146    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:
6149def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
6150    """
6151    Replace children of an expression with the result of a lambda fun(child) -> exp.
6152    """
6153    for k, v in expression.args.items():
6154        is_list_arg = type(v) is list
6155
6156        child_nodes = v if is_list_arg else [v]
6157        new_child_nodes = []
6158
6159        for cn in child_nodes:
6160            if isinstance(cn, Expression):
6161                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
6162                    new_child_nodes.append(child_node)
6163                    child_node.parent = expression
6164                    child_node.arg_key = k
6165            else:
6166                new_child_nodes.append(cn)
6167
6168        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]:
6171def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
6172    """
6173    Return all table names referenced through columns in an expression.
6174
6175    Example:
6176        >>> import sqlglot
6177        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
6178        ['a', 'c']
6179
6180    Args:
6181        expression: expression to find table names.
6182        exclude: a table name to exclude
6183
6184    Returns:
6185        A list of unique names.
6186    """
6187    return {
6188        table
6189        for table in (column.table for column in expression.find_all(Column))
6190        if table and table != exclude
6191    }

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:
6194def table_name(table: Table | str, dialect: DialectType = None) -> str:
6195    """Get the full name of a table as a string.
6196
6197    Args:
6198        table: Table expression node or string.
6199        dialect: The dialect to generate the table name for.
6200
6201    Examples:
6202        >>> from sqlglot import exp, parse_one
6203        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
6204        'a.b.c'
6205
6206    Returns:
6207        The table name.
6208    """
6209
6210    table = maybe_parse(table, into=Table, dialect=dialect)
6211
6212    if not table:
6213        raise ValueError(f"Cannot parse {table}")
6214
6215    return ".".join(
6216        part.sql(dialect=dialect, identify=True)
6217        if not SAFE_IDENTIFIER_RE.match(part.name)
6218        else part.name
6219        for part in table.parts
6220    )

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:
6223def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
6224    """Replace all tables in expression according to the mapping.
6225
6226    Args:
6227        expression: expression node to be transformed and replaced.
6228        mapping: mapping of table names.
6229        copy: whether or not to copy the expression.
6230
6231    Examples:
6232        >>> from sqlglot import exp, parse_one
6233        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
6234        'SELECT * FROM c'
6235
6236    Returns:
6237        The mapped expression.
6238    """
6239
6240    def _replace_tables(node: Expression) -> Expression:
6241        if isinstance(node, Table):
6242            new_name = mapping.get(table_name(node))
6243            if new_name:
6244                return to_table(
6245                    new_name,
6246                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
6247                )
6248        return node
6249
6250    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:
6253def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
6254    """Replace placeholders in an expression.
6255
6256    Args:
6257        expression: expression node to be transformed and replaced.
6258        args: positional names that will substitute unnamed placeholders in the given order.
6259        kwargs: keyword arguments that will substitute named placeholders.
6260
6261    Examples:
6262        >>> from sqlglot import exp, parse_one
6263        >>> replace_placeholders(
6264        ...     parse_one("select * from :tbl where ? = ?"),
6265        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
6266        ... ).sql()
6267        "SELECT * FROM foo WHERE str_col = 'b'"
6268
6269    Returns:
6270        The mapped expression.
6271    """
6272
6273    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
6274        if isinstance(node, Placeholder):
6275            if node.name:
6276                new_name = kwargs.get(node.name)
6277                if new_name:
6278                    return convert(new_name)
6279            else:
6280                try:
6281                    return convert(next(args))
6282                except StopIteration:
6283                    pass
6284        return node
6285
6286    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:
6289def expand(
6290    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
6291) -> Expression:
6292    """Transforms an expression by expanding all referenced sources into subqueries.
6293
6294    Examples:
6295        >>> from sqlglot import parse_one
6296        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
6297        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
6298
6299        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
6300        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
6301
6302    Args:
6303        expression: The expression to expand.
6304        sources: A dictionary of name to Subqueryables.
6305        copy: Whether or not to copy the expression during transformation. Defaults to True.
6306
6307    Returns:
6308        The transformed expression.
6309    """
6310
6311    def _expand(node: Expression):
6312        if isinstance(node, Table):
6313            name = table_name(node)
6314            source = sources.get(name)
6315            if source:
6316                subquery = source.subquery(node.alias or name)
6317                subquery.comments = [f"source: {name}"]
6318                return subquery.transform(_expand, copy=False)
6319        return node
6320
6321    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:
6324def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6325    """
6326    Returns a Func expression.
6327
6328    Examples:
6329        >>> func("abs", 5).sql()
6330        'ABS(5)'
6331
6332        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6333        'CAST(5 AS DOUBLE)'
6334
6335    Args:
6336        name: the name of the function to build.
6337        args: the args used to instantiate the function of interest.
6338        dialect: the source dialect.
6339        kwargs: the kwargs used to instantiate the function of interest.
6340
6341    Note:
6342        The arguments `args` and `kwargs` are mutually exclusive.
6343
6344    Returns:
6345        An instance of the function of interest, or an anonymous function, if `name` doesn't
6346        correspond to an existing `sqlglot.expressions.Func` class.
6347    """
6348    if args and kwargs:
6349        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6350
6351    from sqlglot.dialects.dialect import Dialect
6352
6353    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6354    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6355
6356    parser = Dialect.get_or_raise(dialect)().parser()
6357    from_args_list = parser.FUNCTIONS.get(name.upper())
6358
6359    if from_args_list:
6360        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6361    else:
6362        kwargs = kwargs or {"expressions": converted}
6363        function = Anonymous(this=name, **kwargs)
6364
6365    for error_message in function.error_messages(converted):
6366        raise ValueError(error_message)
6367
6368    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:
6371def true() -> Boolean:
6372    """
6373    Returns a true Boolean expression.
6374    """
6375    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> Boolean:
6378def false() -> Boolean:
6379    """
6380    Returns a false Boolean expression.
6381    """
6382    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> Null:
6385def null() -> Null:
6386    """
6387    Returns a Null expression.
6388    """
6389    return Null()

Returns a Null expression.

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