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

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
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)
89    def __init__(self, **args: t.Any):
90        self.args: t.Dict[str, t.Any] = args
91        self.parent: t.Optional[Expression] = None
92        self.arg_key: t.Optional[str] = None
93        self.comments: t.Optional[t.List[str]] = None
94        self._type: t.Optional[DataType] = None
95        self._meta: t.Optional[t.Dict[str, t.Any]] = None
96        self._hash: t.Optional[int] = None
97
98        for arg_key, value in self.args.items():
99            self._set_parent(arg_key, value)
key = 'expression'
arg_types = {'this': True}
args: Dict[str, Any]
parent: Optional[sqlglot.expressions.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:
139    def text(self, key) -> str:
140        """
141        Returns a textual representation of the argument corresponding to "key". This can only be used
142        for args that are strings or leaf Expression instances, such as identifiers and literals.
143        """
144        field = self.args.get(key)
145        if isinstance(field, str):
146            return field
147        if isinstance(field, (Identifier, Literal, Var)):
148            return field.this
149        if isinstance(field, (Star, Null)):
150            return field.name
151        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.

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").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
meta: Dict[str, Any]
def copy(self):
249    def copy(self):
250        """
251        Returns a deep copy of the expression.
252        """
253        new = deepcopy(self)
254        new.parent = self.parent
255        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
257    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
258        if self.comments is None:
259            self.comments = []
260        if comments:
261            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
263    def append(self, arg_key: str, value: t.Any) -> None:
264        """
265        Appends value to arg_key if it's a list or sets it as a new list.
266
267        Args:
268            arg_key (str): name of the list expression arg
269            value (Any): value to append to the list
270        """
271        if not isinstance(self.args.get(arg_key), list):
272            self.args[arg_key] = []
273        self.args[arg_key].append(value)
274        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:
276    def set(self, arg_key: str, value: t.Any) -> None:
277        """
278        Sets arg_key to value.
279
280        Args:
281            arg_key: name of the expression arg.
282            value: value to set the arg to.
283        """
284        if value is None:
285            self.args.pop(arg_key, None)
286            return
287
288        self.args[arg_key] = value
289        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, sqlglot.expressions.Expression]]:
310    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
311        """Yields the key and expression for all arguments, exploding list args."""
312        for k, vs in self.args.items():
313            if type(vs) is list:
314                for v in vs:
315                    if hasattr(v, "parent"):
316                        yield k, v
317            else:
318                if hasattr(vs, "parent"):
319                    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]:
321    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
322        """
323        Returns the first node in this tree which matches at least one of
324        the specified types.
325
326        Args:
327            expression_types: the expression type(s) to match.
328            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
329
330        Returns:
331            The node which matches the criteria or None if no such node was found.
332        """
333        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]:
335    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
336        """
337        Returns a generator object which visits all nodes in this tree and only
338        yields those that match at least one of the specified expression types.
339
340        Args:
341            expression_types: the expression type(s) to match.
342            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
343
344        Returns:
345            The generator object.
346        """
347        for expression, *_ in self.walk(bfs=bfs):
348            if isinstance(expression, expression_types):
349                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]:
351    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
352        """
353        Returns a nearest parent matching expression_types.
354
355        Args:
356            expression_types: the expression type(s) to match.
357
358        Returns:
359            The parent node.
360        """
361        ancestor = self.parent
362        while ancestor and not isinstance(ancestor, expression_types):
363            ancestor = ancestor.parent
364        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[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
378    def root(self) -> Expression:
379        """
380        Returns the root expression of this tree.
381        """
382        expression = self
383        while expression.parent:
384            expression = expression.parent
385        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
387    def walk(self, bfs=True, prune=None):
388        """
389        Returns a generator object which visits all nodes in this tree.
390
391        Args:
392            bfs (bool): if set to True the BFS traversal order will be applied,
393                otherwise the DFS traversal will be used instead.
394            prune ((node, parent, arg_key) -> bool): callable that returns True if
395                the generator should stop traversing this branch of the tree.
396
397        Returns:
398            the generator object.
399        """
400        if bfs:
401            yield from self.bfs(prune=prune)
402        else:
403            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):
405    def dfs(self, parent=None, key=None, prune=None):
406        """
407        Returns a generator object which visits all nodes in this tree in
408        the DFS (Depth-first) order.
409
410        Returns:
411            The generator object.
412        """
413        parent = parent or self.parent
414        yield self, parent, key
415        if prune and prune(self, parent, key):
416            return
417
418        for k, v in self.iter_expressions():
419            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):
421    def bfs(self, prune=None):
422        """
423        Returns a generator object which visits all nodes in this tree in
424        the BFS (Breadth-first) order.
425
426        Returns:
427            The generator object.
428        """
429        queue = deque([(self, self.parent, None)])
430
431        while queue:
432            item, parent, key = queue.popleft()
433
434            yield item, parent, key
435            if prune and prune(item, parent, key):
436                continue
437
438            for k, v in item.iter_expressions():
439                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):
441    def unnest(self):
442        """
443        Returns the first non parenthesis child or self.
444        """
445        expression = self
446        while type(expression) is Paren:
447            expression = expression.this
448        return expression

Returns the first non parenthesis child or self.

def unalias(self):
450    def unalias(self):
451        """
452        Returns the inner expression if this is an Alias.
453        """
454        if isinstance(self, Alias):
455            return self.this
456        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
458    def unnest_operands(self):
459        """
460        Returns unnested operands as a tuple.
461        """
462        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
464    def flatten(self, unnest=True):
465        """
466        Returns a generator which yields child nodes who's parents are the same class.
467
468        A AND B AND C -> [A, B, C]
469        """
470        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
471            if not type(node) is self.__class__:
472                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:
480    def sql(self, dialect: DialectType = None, **opts) -> str:
481        """
482        Returns SQL string representation of this tree.
483
484        Args:
485            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
486            opts: other `sqlglot.generator.Generator` options.
487
488        Returns:
489            The SQL string.
490        """
491        from sqlglot.dialects import Dialect
492
493        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):
519    def transform(self, fun, *args, copy=True, **kwargs):
520        """
521        Recursively visits all tree nodes (excluding already transformed ones)
522        and applies the given transformation function to each node.
523
524        Args:
525            fun (function): a function which takes a node as an argument and returns a
526                new transformed node or the same node without modifications. If the function
527                returns None, then the corresponding node will be removed from the syntax tree.
528            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
529                modified in place.
530
531        Returns:
532            The transformed tree.
533        """
534        node = self.copy() if copy else self
535        new_node = fun(node, *args, **kwargs)
536
537        if new_node is None or not isinstance(new_node, Expression):
538            return new_node
539        if new_node is not node:
540            new_node.parent = node.parent
541            return new_node
542
543        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
544        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):
554    def replace(self, expression):
555        """
556        Swap out this expression with a new expression.
557
558        For example::
559
560            >>> tree = Select().select("x").from_("tbl")
561            >>> tree.find(Column).replace(Column(this="y"))
562            (COLUMN this: y)
563            >>> tree.sql()
564            'SELECT y FROM tbl'
565
566        Args:
567            expression: new node
568
569        Returns:
570            The new expression or expressions.
571        """
572        if not self.parent:
573            return expression
574
575        parent = self.parent
576        self.parent = None
577
578        replace_children(parent, lambda child: expression if child is self else child)
579        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:
581    def pop(self: E) -> E:
582        """
583        Remove this expression from its AST.
584
585        Returns:
586            The popped expression.
587        """
588        self.replace(None)
589        return self

Remove this expression from its AST.

Returns:

The popped expression.

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

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
650    @classmethod
651    def load(cls, obj):
652        """
653        Load a dict (as returned by `Expression.dump`) into an Expression instance.
654        """
655        from sqlglot.serde import load
656
657        return load(obj)

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

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

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

key = 'predicate'
class DerivedTable(Expression):
885class DerivedTable(Expression):
886    @property
887    def alias_column_names(self) -> t.List[str]:
888        table_alias = self.args.get("alias")
889        if not table_alias:
890            return []
891        return [c.name for c in table_alias.args.get("columns") or []]
892
893    @property
894    def selects(self) -> t.List[Expression]:
895        return self.this.selects if isinstance(self.this, Subqueryable) else []
896
897    @property
898    def named_selects(self) -> t.List[str]:
899        return [select.output_name for select in self.selects]
alias_column_names: List[str]
named_selects: List[str]
key = 'derivedtable'
class Unionable(Expression):
902class Unionable(Expression):
903    def union(
904        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
905    ) -> Unionable:
906        """
907        Builds a UNION expression.
908
909        Example:
910            >>> import sqlglot
911            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
912            'SELECT * FROM foo UNION SELECT * FROM bla'
913
914        Args:
915            expression: the SQL code string.
916                If an `Expression` instance is passed, it will be used as-is.
917            distinct: set the DISTINCT flag if and only if this is true.
918            dialect: the dialect used to parse the input expression.
919            opts: other options to use to parse the input expressions.
920
921        Returns:
922            The new Union expression.
923        """
924        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
925
926    def intersect(
927        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
928    ) -> Unionable:
929        """
930        Builds an INTERSECT expression.
931
932        Example:
933            >>> import sqlglot
934            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
935            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
936
937        Args:
938            expression: the SQL code string.
939                If an `Expression` instance is passed, it will be used as-is.
940            distinct: set the DISTINCT flag if and only if this is true.
941            dialect: the dialect used to parse the input expression.
942            opts: other options to use to parse the input expressions.
943
944        Returns:
945            The new Intersect expression.
946        """
947        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
948
949    def except_(
950        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
951    ) -> Unionable:
952        """
953        Builds an EXCEPT expression.
954
955        Example:
956            >>> import sqlglot
957            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
958            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
959
960        Args:
961            expression: the SQL code string.
962                If an `Expression` instance is passed, it will be used as-is.
963            distinct: set the DISTINCT flag if and only if this is true.
964            dialect: the dialect used to parse the input expression.
965            opts: other options to use to parse the input expressions.
966
967        Returns:
968            The new Except expression.
969        """
970        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
903    def union(
904        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
905    ) -> Unionable:
906        """
907        Builds a UNION expression.
908
909        Example:
910            >>> import sqlglot
911            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
912            'SELECT * FROM foo UNION SELECT * FROM bla'
913
914        Args:
915            expression: the SQL code string.
916                If an `Expression` instance is passed, it will be used as-is.
917            distinct: set the DISTINCT flag if and only if this is true.
918            dialect: the dialect used to parse the input expression.
919            opts: other options to use to parse the input expressions.
920
921        Returns:
922            The new Union expression.
923        """
924        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, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
926    def intersect(
927        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
928    ) -> Unionable:
929        """
930        Builds an INTERSECT expression.
931
932        Example:
933            >>> import sqlglot
934            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
935            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
936
937        Args:
938            expression: the SQL code string.
939                If an `Expression` instance is passed, it will be used as-is.
940            distinct: set the DISTINCT flag if and only if this is true.
941            dialect: the dialect used to parse the input expression.
942            opts: other options to use to parse the input expressions.
943
944        Returns:
945            The new Intersect expression.
946        """
947        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, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
949    def except_(
950        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
951    ) -> Unionable:
952        """
953        Builds an EXCEPT expression.
954
955        Example:
956            >>> import sqlglot
957            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
958            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
959
960        Args:
961            expression: the SQL code string.
962                If an `Expression` instance is passed, it will be used as-is.
963            distinct: set the DISTINCT flag if and only if this is true.
964            dialect: the dialect used to parse the input expression.
965            opts: other options to use to parse the input expressions.
966
967        Returns:
968            The new Except expression.
969        """
970        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):
973class UDTF(DerivedTable, Unionable):
974    @property
975    def selects(self) -> t.List[Expression]:
976        alias = self.args.get("alias")
977        return alias.columns if alias else []
key = 'udtf'
class Cache(Expression):
980class Cache(Expression):
981    arg_types = {
982        "with": False,
983        "this": True,
984        "lazy": False,
985        "options": False,
986        "expression": False,
987    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
990class Uncache(Expression):
991    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class Create(Expression):
 994class Create(Expression):
 995    arg_types = {
 996        "with": False,
 997        "this": True,
 998        "kind": True,
 999        "expression": False,
1000        "exists": False,
1001        "properties": False,
1002        "replace": False,
1003        "unique": False,
1004        "indexes": False,
1005        "no_schema_binding": False,
1006        "begin": False,
1007        "clone": False,
1008    }
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):
1012class Clone(Expression):
1013    arg_types = {
1014        "this": True,
1015        "when": False,
1016        "kind": False,
1017        "expression": False,
1018    }
arg_types = {'this': True, 'when': False, 'kind': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1021class Describe(Expression):
1022    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'describe'
class Pragma(Expression):
1025class Pragma(Expression):
1026    pass
key = 'pragma'
class Set(Expression):
1029class Set(Expression):
1030    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1033class SetItem(Expression):
1034    arg_types = {
1035        "this": False,
1036        "expressions": False,
1037        "kind": False,
1038        "collate": False,  # MySQL SET NAMES statement
1039        "global": False,
1040    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1043class Show(Expression):
1044    arg_types = {
1045        "this": True,
1046        "target": False,
1047        "offset": False,
1048        "limit": False,
1049        "like": False,
1050        "where": False,
1051        "db": False,
1052        "full": False,
1053        "mutex": False,
1054        "query": False,
1055        "channel": False,
1056        "global": False,
1057        "log": False,
1058        "position": False,
1059        "types": False,
1060    }
arg_types = {'this': True, 'target': False, 'offset': False, 'limit': False, 'like': False, 'where': False, 'db': False, 'full': False, 'mutex': False, 'query': False, 'channel': False, 'global': False, 'log': False, 'position': False, 'types': False}
key = 'show'
class UserDefinedFunction(Expression):
1063class UserDefinedFunction(Expression):
1064    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1067class CharacterSet(Expression):
1068    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1071class With(Expression):
1072    arg_types = {"expressions": True, "recursive": False}
1073
1074    @property
1075    def recursive(self) -> bool:
1076        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1079class WithinGroup(Expression):
1080    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1083class CTE(DerivedTable):
1084    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1087class TableAlias(Expression):
1088    arg_types = {"this": False, "columns": False}
1089
1090    @property
1091    def columns(self):
1092        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1095class BitString(Condition):
1096    pass
key = 'bitstring'
class HexString(Condition):
1099class HexString(Condition):
1100    pass
key = 'hexstring'
class ByteString(Condition):
1103class ByteString(Condition):
1104    pass
key = 'bytestring'
class RawString(Condition):
1107class RawString(Condition):
1108    pass
key = 'rawstring'
class Column(Condition):
1111class Column(Condition):
1112    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1113
1114    @property
1115    def table(self) -> str:
1116        return self.text("table")
1117
1118    @property
1119    def db(self) -> str:
1120        return self.text("db")
1121
1122    @property
1123    def catalog(self) -> str:
1124        return self.text("catalog")
1125
1126    @property
1127    def output_name(self) -> str:
1128        return self.name
1129
1130    @property
1131    def parts(self) -> t.List[Identifier]:
1132        """Return the parts of a column in order catalog, db, table, name."""
1133        return [
1134            t.cast(Identifier, self.args[part])
1135            for part in ("catalog", "db", "table", "this")
1136            if self.args.get(part)
1137        ]
1138
1139    def to_dot(self) -> Dot:
1140        """Converts the column into a dot expression."""
1141        parts = self.parts
1142        parent = self.parent
1143
1144        while parent:
1145            if isinstance(parent, Dot):
1146                parts.append(parent.expression)
1147            parent = parent.parent
1148
1149        return Dot.build(parts)
arg_types = {'this': True, 'table': False, 'db': False, 'catalog': False, 'join_mark': False}
table: str
db: str
catalog: str
output_name: str

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

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

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

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

def to_dot(self) -> sqlglot.expressions.Dot:
1139    def to_dot(self) -> Dot:
1140        """Converts the column into a dot expression."""
1141        parts = self.parts
1142        parent = self.parent
1143
1144        while parent:
1145            if isinstance(parent, Dot):
1146                parts.append(parent.expression)
1147            parent = parent.parent
1148
1149        return Dot.build(parts)

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1152class ColumnPosition(Expression):
1153    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1156class ColumnDef(Expression):
1157    arg_types = {
1158        "this": True,
1159        "kind": False,
1160        "constraints": False,
1161        "exists": False,
1162        "position": False,
1163    }
1164
1165    @property
1166    def constraints(self) -> t.List[ColumnConstraint]:
1167        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
key = 'columndef'
class AlterColumn(Expression):
1170class AlterColumn(Expression):
1171    arg_types = {
1172        "this": True,
1173        "dtype": False,
1174        "collate": False,
1175        "using": False,
1176        "default": False,
1177        "drop": False,
1178    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1181class RenameTable(Expression):
1182    pass
key = 'renametable'
class Comment(Expression):
1185class Comment(Expression):
1186    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
arg_types = {'this': True, 'kind': True, 'expression': True, 'exists': False}
key = 'comment'
class MergeTreeTTLAction(Expression):
1190class MergeTreeTTLAction(Expression):
1191    arg_types = {
1192        "this": True,
1193        "delete": False,
1194        "recompress": False,
1195        "to_disk": False,
1196        "to_volume": False,
1197    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1201class MergeTreeTTL(Expression):
1202    arg_types = {
1203        "expressions": True,
1204        "where": False,
1205        "group": False,
1206        "aggregates": False,
1207    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class ColumnConstraint(Expression):
1210class ColumnConstraint(Expression):
1211    arg_types = {"this": False, "kind": True}
1212
1213    @property
1214    def kind(self) -> ColumnConstraintKind:
1215        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1218class ColumnConstraintKind(Expression):
1219    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1222class AutoIncrementColumnConstraint(ColumnConstraintKind):
1223    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1226class CaseSpecificColumnConstraint(ColumnConstraintKind):
1227    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1230class CharacterSetColumnConstraint(ColumnConstraintKind):
1231    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1234class CheckColumnConstraint(ColumnConstraintKind):
1235    pass
key = 'checkcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1238class CollateColumnConstraint(ColumnConstraintKind):
1239    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1242class CommentColumnConstraint(ColumnConstraintKind):
1243    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1246class CompressColumnConstraint(ColumnConstraintKind):
1247    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1250class DateFormatColumnConstraint(ColumnConstraintKind):
1251    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1254class DefaultColumnConstraint(ColumnConstraintKind):
1255    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1258class EncodeColumnConstraint(ColumnConstraintKind):
1259    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1262class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1263    # this: True -> ALWAYS, this: False -> BY DEFAULT
1264    arg_types = {
1265        "this": False,
1266        "expression": False,
1267        "on_null": False,
1268        "start": False,
1269        "increment": False,
1270        "minvalue": False,
1271        "maxvalue": False,
1272        "cycle": False,
1273    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1276class InlineLengthColumnConstraint(ColumnConstraintKind):
1277    pass
key = 'inlinelengthcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1280class NotNullColumnConstraint(ColumnConstraintKind):
1281    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1285class OnUpdateColumnConstraint(ColumnConstraintKind):
1286    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1289class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1290    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1293class TitleColumnConstraint(ColumnConstraintKind):
1294    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1297class UniqueColumnConstraint(ColumnConstraintKind):
1298    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1301class UppercaseColumnConstraint(ColumnConstraintKind):
1302    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1305class PathColumnConstraint(ColumnConstraintKind):
1306    pass
key = 'pathcolumnconstraint'
class Constraint(Expression):
1309class Constraint(Expression):
1310    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1313class Delete(Expression):
1314    arg_types = {
1315        "with": False,
1316        "this": False,
1317        "using": False,
1318        "where": False,
1319        "returning": False,
1320        "limit": False,
1321        "tables": False,  # Multiple-Table Syntax (MySQL)
1322    }
1323
1324    def delete(
1325        self,
1326        table: ExpOrStr,
1327        dialect: DialectType = None,
1328        copy: bool = True,
1329        **opts,
1330    ) -> Delete:
1331        """
1332        Create a DELETE expression or replace the table on an existing DELETE expression.
1333
1334        Example:
1335            >>> delete("tbl").sql()
1336            'DELETE FROM tbl'
1337
1338        Args:
1339            table: the table from which to delete.
1340            dialect: the dialect used to parse the input expression.
1341            copy: if `False`, modify this expression instance in-place.
1342            opts: other options to use to parse the input expressions.
1343
1344        Returns:
1345            Delete: the modified expression.
1346        """
1347        return _apply_builder(
1348            expression=table,
1349            instance=self,
1350            arg="this",
1351            dialect=dialect,
1352            into=Table,
1353            copy=copy,
1354            **opts,
1355        )
1356
1357    def where(
1358        self,
1359        *expressions: t.Optional[ExpOrStr],
1360        append: bool = True,
1361        dialect: DialectType = None,
1362        copy: bool = True,
1363        **opts,
1364    ) -> Delete:
1365        """
1366        Append to or set the WHERE expressions.
1367
1368        Example:
1369            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1370            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1371
1372        Args:
1373            *expressions: the SQL code strings to parse.
1374                If an `Expression` instance is passed, it will be used as-is.
1375                Multiple expressions are combined with an AND operator.
1376            append: if `True`, AND the new expressions to any existing expression.
1377                Otherwise, this resets the expression.
1378            dialect: the dialect used to parse the input expressions.
1379            copy: if `False`, modify this expression instance in-place.
1380            opts: other options to use to parse the input expressions.
1381
1382        Returns:
1383            Delete: the modified expression.
1384        """
1385        return _apply_conjunction_builder(
1386            *expressions,
1387            instance=self,
1388            arg="where",
1389            append=append,
1390            into=Where,
1391            dialect=dialect,
1392            copy=copy,
1393            **opts,
1394        )
1395
1396    def returning(
1397        self,
1398        expression: ExpOrStr,
1399        dialect: DialectType = None,
1400        copy: bool = True,
1401        **opts,
1402    ) -> Delete:
1403        """
1404        Set the RETURNING expression. Not supported by all dialects.
1405
1406        Example:
1407            >>> delete("tbl").returning("*", dialect="postgres").sql()
1408            'DELETE FROM tbl RETURNING *'
1409
1410        Args:
1411            expression: the SQL code strings to parse.
1412                If an `Expression` instance is passed, it will be used as-is.
1413            dialect: the dialect used to parse the input expressions.
1414            copy: if `False`, modify this expression instance in-place.
1415            opts: other options to use to parse the input expressions.
1416
1417        Returns:
1418            Delete: the modified expression.
1419        """
1420        return _apply_builder(
1421            expression=expression,
1422            instance=self,
1423            arg="returning",
1424            prefix="RETURNING",
1425            dialect=dialect,
1426            copy=copy,
1427            into=Returning,
1428            **opts,
1429        )
arg_types = {'with': False, 'this': False, 'using': False, 'where': False, 'returning': False, 'limit': False, 'tables': False}
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1324    def delete(
1325        self,
1326        table: ExpOrStr,
1327        dialect: DialectType = None,
1328        copy: bool = True,
1329        **opts,
1330    ) -> Delete:
1331        """
1332        Create a DELETE expression or replace the table on an existing DELETE expression.
1333
1334        Example:
1335            >>> delete("tbl").sql()
1336            'DELETE FROM tbl'
1337
1338        Args:
1339            table: the table from which to delete.
1340            dialect: the dialect used to parse the input expression.
1341            copy: if `False`, modify this expression instance in-place.
1342            opts: other options to use to parse the input expressions.
1343
1344        Returns:
1345            Delete: the modified expression.
1346        """
1347        return _apply_builder(
1348            expression=table,
1349            instance=self,
1350            arg="this",
1351            dialect=dialect,
1352            into=Table,
1353            copy=copy,
1354            **opts,
1355        )

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, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1357    def where(
1358        self,
1359        *expressions: t.Optional[ExpOrStr],
1360        append: bool = True,
1361        dialect: DialectType = None,
1362        copy: bool = True,
1363        **opts,
1364    ) -> Delete:
1365        """
1366        Append to or set the WHERE expressions.
1367
1368        Example:
1369            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1370            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1371
1372        Args:
1373            *expressions: the SQL code strings to parse.
1374                If an `Expression` instance is passed, it will be used as-is.
1375                Multiple expressions are combined with an AND operator.
1376            append: if `True`, AND the new expressions to any existing expression.
1377                Otherwise, this resets the expression.
1378            dialect: the dialect used to parse the input expressions.
1379            copy: if `False`, modify this expression instance in-place.
1380            opts: other options to use to parse the input expressions.
1381
1382        Returns:
1383            Delete: the modified expression.
1384        """
1385        return _apply_conjunction_builder(
1386            *expressions,
1387            instance=self,
1388            arg="where",
1389            append=append,
1390            into=Where,
1391            dialect=dialect,
1392            copy=copy,
1393            **opts,
1394        )

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, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1396    def returning(
1397        self,
1398        expression: ExpOrStr,
1399        dialect: DialectType = None,
1400        copy: bool = True,
1401        **opts,
1402    ) -> Delete:
1403        """
1404        Set the RETURNING expression. Not supported by all dialects.
1405
1406        Example:
1407            >>> delete("tbl").returning("*", dialect="postgres").sql()
1408            'DELETE FROM tbl RETURNING *'
1409
1410        Args:
1411            expression: the SQL code strings to parse.
1412                If an `Expression` instance is passed, it will be used as-is.
1413            dialect: the dialect used to parse the input expressions.
1414            copy: if `False`, modify this expression instance in-place.
1415            opts: other options to use to parse the input expressions.
1416
1417        Returns:
1418            Delete: the modified expression.
1419        """
1420        return _apply_builder(
1421            expression=expression,
1422            instance=self,
1423            arg="returning",
1424            prefix="RETURNING",
1425            dialect=dialect,
1426            copy=copy,
1427            into=Returning,
1428            **opts,
1429        )

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):
1432class Drop(Expression):
1433    arg_types = {
1434        "this": False,
1435        "kind": False,
1436        "exists": False,
1437        "temporary": False,
1438        "materialized": False,
1439        "cascade": False,
1440        "constraints": False,
1441        "purge": False,
1442    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1445class Filter(Expression):
1446    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1449class Check(Expression):
1450    pass
key = 'check'
class Directory(Expression):
1453class Directory(Expression):
1454    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1455    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1458class ForeignKey(Expression):
1459    arg_types = {
1460        "expressions": True,
1461        "reference": False,
1462        "delete": False,
1463        "update": False,
1464    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1467class PrimaryKey(Expression):
1468    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1473class Into(Expression):
1474    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1477class From(Expression):
1478    @property
1479    def name(self) -> str:
1480        return self.this.name
1481
1482    @property
1483    def alias_or_name(self) -> str:
1484        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1487class Having(Expression):
1488    pass
key = 'having'
class Hint(Expression):
1491class Hint(Expression):
1492    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1495class JoinHint(Expression):
1496    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1499class Identifier(Expression):
1500    arg_types = {"this": True, "quoted": False}
1501
1502    @property
1503    def quoted(self) -> bool:
1504        return bool(self.args.get("quoted"))
1505
1506    @property
1507    def hashable_args(self) -> t.Any:
1508        return (self.this, self.quoted)
1509
1510    @property
1511    def output_name(self) -> str:
1512        return self.name
arg_types = {'this': True, 'quoted': 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").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'identifier'
class Index(Expression):
1515class Index(Expression):
1516    arg_types = {
1517        "this": False,
1518        "table": False,
1519        "using": False,
1520        "where": False,
1521        "columns": False,
1522        "unique": False,
1523        "primary": False,
1524        "amp": False,  # teradata
1525        "partition_by": False,  # teradata
1526    }
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(Expression):
1529class Insert(Expression):
1530    arg_types = {
1531        "with": False,
1532        "this": True,
1533        "expression": False,
1534        "conflict": False,
1535        "returning": False,
1536        "overwrite": False,
1537        "exists": False,
1538        "partition": False,
1539        "alternative": False,
1540        "where": False,
1541        "ignore": False,
1542    }
1543
1544    def with_(
1545        self,
1546        alias: ExpOrStr,
1547        as_: ExpOrStr,
1548        recursive: t.Optional[bool] = None,
1549        append: bool = True,
1550        dialect: DialectType = None,
1551        copy: bool = True,
1552        **opts,
1553    ) -> Insert:
1554        """
1555        Append to or set the common table expressions.
1556
1557        Example:
1558            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1559            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1560
1561        Args:
1562            alias: the SQL code string to parse as the table name.
1563                If an `Expression` instance is passed, this is used as-is.
1564            as_: the SQL code string to parse as the table expression.
1565                If an `Expression` instance is passed, it will be used as-is.
1566            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1567            append: if `True`, add to any existing expressions.
1568                Otherwise, this resets the expressions.
1569            dialect: the dialect used to parse the input expression.
1570            copy: if `False`, modify this expression instance in-place.
1571            opts: other options to use to parse the input expressions.
1572
1573        Returns:
1574            The modified expression.
1575        """
1576        return _apply_cte_builder(
1577            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1578        )
arg_types = {'with': False, 'this': True, 'expression': False, 'conflict': False, 'returning': False, 'overwrite': False, 'exists': False, 'partition': False, 'alternative': False, 'where': False, 'ignore': False}
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.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) -> sqlglot.expressions.Insert:
1544    def with_(
1545        self,
1546        alias: ExpOrStr,
1547        as_: ExpOrStr,
1548        recursive: t.Optional[bool] = None,
1549        append: bool = True,
1550        dialect: DialectType = None,
1551        copy: bool = True,
1552        **opts,
1553    ) -> Insert:
1554        """
1555        Append to or set the common table expressions.
1556
1557        Example:
1558            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1559            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1560
1561        Args:
1562            alias: the SQL code string to parse as the table name.
1563                If an `Expression` instance is passed, this is used as-is.
1564            as_: the SQL code string to parse as the table expression.
1565                If an `Expression` instance is passed, it will be used as-is.
1566            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1567            append: if `True`, add to any existing expressions.
1568                Otherwise, this resets the expressions.
1569            dialect: the dialect used to parse the input expression.
1570            copy: if `False`, modify this expression instance in-place.
1571            opts: other options to use to parse the input expressions.
1572
1573        Returns:
1574            The modified expression.
1575        """
1576        return _apply_cte_builder(
1577            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1578        )

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):
1581class OnConflict(Expression):
1582    arg_types = {
1583        "duplicate": False,
1584        "expressions": False,
1585        "nothing": False,
1586        "key": False,
1587        "constraint": False,
1588    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1591class Returning(Expression):
1592    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1596class Introducer(Expression):
1597    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1601class National(Expression):
1602    pass
key = 'national'
class LoadData(Expression):
1605class LoadData(Expression):
1606    arg_types = {
1607        "this": True,
1608        "local": False,
1609        "overwrite": False,
1610        "inpath": True,
1611        "partition": False,
1612        "input_format": False,
1613        "serde": False,
1614    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1617class Partition(Expression):
1618    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1621class Fetch(Expression):
1622    arg_types = {
1623        "direction": False,
1624        "count": False,
1625        "percent": False,
1626        "with_ties": False,
1627    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1630class Group(Expression):
1631    arg_types = {
1632        "expressions": False,
1633        "grouping_sets": False,
1634        "cube": False,
1635        "rollup": False,
1636        "totals": False,
1637        "all": False,
1638    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1641class Lambda(Expression):
1642    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1645class Limit(Expression):
1646    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1649class Literal(Condition):
1650    arg_types = {"this": True, "is_string": True}
1651
1652    @property
1653    def hashable_args(self) -> t.Any:
1654        return (self.this, self.args.get("is_string"))
1655
1656    @classmethod
1657    def number(cls, number) -> Literal:
1658        return cls(this=str(number), is_string=False)
1659
1660    @classmethod
1661    def string(cls, string) -> Literal:
1662        return cls(this=str(string), is_string=True)
1663
1664    @property
1665    def output_name(self) -> str:
1666        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1656    @classmethod
1657    def number(cls, number) -> Literal:
1658        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1660    @classmethod
1661    def string(cls, string) -> Literal:
1662        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").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'literal'
class Join(Expression):
1669class Join(Expression):
1670    arg_types = {
1671        "this": True,
1672        "on": False,
1673        "side": False,
1674        "kind": False,
1675        "using": False,
1676        "method": False,
1677        "global": False,
1678        "hint": False,
1679    }
1680
1681    @property
1682    def method(self) -> str:
1683        return self.text("method").upper()
1684
1685    @property
1686    def kind(self) -> str:
1687        return self.text("kind").upper()
1688
1689    @property
1690    def side(self) -> str:
1691        return self.text("side").upper()
1692
1693    @property
1694    def hint(self) -> str:
1695        return self.text("hint").upper()
1696
1697    @property
1698    def alias_or_name(self) -> str:
1699        return self.this.alias_or_name
1700
1701    def on(
1702        self,
1703        *expressions: t.Optional[ExpOrStr],
1704        append: bool = True,
1705        dialect: DialectType = None,
1706        copy: bool = True,
1707        **opts,
1708    ) -> Join:
1709        """
1710        Append to or set the ON expressions.
1711
1712        Example:
1713            >>> import sqlglot
1714            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1715            'JOIN x ON y = 1'
1716
1717        Args:
1718            *expressions: the SQL code strings to parse.
1719                If an `Expression` instance is passed, it will be used as-is.
1720                Multiple expressions are combined with an AND operator.
1721            append: if `True`, AND the new expressions to any existing expression.
1722                Otherwise, this resets the expression.
1723            dialect: the dialect used to parse the input expressions.
1724            copy: if `False`, modify this expression instance in-place.
1725            opts: other options to use to parse the input expressions.
1726
1727        Returns:
1728            The modified Join expression.
1729        """
1730        join = _apply_conjunction_builder(
1731            *expressions,
1732            instance=self,
1733            arg="on",
1734            append=append,
1735            dialect=dialect,
1736            copy=copy,
1737            **opts,
1738        )
1739
1740        if join.kind == "CROSS":
1741            join.set("kind", None)
1742
1743        return join
1744
1745    def using(
1746        self,
1747        *expressions: t.Optional[ExpOrStr],
1748        append: bool = True,
1749        dialect: DialectType = None,
1750        copy: bool = True,
1751        **opts,
1752    ) -> Join:
1753        """
1754        Append to or set the USING expressions.
1755
1756        Example:
1757            >>> import sqlglot
1758            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1759            'JOIN x USING (foo, bla)'
1760
1761        Args:
1762            *expressions: the SQL code strings to parse.
1763                If an `Expression` instance is passed, it will be used as-is.
1764            append: if `True`, concatenate the new expressions to the existing "using" list.
1765                Otherwise, this resets the expression.
1766            dialect: the dialect used to parse the input expressions.
1767            copy: if `False`, modify this expression instance in-place.
1768            opts: other options to use to parse the input expressions.
1769
1770        Returns:
1771            The modified Join expression.
1772        """
1773        join = _apply_list_builder(
1774            *expressions,
1775            instance=self,
1776            arg="using",
1777            append=append,
1778            dialect=dialect,
1779            copy=copy,
1780            **opts,
1781        )
1782
1783        if join.kind == "CROSS":
1784            join.set("kind", None)
1785
1786        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, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1701    def on(
1702        self,
1703        *expressions: t.Optional[ExpOrStr],
1704        append: bool = True,
1705        dialect: DialectType = None,
1706        copy: bool = True,
1707        **opts,
1708    ) -> Join:
1709        """
1710        Append to or set the ON expressions.
1711
1712        Example:
1713            >>> import sqlglot
1714            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1715            'JOIN x ON y = 1'
1716
1717        Args:
1718            *expressions: the SQL code strings to parse.
1719                If an `Expression` instance is passed, it will be used as-is.
1720                Multiple expressions are combined with an AND operator.
1721            append: if `True`, AND the new expressions to any existing expression.
1722                Otherwise, this resets the expression.
1723            dialect: the dialect used to parse the input expressions.
1724            copy: if `False`, modify this expression instance in-place.
1725            opts: other options to use to parse the input expressions.
1726
1727        Returns:
1728            The modified Join expression.
1729        """
1730        join = _apply_conjunction_builder(
1731            *expressions,
1732            instance=self,
1733            arg="on",
1734            append=append,
1735            dialect=dialect,
1736            copy=copy,
1737            **opts,
1738        )
1739
1740        if join.kind == "CROSS":
1741            join.set("kind", None)
1742
1743        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, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1745    def using(
1746        self,
1747        *expressions: t.Optional[ExpOrStr],
1748        append: bool = True,
1749        dialect: DialectType = None,
1750        copy: bool = True,
1751        **opts,
1752    ) -> Join:
1753        """
1754        Append to or set the USING expressions.
1755
1756        Example:
1757            >>> import sqlglot
1758            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1759            'JOIN x USING (foo, bla)'
1760
1761        Args:
1762            *expressions: the SQL code strings to parse.
1763                If an `Expression` instance is passed, it will be used as-is.
1764            append: if `True`, concatenate the new expressions to the existing "using" list.
1765                Otherwise, this resets the expression.
1766            dialect: the dialect used to parse the input expressions.
1767            copy: if `False`, modify this expression instance in-place.
1768            opts: other options to use to parse the input expressions.
1769
1770        Returns:
1771            The modified Join expression.
1772        """
1773        join = _apply_list_builder(
1774            *expressions,
1775            instance=self,
1776            arg="using",
1777            append=append,
1778            dialect=dialect,
1779            copy=copy,
1780            **opts,
1781        )
1782
1783        if join.kind == "CROSS":
1784            join.set("kind", None)
1785
1786        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):
1789class Lateral(UDTF):
1790    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):
1793class MatchRecognize(Expression):
1794    arg_types = {
1795        "partition_by": False,
1796        "order": False,
1797        "measures": False,
1798        "rows": False,
1799        "after": False,
1800        "pattern": False,
1801        "define": False,
1802        "alias": False,
1803    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1808class Final(Expression):
1809    pass
key = 'final'
class Offset(Expression):
1812class Offset(Expression):
1813    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1816class Order(Expression):
1817    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1822class Cluster(Order):
1823    pass
key = 'cluster'
class Distribute(Order):
1826class Distribute(Order):
1827    pass
key = 'distribute'
class Sort(Order):
1830class Sort(Order):
1831    pass
key = 'sort'
class Ordered(Expression):
1834class Ordered(Expression):
1835    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1838class Property(Expression):
1839    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1842class AlgorithmProperty(Property):
1843    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1846class AutoIncrementProperty(Property):
1847    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1850class BlockCompressionProperty(Property):
1851    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):
1854class CharacterSetProperty(Property):
1855    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1858class ChecksumProperty(Property):
1859    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1862class CollateProperty(Property):
1863    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1866class CopyGrantsProperty(Property):
1867    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1870class DataBlocksizeProperty(Property):
1871    arg_types = {
1872        "size": False,
1873        "units": False,
1874        "minimum": False,
1875        "maximum": False,
1876        "default": False,
1877    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1880class DefinerProperty(Property):
1881    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1884class DistKeyProperty(Property):
1885    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1888class DistStyleProperty(Property):
1889    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1892class EngineProperty(Property):
1893    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1896class ToTableProperty(Property):
1897    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1900class ExecuteAsProperty(Property):
1901    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1904class ExternalProperty(Property):
1905    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1908class FallbackProperty(Property):
1909    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1912class FileFormatProperty(Property):
1913    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1916class FreespaceProperty(Property):
1917    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1920class InputOutputFormat(Expression):
1921    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1924class IsolatedLoadingProperty(Property):
1925    arg_types = {
1926        "no": True,
1927        "concurrent": True,
1928        "for_all": True,
1929        "for_insert": True,
1930        "for_none": True,
1931    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1934class JournalProperty(Property):
1935    arg_types = {
1936        "no": False,
1937        "dual": False,
1938        "before": False,
1939        "local": False,
1940        "after": False,
1941    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1944class LanguageProperty(Property):
1945    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1949class ClusteredByProperty(Property):
1950    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1953class DictProperty(Property):
1954    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1957class DictSubProperty(Property):
1958    pass
key = 'dictsubproperty'
class DictRange(Property):
1961class DictRange(Property):
1962    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1967class OnCluster(Property):
1968    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1971class LikeProperty(Property):
1972    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1975class LocationProperty(Property):
1976    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
1979class LockingProperty(Property):
1980    arg_types = {
1981        "this": False,
1982        "kind": True,
1983        "for_or_in": True,
1984        "lock_type": True,
1985        "override": False,
1986    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
1989class LogProperty(Property):
1990    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
1993class MaterializedProperty(Property):
1994    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
1997class MergeBlockRatioProperty(Property):
1998    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):
2001class NoPrimaryIndexProperty(Property):
2002    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
2005class OnCommitProperty(Property):
2006    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2009class PartitionedByProperty(Property):
2010    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2013class ReturnsProperty(Property):
2014    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2017class RowFormatProperty(Property):
2018    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2021class RowFormatDelimitedProperty(Property):
2022    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2023    arg_types = {
2024        "fields": False,
2025        "escaped": False,
2026        "collection_items": False,
2027        "map_keys": False,
2028        "lines": False,
2029        "null": False,
2030        "serde": False,
2031    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2034class RowFormatSerdeProperty(Property):
2035    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2039class QueryTransform(Expression):
2040    arg_types = {
2041        "expressions": True,
2042        "command_script": True,
2043        "schema": False,
2044        "row_format_before": False,
2045        "record_writer": False,
2046        "row_format_after": False,
2047        "record_reader": False,
2048    }
arg_types = {'expressions': True, 'command_script': True, 'schema': False, 'row_format_before': False, 'record_writer': False, 'row_format_after': False, 'record_reader': False}
key = 'querytransform'
class SchemaCommentProperty(Property):
2051class SchemaCommentProperty(Property):
2052    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2055class SerdeProperties(Property):
2056    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2059class SetProperty(Property):
2060    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2063class SettingsProperty(Property):
2064    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2067class SortKeyProperty(Property):
2068    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2071class SqlSecurityProperty(Property):
2072    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2075class StabilityProperty(Property):
2076    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2079class TemporaryProperty(Property):
2080    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2083class TransientProperty(Property):
2084    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2087class VolatileProperty(Property):
2088    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2091class WithDataProperty(Property):
2092    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2095class WithJournalTableProperty(Property):
2096    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2099class Properties(Expression):
2100    arg_types = {"expressions": True}
2101
2102    NAME_TO_PROPERTY = {
2103        "ALGORITHM": AlgorithmProperty,
2104        "AUTO_INCREMENT": AutoIncrementProperty,
2105        "CHARACTER SET": CharacterSetProperty,
2106        "CLUSTERED_BY": ClusteredByProperty,
2107        "COLLATE": CollateProperty,
2108        "COMMENT": SchemaCommentProperty,
2109        "DEFINER": DefinerProperty,
2110        "DISTKEY": DistKeyProperty,
2111        "DISTSTYLE": DistStyleProperty,
2112        "ENGINE": EngineProperty,
2113        "EXECUTE AS": ExecuteAsProperty,
2114        "FORMAT": FileFormatProperty,
2115        "LANGUAGE": LanguageProperty,
2116        "LOCATION": LocationProperty,
2117        "PARTITIONED_BY": PartitionedByProperty,
2118        "RETURNS": ReturnsProperty,
2119        "ROW_FORMAT": RowFormatProperty,
2120        "SORTKEY": SortKeyProperty,
2121    }
2122
2123    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2124
2125    # CREATE property locations
2126    # Form: schema specified
2127    #   create [POST_CREATE]
2128    #     table a [POST_NAME]
2129    #     (b int) [POST_SCHEMA]
2130    #     with ([POST_WITH])
2131    #     index (b) [POST_INDEX]
2132    #
2133    # Form: alias selection
2134    #   create [POST_CREATE]
2135    #     table a [POST_NAME]
2136    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2137    #     index (c) [POST_INDEX]
2138    class Location(AutoName):
2139        POST_CREATE = auto()
2140        POST_NAME = auto()
2141        POST_SCHEMA = auto()
2142        POST_WITH = auto()
2143        POST_ALIAS = auto()
2144        POST_EXPRESSION = auto()
2145        POST_INDEX = auto()
2146        UNSUPPORTED = auto()
2147
2148    @classmethod
2149    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2150        expressions = []
2151        for key, value in properties_dict.items():
2152            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2153            if property_cls:
2154                expressions.append(property_cls(this=convert(value)))
2155            else:
2156                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2157
2158        return cls(expressions=expressions)
arg_types = {'expressions': True}
NAME_TO_PROPERTY = {'ALGORITHM': <class 'sqlglot.expressions.AlgorithmProperty'>, 'AUTO_INCREMENT': <class 'sqlglot.expressions.AutoIncrementProperty'>, 'CHARACTER SET': <class 'sqlglot.expressions.CharacterSetProperty'>, 'CLUSTERED_BY': <class 'sqlglot.expressions.ClusteredByProperty'>, 'COLLATE': <class 'sqlglot.expressions.CollateProperty'>, 'COMMENT': <class 'sqlglot.expressions.SchemaCommentProperty'>, 'DEFINER': <class 'sqlglot.expressions.DefinerProperty'>, 'DISTKEY': <class 'sqlglot.expressions.DistKeyProperty'>, 'DISTSTYLE': <class 'sqlglot.expressions.DistStyleProperty'>, 'ENGINE': <class 'sqlglot.expressions.EngineProperty'>, 'EXECUTE AS': <class 'sqlglot.expressions.ExecuteAsProperty'>, 'FORMAT': <class 'sqlglot.expressions.FileFormatProperty'>, 'LANGUAGE': <class 'sqlglot.expressions.LanguageProperty'>, 'LOCATION': <class 'sqlglot.expressions.LocationProperty'>, 'PARTITIONED_BY': <class 'sqlglot.expressions.PartitionedByProperty'>, 'RETURNS': <class 'sqlglot.expressions.ReturnsProperty'>, 'ROW_FORMAT': <class 'sqlglot.expressions.RowFormatProperty'>, 'SORTKEY': <class 'sqlglot.expressions.SortKeyProperty'>}
PROPERTY_TO_NAME = {<class 'sqlglot.expressions.AlgorithmProperty'>: 'ALGORITHM', <class 'sqlglot.expressions.AutoIncrementProperty'>: 'AUTO_INCREMENT', <class 'sqlglot.expressions.CharacterSetProperty'>: 'CHARACTER SET', <class 'sqlglot.expressions.ClusteredByProperty'>: 'CLUSTERED_BY', <class 'sqlglot.expressions.CollateProperty'>: 'COLLATE', <class 'sqlglot.expressions.SchemaCommentProperty'>: 'COMMENT', <class 'sqlglot.expressions.DefinerProperty'>: 'DEFINER', <class 'sqlglot.expressions.DistKeyProperty'>: 'DISTKEY', <class 'sqlglot.expressions.DistStyleProperty'>: 'DISTSTYLE', <class 'sqlglot.expressions.EngineProperty'>: 'ENGINE', <class 'sqlglot.expressions.ExecuteAsProperty'>: 'EXECUTE AS', <class 'sqlglot.expressions.FileFormatProperty'>: 'FORMAT', <class 'sqlglot.expressions.LanguageProperty'>: 'LANGUAGE', <class 'sqlglot.expressions.LocationProperty'>: 'LOCATION', <class 'sqlglot.expressions.PartitionedByProperty'>: 'PARTITIONED_BY', <class 'sqlglot.expressions.ReturnsProperty'>: 'RETURNS', <class 'sqlglot.expressions.RowFormatProperty'>: 'ROW_FORMAT', <class 'sqlglot.expressions.SortKeyProperty'>: 'SORTKEY'}
@classmethod
def from_dict(cls, properties_dict: Dict) -> sqlglot.expressions.Properties:
2148    @classmethod
2149    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2150        expressions = []
2151        for key, value in properties_dict.items():
2152            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2153            if property_cls:
2154                expressions.append(property_cls(this=convert(value)))
2155            else:
2156                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2157
2158        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2138    class Location(AutoName):
2139        POST_CREATE = auto()
2140        POST_NAME = auto()
2141        POST_SCHEMA = auto()
2142        POST_WITH = auto()
2143        POST_ALIAS = auto()
2144        POST_EXPRESSION = auto()
2145        POST_INDEX = auto()
2146        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):
2161class Qualify(Expression):
2162    pass
key = 'qualify'
class Return(Expression):
2166class Return(Expression):
2167    pass
key = 'return'
class Reference(Expression):
2170class Reference(Expression):
2171    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2174class Tuple(Expression):
2175    arg_types = {"expressions": False}
2176
2177    def isin(
2178        self,
2179        *expressions: t.Any,
2180        query: t.Optional[ExpOrStr] = None,
2181        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2182        copy: bool = True,
2183        **opts,
2184    ) -> In:
2185        return In(
2186            this=_maybe_copy(self, copy),
2187            expressions=[convert(e, copy=copy) for e in expressions],
2188            query=maybe_parse(query, copy=copy, **opts) if query else None,
2189            unnest=Unnest(
2190                expressions=[
2191                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2192                ]
2193            )
2194            if unnest
2195            else None,
2196        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, unnest: Union[str, sqlglot.expressions.Expression, NoneType, Collection[Union[str, sqlglot.expressions.Expression]]] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2177    def isin(
2178        self,
2179        *expressions: t.Any,
2180        query: t.Optional[ExpOrStr] = None,
2181        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2182        copy: bool = True,
2183        **opts,
2184    ) -> In:
2185        return In(
2186            this=_maybe_copy(self, copy),
2187            expressions=[convert(e, copy=copy) for e in expressions],
2188            query=maybe_parse(query, copy=copy, **opts) if query else None,
2189            unnest=Unnest(
2190                expressions=[
2191                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2192                ]
2193            )
2194            if unnest
2195            else None,
2196        )
key = 'tuple'
class Subqueryable(Unionable):
2199class Subqueryable(Unionable):
2200    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2201        """
2202        Convert this expression to an aliased expression that can be used as a Subquery.
2203
2204        Example:
2205            >>> subquery = Select().select("x").from_("tbl").subquery()
2206            >>> Select().select("x").from_(subquery).sql()
2207            'SELECT x FROM (SELECT x FROM tbl)'
2208
2209        Args:
2210            alias (str | Identifier): an optional alias for the subquery
2211            copy (bool): if `False`, modify this expression instance in-place.
2212
2213        Returns:
2214            Alias: the subquery
2215        """
2216        instance = _maybe_copy(self, copy)
2217        if not isinstance(alias, Expression):
2218            alias = TableAlias(this=to_identifier(alias)) if alias else None
2219
2220        return Subquery(this=instance, alias=alias)
2221
2222    def limit(
2223        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2224    ) -> Select:
2225        raise NotImplementedError
2226
2227    @property
2228    def ctes(self):
2229        with_ = self.args.get("with")
2230        if not with_:
2231            return []
2232        return with_.expressions
2233
2234    @property
2235    def selects(self) -> t.List[Expression]:
2236        raise NotImplementedError("Subqueryable objects must implement `selects`")
2237
2238    @property
2239    def named_selects(self) -> t.List[str]:
2240        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2241
2242    def with_(
2243        self,
2244        alias: ExpOrStr,
2245        as_: ExpOrStr,
2246        recursive: t.Optional[bool] = None,
2247        append: bool = True,
2248        dialect: DialectType = None,
2249        copy: bool = True,
2250        **opts,
2251    ) -> Subqueryable:
2252        """
2253        Append to or set the common table expressions.
2254
2255        Example:
2256            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2257            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2258
2259        Args:
2260            alias: the SQL code string to parse as the table name.
2261                If an `Expression` instance is passed, this is used as-is.
2262            as_: the SQL code string to parse as the table expression.
2263                If an `Expression` instance is passed, it will be used as-is.
2264            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2265            append: if `True`, add to any existing expressions.
2266                Otherwise, this resets the expressions.
2267            dialect: the dialect used to parse the input expression.
2268            copy: if `False`, modify this expression instance in-place.
2269            opts: other options to use to parse the input expressions.
2270
2271        Returns:
2272            The modified expression.
2273        """
2274        return _apply_cte_builder(
2275            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2276        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2200    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2201        """
2202        Convert this expression to an aliased expression that can be used as a Subquery.
2203
2204        Example:
2205            >>> subquery = Select().select("x").from_("tbl").subquery()
2206            >>> Select().select("x").from_(subquery).sql()
2207            'SELECT x FROM (SELECT x FROM tbl)'
2208
2209        Args:
2210            alias (str | Identifier): an optional alias for the subquery
2211            copy (bool): if `False`, modify this expression instance in-place.
2212
2213        Returns:
2214            Alias: the subquery
2215        """
2216        instance = _maybe_copy(self, copy)
2217        if not isinstance(alias, Expression):
2218            alias = TableAlias(this=to_identifier(alias)) if alias else None
2219
2220        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, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2222    def limit(
2223        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2224    ) -> Select:
2225        raise NotImplementedError
ctes
named_selects: List[str]
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.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) -> sqlglot.expressions.Subqueryable:
2242    def with_(
2243        self,
2244        alias: ExpOrStr,
2245        as_: ExpOrStr,
2246        recursive: t.Optional[bool] = None,
2247        append: bool = True,
2248        dialect: DialectType = None,
2249        copy: bool = True,
2250        **opts,
2251    ) -> Subqueryable:
2252        """
2253        Append to or set the common table expressions.
2254
2255        Example:
2256            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2257            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2258
2259        Args:
2260            alias: the SQL code string to parse as the table name.
2261                If an `Expression` instance is passed, this is used as-is.
2262            as_: the SQL code string to parse as the table expression.
2263                If an `Expression` instance is passed, it will be used as-is.
2264            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2265            append: if `True`, add to any existing expressions.
2266                Otherwise, this resets the expressions.
2267            dialect: the dialect used to parse the input expression.
2268            copy: if `False`, modify this expression instance in-place.
2269            opts: other options to use to parse the input expressions.
2270
2271        Returns:
2272            The modified expression.
2273        """
2274        return _apply_cte_builder(
2275            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2276        )

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, '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):
2303class WithTableHint(Expression):
2304    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2308class IndexTableHint(Expression):
2309    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2312class Table(Expression):
2313    arg_types = {
2314        "this": True,
2315        "alias": False,
2316        "db": False,
2317        "catalog": False,
2318        "laterals": False,
2319        "joins": False,
2320        "pivots": False,
2321        "hints": False,
2322        "system_time": False,
2323    }
2324
2325    @property
2326    def name(self) -> str:
2327        if isinstance(self.this, Func):
2328            return ""
2329        return self.this.name
2330
2331    @property
2332    def db(self) -> str:
2333        return self.text("db")
2334
2335    @property
2336    def catalog(self) -> str:
2337        return self.text("catalog")
2338
2339    @property
2340    def selects(self) -> t.List[Expression]:
2341        return []
2342
2343    @property
2344    def named_selects(self) -> t.List[str]:
2345        return []
2346
2347    @property
2348    def parts(self) -> t.List[Identifier]:
2349        """Return the parts of a table in order catalog, db, table."""
2350        parts: t.List[Identifier] = []
2351
2352        for arg in ("catalog", "db", "this"):
2353            part = self.args.get(arg)
2354
2355            if isinstance(part, Identifier):
2356                parts.append(part)
2357            elif isinstance(part, Dot):
2358                parts.extend(part.flatten())
2359
2360        return parts
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False}
name: str
db: str
catalog: str
named_selects: List[str]

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

key = 'table'
class SystemTime(Expression):
2364class SystemTime(Expression):
2365    arg_types = {
2366        "this": False,
2367        "expression": False,
2368        "kind": True,
2369    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2372class Union(Subqueryable):
2373    arg_types = {
2374        "with": False,
2375        "this": True,
2376        "expression": True,
2377        "distinct": False,
2378        **QUERY_MODIFIERS,
2379    }
2380
2381    def limit(
2382        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2383    ) -> Select:
2384        """
2385        Set the LIMIT expression.
2386
2387        Example:
2388            >>> select("1").union(select("1")).limit(1).sql()
2389            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2390
2391        Args:
2392            expression: the SQL code string to parse.
2393                This can also be an integer.
2394                If a `Limit` instance is passed, this is used as-is.
2395                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2396            dialect: the dialect used to parse the input expression.
2397            copy: if `False`, modify this expression instance in-place.
2398            opts: other options to use to parse the input expressions.
2399
2400        Returns:
2401            The limited subqueryable.
2402        """
2403        return (
2404            select("*")
2405            .from_(self.subquery(alias="_l_0", copy=copy))
2406            .limit(expression, dialect=dialect, copy=False, **opts)
2407        )
2408
2409    def select(
2410        self,
2411        *expressions: t.Optional[ExpOrStr],
2412        append: bool = True,
2413        dialect: DialectType = None,
2414        copy: bool = True,
2415        **opts,
2416    ) -> Union:
2417        """Append to or set the SELECT of the union recursively.
2418
2419        Example:
2420            >>> from sqlglot import parse_one
2421            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2422            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2423
2424        Args:
2425            *expressions: the SQL code strings to parse.
2426                If an `Expression` instance is passed, it will be used as-is.
2427            append: if `True`, add to any existing expressions.
2428                Otherwise, this resets the expressions.
2429            dialect: the dialect used to parse the input expressions.
2430            copy: if `False`, modify this expression instance in-place.
2431            opts: other options to use to parse the input expressions.
2432
2433        Returns:
2434            Union: the modified expression.
2435        """
2436        this = self.copy() if copy else self
2437        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2438        this.expression.unnest().select(
2439            *expressions, append=append, dialect=dialect, copy=False, **opts
2440        )
2441        return this
2442
2443    @property
2444    def named_selects(self) -> t.List[str]:
2445        return self.this.unnest().named_selects
2446
2447    @property
2448    def is_star(self) -> bool:
2449        return self.this.is_star or self.expression.is_star
2450
2451    @property
2452    def selects(self) -> t.List[Expression]:
2453        return self.this.unnest().selects
2454
2455    @property
2456    def left(self):
2457        return self.this
2458
2459    @property
2460    def right(self):
2461        return self.expression
arg_types = {'with': False, 'this': True, 'expression': True, 'distinct': False, 'match': False, 'laterals': False, 'joins': 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, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2381    def limit(
2382        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2383    ) -> Select:
2384        """
2385        Set the LIMIT expression.
2386
2387        Example:
2388            >>> select("1").union(select("1")).limit(1).sql()
2389            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2390
2391        Args:
2392            expression: the SQL code string to parse.
2393                This can also be an integer.
2394                If a `Limit` instance is passed, this is used as-is.
2395                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2396            dialect: the dialect used to parse the input expression.
2397            copy: if `False`, modify this expression instance in-place.
2398            opts: other options to use to parse the input expressions.
2399
2400        Returns:
2401            The limited subqueryable.
2402        """
2403        return (
2404            select("*")
2405            .from_(self.subquery(alias="_l_0", copy=copy))
2406            .limit(expression, dialect=dialect, copy=False, **opts)
2407        )

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, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
2409    def select(
2410        self,
2411        *expressions: t.Optional[ExpOrStr],
2412        append: bool = True,
2413        dialect: DialectType = None,
2414        copy: bool = True,
2415        **opts,
2416    ) -> Union:
2417        """Append to or set the SELECT of the union recursively.
2418
2419        Example:
2420            >>> from sqlglot import parse_one
2421            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2422            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2423
2424        Args:
2425            *expressions: the SQL code strings to parse.
2426                If an `Expression` instance is passed, it will be used as-is.
2427            append: if `True`, add to any existing expressions.
2428                Otherwise, this resets the expressions.
2429            dialect: the dialect used to parse the input expressions.
2430            copy: if `False`, modify this expression instance in-place.
2431            opts: other options to use to parse the input expressions.
2432
2433        Returns:
2434            Union: the modified expression.
2435        """
2436        this = self.copy() if copy else self
2437        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2438        this.expression.unnest().select(
2439            *expressions, append=append, dialect=dialect, copy=False, **opts
2440        )
2441        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.

left
right
key = 'union'
class Except(Union):
2464class Except(Union):
2465    pass
key = 'except'
class Intersect(Union):
2468class Intersect(Union):
2469    pass
key = 'intersect'
class Unnest(UDTF):
2472class Unnest(UDTF):
2473    arg_types = {
2474        "expressions": True,
2475        "ordinality": False,
2476        "alias": False,
2477        "offset": False,
2478    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False, 'offset': False}
key = 'unnest'
class Update(Expression):
2481class Update(Expression):
2482    arg_types = {
2483        "with": False,
2484        "this": False,
2485        "expressions": True,
2486        "from": False,
2487        "where": False,
2488        "returning": False,
2489        "limit": False,
2490    }
arg_types = {'with': False, 'this': False, 'expressions': True, 'from': False, 'where': False, 'returning': False, 'limit': False}
key = 'update'
class Values(UDTF):
2493class Values(UDTF):
2494    arg_types = {
2495        "expressions": True,
2496        "ordinality": False,
2497        "alias": False,
2498    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False}
key = 'values'
class Var(Expression):
2501class Var(Expression):
2502    pass
key = 'var'
class Schema(Expression):
2505class Schema(Expression):
2506    arg_types = {"this": False, "expressions": False}
arg_types = {'this': False, 'expressions': False}
key = 'schema'
class Lock(Expression):
2511class Lock(Expression):
2512    arg_types = {"update": True, "expressions": False, "wait": False}
arg_types = {'update': True, 'expressions': False, 'wait': False}
key = 'lock'
class Select(Subqueryable):
2515class Select(Subqueryable):
2516    arg_types = {
2517        "with": False,
2518        "kind": False,
2519        "expressions": False,
2520        "hint": False,
2521        "distinct": False,
2522        "into": False,
2523        "from": False,
2524        **QUERY_MODIFIERS,
2525    }
2526
2527    def from_(
2528        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2529    ) -> Select:
2530        """
2531        Set the FROM expression.
2532
2533        Example:
2534            >>> Select().from_("tbl").select("x").sql()
2535            'SELECT x FROM tbl'
2536
2537        Args:
2538            expression : the SQL code strings to parse.
2539                If a `From` instance is passed, this is used as-is.
2540                If another `Expression` instance is passed, it will be wrapped in a `From`.
2541            dialect: the dialect used to parse the input expression.
2542            copy: if `False`, modify this expression instance in-place.
2543            opts: other options to use to parse the input expressions.
2544
2545        Returns:
2546            The modified Select expression.
2547        """
2548        return _apply_builder(
2549            expression=expression,
2550            instance=self,
2551            arg="from",
2552            into=From,
2553            prefix="FROM",
2554            dialect=dialect,
2555            copy=copy,
2556            **opts,
2557        )
2558
2559    def group_by(
2560        self,
2561        *expressions: t.Optional[ExpOrStr],
2562        append: bool = True,
2563        dialect: DialectType = None,
2564        copy: bool = True,
2565        **opts,
2566    ) -> Select:
2567        """
2568        Set the GROUP BY expression.
2569
2570        Example:
2571            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2572            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2573
2574        Args:
2575            *expressions: the SQL code strings to parse.
2576                If a `Group` instance is passed, this is used as-is.
2577                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2578                If nothing is passed in then a group by is not applied to the expression
2579            append: if `True`, add to any existing expressions.
2580                Otherwise, this flattens all the `Group` expression into a single expression.
2581            dialect: the dialect used to parse the input expression.
2582            copy: if `False`, modify this expression instance in-place.
2583            opts: other options to use to parse the input expressions.
2584
2585        Returns:
2586            The modified Select expression.
2587        """
2588        if not expressions:
2589            return self if not copy else self.copy()
2590
2591        return _apply_child_list_builder(
2592            *expressions,
2593            instance=self,
2594            arg="group",
2595            append=append,
2596            copy=copy,
2597            prefix="GROUP BY",
2598            into=Group,
2599            dialect=dialect,
2600            **opts,
2601        )
2602
2603    def order_by(
2604        self,
2605        *expressions: t.Optional[ExpOrStr],
2606        append: bool = True,
2607        dialect: DialectType = None,
2608        copy: bool = True,
2609        **opts,
2610    ) -> Select:
2611        """
2612        Set the ORDER BY expression.
2613
2614        Example:
2615            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2616            'SELECT x FROM tbl ORDER BY x DESC'
2617
2618        Args:
2619            *expressions: the SQL code strings to parse.
2620                If a `Group` instance is passed, this is used as-is.
2621                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2622            append: if `True`, add to any existing expressions.
2623                Otherwise, this flattens all the `Order` expression into a single expression.
2624            dialect: the dialect used to parse the input expression.
2625            copy: if `False`, modify this expression instance in-place.
2626            opts: other options to use to parse the input expressions.
2627
2628        Returns:
2629            The modified Select expression.
2630        """
2631        return _apply_child_list_builder(
2632            *expressions,
2633            instance=self,
2634            arg="order",
2635            append=append,
2636            copy=copy,
2637            prefix="ORDER BY",
2638            into=Order,
2639            dialect=dialect,
2640            **opts,
2641        )
2642
2643    def sort_by(
2644        self,
2645        *expressions: t.Optional[ExpOrStr],
2646        append: bool = True,
2647        dialect: DialectType = None,
2648        copy: bool = True,
2649        **opts,
2650    ) -> Select:
2651        """
2652        Set the SORT BY expression.
2653
2654        Example:
2655            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2656            'SELECT x FROM tbl SORT BY x DESC'
2657
2658        Args:
2659            *expressions: the SQL code strings to parse.
2660                If a `Group` instance is passed, this is used as-is.
2661                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2662            append: if `True`, add to any existing expressions.
2663                Otherwise, this flattens all the `Order` expression into a single expression.
2664            dialect: the dialect used to parse the input expression.
2665            copy: if `False`, modify this expression instance in-place.
2666            opts: other options to use to parse the input expressions.
2667
2668        Returns:
2669            The modified Select expression.
2670        """
2671        return _apply_child_list_builder(
2672            *expressions,
2673            instance=self,
2674            arg="sort",
2675            append=append,
2676            copy=copy,
2677            prefix="SORT BY",
2678            into=Sort,
2679            dialect=dialect,
2680            **opts,
2681        )
2682
2683    def cluster_by(
2684        self,
2685        *expressions: t.Optional[ExpOrStr],
2686        append: bool = True,
2687        dialect: DialectType = None,
2688        copy: bool = True,
2689        **opts,
2690    ) -> Select:
2691        """
2692        Set the CLUSTER BY expression.
2693
2694        Example:
2695            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2696            'SELECT x FROM tbl CLUSTER BY x DESC'
2697
2698        Args:
2699            *expressions: the SQL code strings to parse.
2700                If a `Group` instance is passed, this is used as-is.
2701                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2702            append: if `True`, add to any existing expressions.
2703                Otherwise, this flattens all the `Order` expression into a single expression.
2704            dialect: the dialect used to parse the input expression.
2705            copy: if `False`, modify this expression instance in-place.
2706            opts: other options to use to parse the input expressions.
2707
2708        Returns:
2709            The modified Select expression.
2710        """
2711        return _apply_child_list_builder(
2712            *expressions,
2713            instance=self,
2714            arg="cluster",
2715            append=append,
2716            copy=copy,
2717            prefix="CLUSTER BY",
2718            into=Cluster,
2719            dialect=dialect,
2720            **opts,
2721        )
2722
2723    def limit(
2724        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2725    ) -> Select:
2726        """
2727        Set the LIMIT expression.
2728
2729        Example:
2730            >>> Select().from_("tbl").select("x").limit(10).sql()
2731            'SELECT x FROM tbl LIMIT 10'
2732
2733        Args:
2734            expression: the SQL code string to parse.
2735                This can also be an integer.
2736                If a `Limit` instance is passed, this is used as-is.
2737                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2738            dialect: the dialect used to parse the input expression.
2739            copy: if `False`, modify this expression instance in-place.
2740            opts: other options to use to parse the input expressions.
2741
2742        Returns:
2743            Select: the modified expression.
2744        """
2745        return _apply_builder(
2746            expression=expression,
2747            instance=self,
2748            arg="limit",
2749            into=Limit,
2750            prefix="LIMIT",
2751            dialect=dialect,
2752            copy=copy,
2753            **opts,
2754        )
2755
2756    def offset(
2757        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2758    ) -> Select:
2759        """
2760        Set the OFFSET expression.
2761
2762        Example:
2763            >>> Select().from_("tbl").select("x").offset(10).sql()
2764            'SELECT x FROM tbl OFFSET 10'
2765
2766        Args:
2767            expression: the SQL code string to parse.
2768                This can also be an integer.
2769                If a `Offset` instance is passed, this is used as-is.
2770                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2771            dialect: the dialect used to parse the input expression.
2772            copy: if `False`, modify this expression instance in-place.
2773            opts: other options to use to parse the input expressions.
2774
2775        Returns:
2776            The modified Select expression.
2777        """
2778        return _apply_builder(
2779            expression=expression,
2780            instance=self,
2781            arg="offset",
2782            into=Offset,
2783            prefix="OFFSET",
2784            dialect=dialect,
2785            copy=copy,
2786            **opts,
2787        )
2788
2789    def select(
2790        self,
2791        *expressions: t.Optional[ExpOrStr],
2792        append: bool = True,
2793        dialect: DialectType = None,
2794        copy: bool = True,
2795        **opts,
2796    ) -> Select:
2797        """
2798        Append to or set the SELECT expressions.
2799
2800        Example:
2801            >>> Select().select("x", "y").sql()
2802            'SELECT x, y'
2803
2804        Args:
2805            *expressions: the SQL code strings to parse.
2806                If an `Expression` instance is passed, it will be used as-is.
2807            append: if `True`, add to any existing expressions.
2808                Otherwise, this resets the expressions.
2809            dialect: the dialect used to parse the input expressions.
2810            copy: if `False`, modify this expression instance in-place.
2811            opts: other options to use to parse the input expressions.
2812
2813        Returns:
2814            The modified Select expression.
2815        """
2816        return _apply_list_builder(
2817            *expressions,
2818            instance=self,
2819            arg="expressions",
2820            append=append,
2821            dialect=dialect,
2822            copy=copy,
2823            **opts,
2824        )
2825
2826    def lateral(
2827        self,
2828        *expressions: t.Optional[ExpOrStr],
2829        append: bool = True,
2830        dialect: DialectType = None,
2831        copy: bool = True,
2832        **opts,
2833    ) -> Select:
2834        """
2835        Append to or set the LATERAL expressions.
2836
2837        Example:
2838            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2839            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2840
2841        Args:
2842            *expressions: the SQL code strings to parse.
2843                If an `Expression` instance is passed, it will be used as-is.
2844            append: if `True`, add to any existing expressions.
2845                Otherwise, this resets the expressions.
2846            dialect: the dialect used to parse the input expressions.
2847            copy: if `False`, modify this expression instance in-place.
2848            opts: other options to use to parse the input expressions.
2849
2850        Returns:
2851            The modified Select expression.
2852        """
2853        return _apply_list_builder(
2854            *expressions,
2855            instance=self,
2856            arg="laterals",
2857            append=append,
2858            into=Lateral,
2859            prefix="LATERAL VIEW",
2860            dialect=dialect,
2861            copy=copy,
2862            **opts,
2863        )
2864
2865    def join(
2866        self,
2867        expression: ExpOrStr,
2868        on: t.Optional[ExpOrStr] = None,
2869        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2870        append: bool = True,
2871        join_type: t.Optional[str] = None,
2872        join_alias: t.Optional[Identifier | str] = None,
2873        dialect: DialectType = None,
2874        copy: bool = True,
2875        **opts,
2876    ) -> Select:
2877        """
2878        Append to or set the JOIN expressions.
2879
2880        Example:
2881            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2882            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2883
2884            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2885            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2886
2887            Use `join_type` to change the type of join:
2888
2889            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2890            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2891
2892        Args:
2893            expression: the SQL code string to parse.
2894                If an `Expression` instance is passed, it will be used as-is.
2895            on: optionally specify the join "on" criteria as a SQL string.
2896                If an `Expression` instance is passed, it will be used as-is.
2897            using: optionally specify the join "using" criteria as a SQL string.
2898                If an `Expression` instance is passed, it will be used as-is.
2899            append: if `True`, add to any existing expressions.
2900                Otherwise, this resets the expressions.
2901            join_type: if set, alter the parsed join type.
2902            join_alias: an optional alias for the joined source.
2903            dialect: the dialect used to parse the input expressions.
2904            copy: if `False`, modify this expression instance in-place.
2905            opts: other options to use to parse the input expressions.
2906
2907        Returns:
2908            Select: the modified expression.
2909        """
2910        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2911
2912        try:
2913            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2914        except ParseError:
2915            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2916
2917        join = expression if isinstance(expression, Join) else Join(this=expression)
2918
2919        if isinstance(join.this, Select):
2920            join.this.replace(join.this.subquery())
2921
2922        if join_type:
2923            method: t.Optional[Token]
2924            side: t.Optional[Token]
2925            kind: t.Optional[Token]
2926
2927            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2928
2929            if method:
2930                join.set("method", method.text)
2931            if side:
2932                join.set("side", side.text)
2933            if kind:
2934                join.set("kind", kind.text)
2935
2936        if on:
2937            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2938            join.set("on", on)
2939
2940        if using:
2941            join = _apply_list_builder(
2942                *ensure_list(using),
2943                instance=join,
2944                arg="using",
2945                append=append,
2946                copy=copy,
2947                **opts,
2948            )
2949
2950        if join_alias:
2951            join.set("this", alias_(join.this, join_alias, table=True))
2952
2953        return _apply_list_builder(
2954            join,
2955            instance=self,
2956            arg="joins",
2957            append=append,
2958            copy=copy,
2959            **opts,
2960        )
2961
2962    def where(
2963        self,
2964        *expressions: t.Optional[ExpOrStr],
2965        append: bool = True,
2966        dialect: DialectType = None,
2967        copy: bool = True,
2968        **opts,
2969    ) -> Select:
2970        """
2971        Append to or set the WHERE expressions.
2972
2973        Example:
2974            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2975            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2976
2977        Args:
2978            *expressions: the SQL code strings to parse.
2979                If an `Expression` instance is passed, it will be used as-is.
2980                Multiple expressions are combined with an AND operator.
2981            append: if `True`, AND the new expressions to any existing expression.
2982                Otherwise, this resets the expression.
2983            dialect: the dialect used to parse the input expressions.
2984            copy: if `False`, modify this expression instance in-place.
2985            opts: other options to use to parse the input expressions.
2986
2987        Returns:
2988            Select: the modified expression.
2989        """
2990        return _apply_conjunction_builder(
2991            *expressions,
2992            instance=self,
2993            arg="where",
2994            append=append,
2995            into=Where,
2996            dialect=dialect,
2997            copy=copy,
2998            **opts,
2999        )
3000
3001    def having(
3002        self,
3003        *expressions: t.Optional[ExpOrStr],
3004        append: bool = True,
3005        dialect: DialectType = None,
3006        copy: bool = True,
3007        **opts,
3008    ) -> Select:
3009        """
3010        Append to or set the HAVING expressions.
3011
3012        Example:
3013            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3014            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3015
3016        Args:
3017            *expressions: the SQL code strings to parse.
3018                If an `Expression` instance is passed, it will be used as-is.
3019                Multiple expressions are combined with an AND operator.
3020            append: if `True`, AND the new expressions to any existing expression.
3021                Otherwise, this resets the expression.
3022            dialect: the dialect used to parse the input expressions.
3023            copy: if `False`, modify this expression instance in-place.
3024            opts: other options to use to parse the input expressions.
3025
3026        Returns:
3027            The modified Select expression.
3028        """
3029        return _apply_conjunction_builder(
3030            *expressions,
3031            instance=self,
3032            arg="having",
3033            append=append,
3034            into=Having,
3035            dialect=dialect,
3036            copy=copy,
3037            **opts,
3038        )
3039
3040    def window(
3041        self,
3042        *expressions: t.Optional[ExpOrStr],
3043        append: bool = True,
3044        dialect: DialectType = None,
3045        copy: bool = True,
3046        **opts,
3047    ) -> Select:
3048        return _apply_list_builder(
3049            *expressions,
3050            instance=self,
3051            arg="windows",
3052            append=append,
3053            into=Window,
3054            dialect=dialect,
3055            copy=copy,
3056            **opts,
3057        )
3058
3059    def qualify(
3060        self,
3061        *expressions: t.Optional[ExpOrStr],
3062        append: bool = True,
3063        dialect: DialectType = None,
3064        copy: bool = True,
3065        **opts,
3066    ) -> Select:
3067        return _apply_conjunction_builder(
3068            *expressions,
3069            instance=self,
3070            arg="qualify",
3071            append=append,
3072            into=Qualify,
3073            dialect=dialect,
3074            copy=copy,
3075            **opts,
3076        )
3077
3078    def distinct(
3079        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3080    ) -> Select:
3081        """
3082        Set the OFFSET expression.
3083
3084        Example:
3085            >>> Select().from_("tbl").select("x").distinct().sql()
3086            'SELECT DISTINCT x FROM tbl'
3087
3088        Args:
3089            ons: the expressions to distinct on
3090            distinct: whether the Select should be distinct
3091            copy: if `False`, modify this expression instance in-place.
3092
3093        Returns:
3094            Select: the modified expression.
3095        """
3096        instance = _maybe_copy(self, copy)
3097        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3098        instance.set("distinct", Distinct(on=on) if distinct else None)
3099        return instance
3100
3101    def ctas(
3102        self,
3103        table: ExpOrStr,
3104        properties: t.Optional[t.Dict] = None,
3105        dialect: DialectType = None,
3106        copy: bool = True,
3107        **opts,
3108    ) -> Create:
3109        """
3110        Convert this expression to a CREATE TABLE AS statement.
3111
3112        Example:
3113            >>> Select().select("*").from_("tbl").ctas("x").sql()
3114            'CREATE TABLE x AS SELECT * FROM tbl'
3115
3116        Args:
3117            table: the SQL code string to parse as the table name.
3118                If another `Expression` instance is passed, it will be used as-is.
3119            properties: an optional mapping of table properties
3120            dialect: the dialect used to parse the input table.
3121            copy: if `False`, modify this expression instance in-place.
3122            opts: other options to use to parse the input table.
3123
3124        Returns:
3125            The new Create expression.
3126        """
3127        instance = _maybe_copy(self, copy)
3128        table_expression = maybe_parse(
3129            table,
3130            into=Table,
3131            dialect=dialect,
3132            **opts,
3133        )
3134        properties_expression = None
3135        if properties:
3136            properties_expression = Properties.from_dict(properties)
3137
3138        return Create(
3139            this=table_expression,
3140            kind="table",
3141            expression=instance,
3142            properties=properties_expression,
3143        )
3144
3145    def lock(self, update: bool = True, copy: bool = True) -> Select:
3146        """
3147        Set the locking read mode for this expression.
3148
3149        Examples:
3150            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3151            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3152
3153            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3154            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3155
3156        Args:
3157            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3158            copy: if `False`, modify this expression instance in-place.
3159
3160        Returns:
3161            The modified expression.
3162        """
3163        inst = _maybe_copy(self, copy)
3164        inst.set("locks", [Lock(update=update)])
3165
3166        return inst
3167
3168    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3169        """
3170        Set hints for this expression.
3171
3172        Examples:
3173            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3174            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3175
3176        Args:
3177            hints: The SQL code strings to parse as the hints.
3178                If an `Expression` instance is passed, it will be used as-is.
3179            dialect: The dialect used to parse the hints.
3180            copy: If `False`, modify this expression instance in-place.
3181
3182        Returns:
3183            The modified expression.
3184        """
3185        inst = _maybe_copy(self, copy)
3186        inst.set(
3187            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3188        )
3189
3190        return inst
3191
3192    @property
3193    def named_selects(self) -> t.List[str]:
3194        return [e.output_name for e in self.expressions if e.alias_or_name]
3195
3196    @property
3197    def is_star(self) -> bool:
3198        return any(expression.is_star for expression in self.expressions)
3199
3200    @property
3201    def selects(self) -> t.List[Expression]:
3202        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, '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, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2527    def from_(
2528        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2529    ) -> Select:
2530        """
2531        Set the FROM expression.
2532
2533        Example:
2534            >>> Select().from_("tbl").select("x").sql()
2535            'SELECT x FROM tbl'
2536
2537        Args:
2538            expression : the SQL code strings to parse.
2539                If a `From` instance is passed, this is used as-is.
2540                If another `Expression` instance is passed, it will be wrapped in a `From`.
2541            dialect: the dialect used to parse the input expression.
2542            copy: if `False`, modify this expression instance in-place.
2543            opts: other options to use to parse the input expressions.
2544
2545        Returns:
2546            The modified Select expression.
2547        """
2548        return _apply_builder(
2549            expression=expression,
2550            instance=self,
2551            arg="from",
2552            into=From,
2553            prefix="FROM",
2554            dialect=dialect,
2555            copy=copy,
2556            **opts,
2557        )

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, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2559    def group_by(
2560        self,
2561        *expressions: t.Optional[ExpOrStr],
2562        append: bool = True,
2563        dialect: DialectType = None,
2564        copy: bool = True,
2565        **opts,
2566    ) -> Select:
2567        """
2568        Set the GROUP BY expression.
2569
2570        Example:
2571            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2572            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2573
2574        Args:
2575            *expressions: the SQL code strings to parse.
2576                If a `Group` instance is passed, this is used as-is.
2577                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2578                If nothing is passed in then a group by is not applied to the expression
2579            append: if `True`, add to any existing expressions.
2580                Otherwise, this flattens all the `Group` expression into a single expression.
2581            dialect: the dialect used to parse the input expression.
2582            copy: if `False`, modify this expression instance in-place.
2583            opts: other options to use to parse the input expressions.
2584
2585        Returns:
2586            The modified Select expression.
2587        """
2588        if not expressions:
2589            return self if not copy else self.copy()
2590
2591        return _apply_child_list_builder(
2592            *expressions,
2593            instance=self,
2594            arg="group",
2595            append=append,
2596            copy=copy,
2597            prefix="GROUP BY",
2598            into=Group,
2599            dialect=dialect,
2600            **opts,
2601        )

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, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2603    def order_by(
2604        self,
2605        *expressions: t.Optional[ExpOrStr],
2606        append: bool = True,
2607        dialect: DialectType = None,
2608        copy: bool = True,
2609        **opts,
2610    ) -> Select:
2611        """
2612        Set the ORDER BY expression.
2613
2614        Example:
2615            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2616            'SELECT x FROM tbl ORDER BY x DESC'
2617
2618        Args:
2619            *expressions: the SQL code strings to parse.
2620                If a `Group` instance is passed, this is used as-is.
2621                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2622            append: if `True`, add to any existing expressions.
2623                Otherwise, this flattens all the `Order` expression into a single expression.
2624            dialect: the dialect used to parse the input expression.
2625            copy: if `False`, modify this expression instance in-place.
2626            opts: other options to use to parse the input expressions.
2627
2628        Returns:
2629            The modified Select expression.
2630        """
2631        return _apply_child_list_builder(
2632            *expressions,
2633            instance=self,
2634            arg="order",
2635            append=append,
2636            copy=copy,
2637            prefix="ORDER BY",
2638            into=Order,
2639            dialect=dialect,
2640            **opts,
2641        )

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, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2643    def sort_by(
2644        self,
2645        *expressions: t.Optional[ExpOrStr],
2646        append: bool = True,
2647        dialect: DialectType = None,
2648        copy: bool = True,
2649        **opts,
2650    ) -> Select:
2651        """
2652        Set the SORT BY expression.
2653
2654        Example:
2655            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2656            'SELECT x FROM tbl SORT BY x DESC'
2657
2658        Args:
2659            *expressions: the SQL code strings to parse.
2660                If a `Group` instance is passed, this is used as-is.
2661                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2662            append: if `True`, add to any existing expressions.
2663                Otherwise, this flattens all the `Order` expression into a single expression.
2664            dialect: the dialect used to parse the input expression.
2665            copy: if `False`, modify this expression instance in-place.
2666            opts: other options to use to parse the input expressions.
2667
2668        Returns:
2669            The modified Select expression.
2670        """
2671        return _apply_child_list_builder(
2672            *expressions,
2673            instance=self,
2674            arg="sort",
2675            append=append,
2676            copy=copy,
2677            prefix="SORT BY",
2678            into=Sort,
2679            dialect=dialect,
2680            **opts,
2681        )

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

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, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2723    def limit(
2724        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2725    ) -> Select:
2726        """
2727        Set the LIMIT expression.
2728
2729        Example:
2730            >>> Select().from_("tbl").select("x").limit(10).sql()
2731            'SELECT x FROM tbl LIMIT 10'
2732
2733        Args:
2734            expression: the SQL code string to parse.
2735                This can also be an integer.
2736                If a `Limit` instance is passed, this is used as-is.
2737                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2738            dialect: the dialect used to parse the input expression.
2739            copy: if `False`, modify this expression instance in-place.
2740            opts: other options to use to parse the input expressions.
2741
2742        Returns:
2743            Select: the modified expression.
2744        """
2745        return _apply_builder(
2746            expression=expression,
2747            instance=self,
2748            arg="limit",
2749            into=Limit,
2750            prefix="LIMIT",
2751            dialect=dialect,
2752            copy=copy,
2753            **opts,
2754        )

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, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2756    def offset(
2757        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2758    ) -> Select:
2759        """
2760        Set the OFFSET expression.
2761
2762        Example:
2763            >>> Select().from_("tbl").select("x").offset(10).sql()
2764            'SELECT x FROM tbl OFFSET 10'
2765
2766        Args:
2767            expression: the SQL code string to parse.
2768                This can also be an integer.
2769                If a `Offset` instance is passed, this is used as-is.
2770                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2771            dialect: the dialect used to parse the input expression.
2772            copy: if `False`, modify this expression instance in-place.
2773            opts: other options to use to parse the input expressions.
2774
2775        Returns:
2776            The modified Select expression.
2777        """
2778        return _apply_builder(
2779            expression=expression,
2780            instance=self,
2781            arg="offset",
2782            into=Offset,
2783            prefix="OFFSET",
2784            dialect=dialect,
2785            copy=copy,
2786            **opts,
2787        )

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, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2789    def select(
2790        self,
2791        *expressions: t.Optional[ExpOrStr],
2792        append: bool = True,
2793        dialect: DialectType = None,
2794        copy: bool = True,
2795        **opts,
2796    ) -> Select:
2797        """
2798        Append to or set the SELECT expressions.
2799
2800        Example:
2801            >>> Select().select("x", "y").sql()
2802            'SELECT x, y'
2803
2804        Args:
2805            *expressions: the SQL code strings to parse.
2806                If an `Expression` instance is passed, it will be used as-is.
2807            append: if `True`, add to any existing expressions.
2808                Otherwise, this resets the expressions.
2809            dialect: the dialect used to parse the input expressions.
2810            copy: if `False`, modify this expression instance in-place.
2811            opts: other options to use to parse the input expressions.
2812
2813        Returns:
2814            The modified Select expression.
2815        """
2816        return _apply_list_builder(
2817            *expressions,
2818            instance=self,
2819            arg="expressions",
2820            append=append,
2821            dialect=dialect,
2822            copy=copy,
2823            **opts,
2824        )

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, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2826    def lateral(
2827        self,
2828        *expressions: t.Optional[ExpOrStr],
2829        append: bool = True,
2830        dialect: DialectType = None,
2831        copy: bool = True,
2832        **opts,
2833    ) -> Select:
2834        """
2835        Append to or set the LATERAL expressions.
2836
2837        Example:
2838            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2839            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2840
2841        Args:
2842            *expressions: the SQL code strings to parse.
2843                If an `Expression` instance is passed, it will be used as-is.
2844            append: if `True`, add to any existing expressions.
2845                Otherwise, this resets the expressions.
2846            dialect: the dialect used to parse the input expressions.
2847            copy: if `False`, modify this expression instance in-place.
2848            opts: other options to use to parse the input expressions.
2849
2850        Returns:
2851            The modified Select expression.
2852        """
2853        return _apply_list_builder(
2854            *expressions,
2855            instance=self,
2856            arg="laterals",
2857            append=append,
2858            into=Lateral,
2859            prefix="LATERAL VIEW",
2860            dialect=dialect,
2861            copy=copy,
2862            **opts,
2863        )

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, sqlglot.expressions.Expression], on: Union[str, sqlglot.expressions.Expression, NoneType] = None, using: Union[str, sqlglot.expressions.Expression, List[Union[str, sqlglot.expressions.Expression]], NoneType] = None, append: bool = True, join_type: Optional[str] = None, join_alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2865    def join(
2866        self,
2867        expression: ExpOrStr,
2868        on: t.Optional[ExpOrStr] = None,
2869        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2870        append: bool = True,
2871        join_type: t.Optional[str] = None,
2872        join_alias: t.Optional[Identifier | str] = None,
2873        dialect: DialectType = None,
2874        copy: bool = True,
2875        **opts,
2876    ) -> Select:
2877        """
2878        Append to or set the JOIN expressions.
2879
2880        Example:
2881            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2882            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2883
2884            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2885            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2886
2887            Use `join_type` to change the type of join:
2888
2889            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2890            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2891
2892        Args:
2893            expression: the SQL code string to parse.
2894                If an `Expression` instance is passed, it will be used as-is.
2895            on: optionally specify the join "on" criteria as a SQL string.
2896                If an `Expression` instance is passed, it will be used as-is.
2897            using: optionally specify the join "using" criteria as a SQL string.
2898                If an `Expression` instance is passed, it will be used as-is.
2899            append: if `True`, add to any existing expressions.
2900                Otherwise, this resets the expressions.
2901            join_type: if set, alter the parsed join type.
2902            join_alias: an optional alias for the joined source.
2903            dialect: the dialect used to parse the input expressions.
2904            copy: if `False`, modify this expression instance in-place.
2905            opts: other options to use to parse the input expressions.
2906
2907        Returns:
2908            Select: the modified expression.
2909        """
2910        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2911
2912        try:
2913            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2914        except ParseError:
2915            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2916
2917        join = expression if isinstance(expression, Join) else Join(this=expression)
2918
2919        if isinstance(join.this, Select):
2920            join.this.replace(join.this.subquery())
2921
2922        if join_type:
2923            method: t.Optional[Token]
2924            side: t.Optional[Token]
2925            kind: t.Optional[Token]
2926
2927            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2928
2929            if method:
2930                join.set("method", method.text)
2931            if side:
2932                join.set("side", side.text)
2933            if kind:
2934                join.set("kind", kind.text)
2935
2936        if on:
2937            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2938            join.set("on", on)
2939
2940        if using:
2941            join = _apply_list_builder(
2942                *ensure_list(using),
2943                instance=join,
2944                arg="using",
2945                append=append,
2946                copy=copy,
2947                **opts,
2948            )
2949
2950        if join_alias:
2951            join.set("this", alias_(join.this, join_alias, table=True))
2952
2953        return _apply_list_builder(
2954            join,
2955            instance=self,
2956            arg="joins",
2957            append=append,
2958            copy=copy,
2959            **opts,
2960        )

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, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2962    def where(
2963        self,
2964        *expressions: t.Optional[ExpOrStr],
2965        append: bool = True,
2966        dialect: DialectType = None,
2967        copy: bool = True,
2968        **opts,
2969    ) -> Select:
2970        """
2971        Append to or set the WHERE expressions.
2972
2973        Example:
2974            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2975            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2976
2977        Args:
2978            *expressions: the SQL code strings to parse.
2979                If an `Expression` instance is passed, it will be used as-is.
2980                Multiple expressions are combined with an AND operator.
2981            append: if `True`, AND the new expressions to any existing expression.
2982                Otherwise, this resets the expression.
2983            dialect: the dialect used to parse the input expressions.
2984            copy: if `False`, modify this expression instance in-place.
2985            opts: other options to use to parse the input expressions.
2986
2987        Returns:
2988            Select: the modified expression.
2989        """
2990        return _apply_conjunction_builder(
2991            *expressions,
2992            instance=self,
2993            arg="where",
2994            append=append,
2995            into=Where,
2996            dialect=dialect,
2997            copy=copy,
2998            **opts,
2999        )

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, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
3001    def having(
3002        self,
3003        *expressions: t.Optional[ExpOrStr],
3004        append: bool = True,
3005        dialect: DialectType = None,
3006        copy: bool = True,
3007        **opts,
3008    ) -> Select:
3009        """
3010        Append to or set the HAVING expressions.
3011
3012        Example:
3013            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3014            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3015
3016        Args:
3017            *expressions: the SQL code strings to parse.
3018                If an `Expression` instance is passed, it will be used as-is.
3019                Multiple expressions are combined with an AND operator.
3020            append: if `True`, AND the new expressions to any existing expression.
3021                Otherwise, this resets the expression.
3022            dialect: the dialect used to parse the input expressions.
3023            copy: if `False`, modify this expression instance in-place.
3024            opts: other options to use to parse the input expressions.
3025
3026        Returns:
3027            The modified Select expression.
3028        """
3029        return _apply_conjunction_builder(
3030            *expressions,
3031            instance=self,
3032            arg="having",
3033            append=append,
3034            into=Having,
3035            dialect=dialect,
3036            copy=copy,
3037            **opts,
3038        )

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, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
3040    def window(
3041        self,
3042        *expressions: t.Optional[ExpOrStr],
3043        append: bool = True,
3044        dialect: DialectType = None,
3045        copy: bool = True,
3046        **opts,
3047    ) -> Select:
3048        return _apply_list_builder(
3049            *expressions,
3050            instance=self,
3051            arg="windows",
3052            append=append,
3053            into=Window,
3054            dialect=dialect,
3055            copy=copy,
3056            **opts,
3057        )
def qualify( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
3059    def qualify(
3060        self,
3061        *expressions: t.Optional[ExpOrStr],
3062        append: bool = True,
3063        dialect: DialectType = None,
3064        copy: bool = True,
3065        **opts,
3066    ) -> Select:
3067        return _apply_conjunction_builder(
3068            *expressions,
3069            instance=self,
3070            arg="qualify",
3071            append=append,
3072            into=Qualify,
3073            dialect=dialect,
3074            copy=copy,
3075            **opts,
3076        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3078    def distinct(
3079        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3080    ) -> Select:
3081        """
3082        Set the OFFSET expression.
3083
3084        Example:
3085            >>> Select().from_("tbl").select("x").distinct().sql()
3086            'SELECT DISTINCT x FROM tbl'
3087
3088        Args:
3089            ons: the expressions to distinct on
3090            distinct: whether the Select should be distinct
3091            copy: if `False`, modify this expression instance in-place.
3092
3093        Returns:
3094            Select: the modified expression.
3095        """
3096        instance = _maybe_copy(self, copy)
3097        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3098        instance.set("distinct", Distinct(on=on) if distinct else None)
3099        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, sqlglot.expressions.Expression], properties: Optional[Dict] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Create:
3101    def ctas(
3102        self,
3103        table: ExpOrStr,
3104        properties: t.Optional[t.Dict] = None,
3105        dialect: DialectType = None,
3106        copy: bool = True,
3107        **opts,
3108    ) -> Create:
3109        """
3110        Convert this expression to a CREATE TABLE AS statement.
3111
3112        Example:
3113            >>> Select().select("*").from_("tbl").ctas("x").sql()
3114            'CREATE TABLE x AS SELECT * FROM tbl'
3115
3116        Args:
3117            table: the SQL code string to parse as the table name.
3118                If another `Expression` instance is passed, it will be used as-is.
3119            properties: an optional mapping of table properties
3120            dialect: the dialect used to parse the input table.
3121            copy: if `False`, modify this expression instance in-place.
3122            opts: other options to use to parse the input table.
3123
3124        Returns:
3125            The new Create expression.
3126        """
3127        instance = _maybe_copy(self, copy)
3128        table_expression = maybe_parse(
3129            table,
3130            into=Table,
3131            dialect=dialect,
3132            **opts,
3133        )
3134        properties_expression = None
3135        if properties:
3136            properties_expression = Properties.from_dict(properties)
3137
3138        return Create(
3139            this=table_expression,
3140            kind="table",
3141            expression=instance,
3142            properties=properties_expression,
3143        )

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) -> sqlglot.expressions.Select:
3145    def lock(self, update: bool = True, copy: bool = True) -> Select:
3146        """
3147        Set the locking read mode for this expression.
3148
3149        Examples:
3150            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3151            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3152
3153            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3154            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3155
3156        Args:
3157            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3158            copy: if `False`, modify this expression instance in-place.
3159
3160        Returns:
3161            The modified expression.
3162        """
3163        inst = _maybe_copy(self, copy)
3164        inst.set("locks", [Lock(update=update)])
3165
3166        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, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True) -> sqlglot.expressions.Select:
3168    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3169        """
3170        Set hints for this expression.
3171
3172        Examples:
3173            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3174            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3175
3176        Args:
3177            hints: The SQL code strings to parse as the hints.
3178                If an `Expression` instance is passed, it will be used as-is.
3179            dialect: The dialect used to parse the hints.
3180            copy: If `False`, modify this expression instance in-place.
3181
3182        Returns:
3183            The modified expression.
3184        """
3185        inst = _maybe_copy(self, copy)
3186        inst.set(
3187            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3188        )
3189
3190        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.

key = 'select'
class Subquery(DerivedTable, Unionable):
3205class Subquery(DerivedTable, Unionable):
3206    arg_types = {
3207        "this": True,
3208        "alias": False,
3209        "with": False,
3210        **QUERY_MODIFIERS,
3211    }
3212
3213    def unnest(self):
3214        """
3215        Returns the first non subquery.
3216        """
3217        expression = self
3218        while isinstance(expression, Subquery):
3219            expression = expression.this
3220        return expression
3221
3222    @property
3223    def is_star(self) -> bool:
3224        return self.this.is_star
3225
3226    @property
3227    def output_name(self) -> str:
3228        return self.alias
arg_types = {'this': True, 'alias': False, 'with': False, 'match': False, 'laterals': False, 'joins': 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):
3213    def unnest(self):
3214        """
3215        Returns the first non subquery.
3216        """
3217        expression = self
3218        while isinstance(expression, Subquery):
3219            expression = expression.this
3220        return expression

Returns the first non subquery.

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").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'subquery'
class TableSample(Expression):
3231class TableSample(Expression):
3232    arg_types = {
3233        "this": False,
3234        "method": False,
3235        "bucket_numerator": False,
3236        "bucket_denominator": False,
3237        "bucket_field": False,
3238        "percent": False,
3239        "rows": False,
3240        "size": False,
3241        "seed": False,
3242        "kind": False,
3243    }
arg_types = {'this': 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):
3246class Tag(Expression):
3247    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3248
3249    arg_types = {
3250        "this": False,
3251        "prefix": False,
3252        "postfix": False,
3253    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3258class Pivot(Expression):
3259    arg_types = {
3260        "this": False,
3261        "alias": False,
3262        "expressions": True,
3263        "field": False,
3264        "unpivot": False,
3265        "using": False,
3266        "group": False,
3267        "columns": False,
3268    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3271class Window(Expression):
3272    arg_types = {
3273        "this": True,
3274        "partition_by": False,
3275        "order": False,
3276        "spec": False,
3277        "alias": False,
3278        "over": False,
3279        "first": False,
3280    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3283class WindowSpec(Expression):
3284    arg_types = {
3285        "kind": False,
3286        "start": False,
3287        "start_side": False,
3288        "end": False,
3289        "end_side": False,
3290    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3293class Where(Expression):
3294    pass
key = 'where'
class Star(Expression):
3297class Star(Expression):
3298    arg_types = {"except": False, "replace": False}
3299
3300    @property
3301    def name(self) -> str:
3302        return "*"
3303
3304    @property
3305    def output_name(self) -> str:
3306        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").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'star'
class Parameter(Condition):
3309class Parameter(Condition):
3310    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3313class SessionParameter(Condition):
3314    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3317class Placeholder(Condition):
3318    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3321class Null(Condition):
3322    arg_types: t.Dict[str, t.Any] = {}
3323
3324    @property
3325    def name(self) -> str:
3326        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3329class Boolean(Condition):
3330    pass
key = 'boolean'
class DataTypeSize(Expression):
3333class DataTypeSize(Expression):
3334    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3337class DataType(Expression):
3338    arg_types = {
3339        "this": True,
3340        "expressions": False,
3341        "nested": False,
3342        "values": False,
3343        "prefix": False,
3344    }
3345
3346    class Type(AutoName):
3347        ARRAY = auto()
3348        BIGDECIMAL = auto()
3349        BIGINT = auto()
3350        BIGSERIAL = auto()
3351        BINARY = auto()
3352        BIT = auto()
3353        BOOLEAN = auto()
3354        CHAR = auto()
3355        DATE = auto()
3356        DATETIME = auto()
3357        DATETIME64 = auto()
3358        ENUM = auto()
3359        INT4RANGE = auto()
3360        INT4MULTIRANGE = auto()
3361        INT8RANGE = auto()
3362        INT8MULTIRANGE = auto()
3363        NUMRANGE = auto()
3364        NUMMULTIRANGE = auto()
3365        TSRANGE = auto()
3366        TSMULTIRANGE = auto()
3367        TSTZRANGE = auto()
3368        TSTZMULTIRANGE = auto()
3369        DATERANGE = auto()
3370        DATEMULTIRANGE = auto()
3371        DECIMAL = auto()
3372        DOUBLE = auto()
3373        FLOAT = auto()
3374        GEOGRAPHY = auto()
3375        GEOMETRY = auto()
3376        HLLSKETCH = auto()
3377        HSTORE = auto()
3378        IMAGE = auto()
3379        INET = auto()
3380        INT = auto()
3381        INT128 = auto()
3382        INT256 = auto()
3383        INTERVAL = auto()
3384        JSON = auto()
3385        JSONB = auto()
3386        LONGBLOB = auto()
3387        LONGTEXT = auto()
3388        MAP = auto()
3389        MEDIUMBLOB = auto()
3390        MEDIUMTEXT = auto()
3391        MONEY = auto()
3392        NCHAR = auto()
3393        NULL = auto()
3394        NULLABLE = auto()
3395        NVARCHAR = auto()
3396        OBJECT = auto()
3397        ROWVERSION = auto()
3398        SERIAL = auto()
3399        SET = auto()
3400        SMALLINT = auto()
3401        SMALLMONEY = auto()
3402        SMALLSERIAL = auto()
3403        STRUCT = auto()
3404        SUPER = auto()
3405        TEXT = auto()
3406        TIME = auto()
3407        TIMESTAMP = auto()
3408        TIMESTAMPTZ = auto()
3409        TIMESTAMPLTZ = auto()
3410        TINYINT = auto()
3411        UBIGINT = auto()
3412        UINT = auto()
3413        USMALLINT = auto()
3414        UTINYINT = auto()
3415        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3416        UINT128 = auto()
3417        UINT256 = auto()
3418        UNIQUEIDENTIFIER = auto()
3419        USERDEFINED = "USER-DEFINED"
3420        UUID = auto()
3421        VARBINARY = auto()
3422        VARCHAR = auto()
3423        VARIANT = auto()
3424        XML = auto()
3425
3426    TEXT_TYPES = {
3427        Type.CHAR,
3428        Type.NCHAR,
3429        Type.VARCHAR,
3430        Type.NVARCHAR,
3431        Type.TEXT,
3432    }
3433
3434    INTEGER_TYPES = {
3435        Type.INT,
3436        Type.TINYINT,
3437        Type.SMALLINT,
3438        Type.BIGINT,
3439        Type.INT128,
3440        Type.INT256,
3441    }
3442
3443    FLOAT_TYPES = {
3444        Type.FLOAT,
3445        Type.DOUBLE,
3446    }
3447
3448    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3449
3450    TEMPORAL_TYPES = {
3451        Type.TIME,
3452        Type.TIMESTAMP,
3453        Type.TIMESTAMPTZ,
3454        Type.TIMESTAMPLTZ,
3455        Type.DATE,
3456        Type.DATETIME,
3457        Type.DATETIME64,
3458    }
3459
3460    META_TYPES = {"UNKNOWN", "NULL"}
3461
3462    @classmethod
3463    def build(
3464        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3465    ) -> DataType:
3466        from sqlglot import parse_one
3467
3468        if isinstance(dtype, str):
3469            upper = dtype.upper()
3470            if upper in DataType.META_TYPES:
3471                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3472            else:
3473                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3474
3475            if data_type_exp is None:
3476                raise ValueError(f"Unparsable data type value: {dtype}")
3477        elif isinstance(dtype, DataType.Type):
3478            data_type_exp = DataType(this=dtype)
3479        elif isinstance(dtype, DataType):
3480            return dtype
3481        else:
3482            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3483
3484        return DataType(**{**data_type_exp.args, **kwargs})
3485
3486    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3487        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False}
TEXT_TYPES = {<Type.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.TEXT: 'TEXT'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>}
INTEGER_TYPES = {<Type.INT: 'INT'>, <Type.INT128: 'INT128'>, <Type.SMALLINT: 'SMALLINT'>, <Type.TINYINT: 'TINYINT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT256: 'INT256'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.SMALLINT: 'SMALLINT'>, <Type.TINYINT: 'TINYINT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT256: 'INT256'>, <Type.FLOAT: 'FLOAT'>, <Type.INT: 'INT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.INT128: 'INT128'>}
TEMPORAL_TYPES = {<Type.DATE: 'DATE'>, <Type.DATETIME: 'DATETIME'>, <Type.DATETIME64: 'DATETIME64'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.TIME: 'TIME'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>}
META_TYPES = {'NULL', 'UNKNOWN'}
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
3462    @classmethod
3463    def build(
3464        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3465    ) -> DataType:
3466        from sqlglot import parse_one
3467
3468        if isinstance(dtype, str):
3469            upper = dtype.upper()
3470            if upper in DataType.META_TYPES:
3471                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3472            else:
3473                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3474
3475            if data_type_exp is None:
3476                raise ValueError(f"Unparsable data type value: {dtype}")
3477        elif isinstance(dtype, DataType.Type):
3478            data_type_exp = DataType(this=dtype)
3479        elif isinstance(dtype, DataType):
3480            return dtype
3481        else:
3482            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3483
3484        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3486    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3487        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3346    class Type(AutoName):
3347        ARRAY = auto()
3348        BIGDECIMAL = auto()
3349        BIGINT = auto()
3350        BIGSERIAL = auto()
3351        BINARY = auto()
3352        BIT = auto()
3353        BOOLEAN = auto()
3354        CHAR = auto()
3355        DATE = auto()
3356        DATETIME = auto()
3357        DATETIME64 = auto()
3358        ENUM = auto()
3359        INT4RANGE = auto()
3360        INT4MULTIRANGE = auto()
3361        INT8RANGE = auto()
3362        INT8MULTIRANGE = auto()
3363        NUMRANGE = auto()
3364        NUMMULTIRANGE = auto()
3365        TSRANGE = auto()
3366        TSMULTIRANGE = auto()
3367        TSTZRANGE = auto()
3368        TSTZMULTIRANGE = auto()
3369        DATERANGE = auto()
3370        DATEMULTIRANGE = auto()
3371        DECIMAL = auto()
3372        DOUBLE = auto()
3373        FLOAT = auto()
3374        GEOGRAPHY = auto()
3375        GEOMETRY = auto()
3376        HLLSKETCH = auto()
3377        HSTORE = auto()
3378        IMAGE = auto()
3379        INET = auto()
3380        INT = auto()
3381        INT128 = auto()
3382        INT256 = auto()
3383        INTERVAL = auto()
3384        JSON = auto()
3385        JSONB = auto()
3386        LONGBLOB = auto()
3387        LONGTEXT = auto()
3388        MAP = auto()
3389        MEDIUMBLOB = auto()
3390        MEDIUMTEXT = auto()
3391        MONEY = auto()
3392        NCHAR = auto()
3393        NULL = auto()
3394        NULLABLE = auto()
3395        NVARCHAR = auto()
3396        OBJECT = auto()
3397        ROWVERSION = auto()
3398        SERIAL = auto()
3399        SET = auto()
3400        SMALLINT = auto()
3401        SMALLMONEY = auto()
3402        SMALLSERIAL = auto()
3403        STRUCT = auto()
3404        SUPER = auto()
3405        TEXT = auto()
3406        TIME = auto()
3407        TIMESTAMP = auto()
3408        TIMESTAMPTZ = auto()
3409        TIMESTAMPLTZ = auto()
3410        TINYINT = auto()
3411        UBIGINT = auto()
3412        UINT = auto()
3413        USMALLINT = auto()
3414        UTINYINT = auto()
3415        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3416        UINT128 = auto()
3417        UINT256 = auto()
3418        UNIQUEIDENTIFIER = auto()
3419        USERDEFINED = "USER-DEFINED"
3420        UUID = auto()
3421        VARBINARY = auto()
3422        VARCHAR = auto()
3423        VARIANT = auto()
3424        XML = 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'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
ENUM = <Type.ENUM: 'ENUM'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
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'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
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'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3491class PseudoType(Expression):
3492    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3496class SubqueryPredicate(Predicate):
3497    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3500class All(SubqueryPredicate):
3501    pass
key = 'all'
class Any(SubqueryPredicate):
3504class Any(SubqueryPredicate):
3505    pass
key = 'any'
class Exists(SubqueryPredicate):
3508class Exists(SubqueryPredicate):
3509    pass
key = 'exists'
class Command(Expression):
3514class Command(Expression):
3515    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3518class Transaction(Expression):
3519    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3522class Commit(Expression):
3523    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3526class Rollback(Expression):
3527    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3530class AlterTable(Expression):
3531    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3534class AddConstraint(Expression):
3535    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3538class DropPartition(Expression):
3539    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3543class Binary(Condition):
3544    arg_types = {"this": True, "expression": True}
3545
3546    @property
3547    def left(self):
3548        return self.this
3549
3550    @property
3551    def right(self):
3552        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3555class Add(Binary):
3556    pass
key = 'add'
class Connector(Binary):
3559class Connector(Binary):
3560    pass
key = 'connector'
class And(Connector):
3563class And(Connector):
3564    pass
key = 'and'
class Or(Connector):
3567class Or(Connector):
3568    pass
key = 'or'
class BitwiseAnd(Binary):
3571class BitwiseAnd(Binary):
3572    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3575class BitwiseLeftShift(Binary):
3576    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3579class BitwiseOr(Binary):
3580    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3583class BitwiseRightShift(Binary):
3584    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3587class BitwiseXor(Binary):
3588    pass
key = 'bitwisexor'
class Div(Binary):
3591class Div(Binary):
3592    pass
key = 'div'
class Overlaps(Binary):
3595class Overlaps(Binary):
3596    pass
key = 'overlaps'
class Dot(Binary):
3599class Dot(Binary):
3600    @property
3601    def name(self) -> str:
3602        return self.expression.name
3603
3604    @property
3605    def output_name(self) -> str:
3606        return self.name
3607
3608    @classmethod
3609    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3610        """Build a Dot object with a sequence of expressions."""
3611        if len(expressions) < 2:
3612            raise ValueError(f"Dot requires >= 2 expressions.")
3613
3614        a, b, *expressions = expressions
3615        dot = Dot(this=a, expression=b)
3616
3617        for expression in expressions:
3618            dot = Dot(this=dot, expression=expression)
3619
3620        return dot
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").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3608    @classmethod
3609    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3610        """Build a Dot object with a sequence of expressions."""
3611        if len(expressions) < 2:
3612            raise ValueError(f"Dot requires >= 2 expressions.")
3613
3614        a, b, *expressions = expressions
3615        dot = Dot(this=a, expression=b)
3616
3617        for expression in expressions:
3618            dot = Dot(this=dot, expression=expression)
3619
3620        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3623class DPipe(Binary):
3624    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3627class SafeDPipe(DPipe):
3628    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3631class EQ(Binary, Predicate):
3632    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3635class NullSafeEQ(Binary, Predicate):
3636    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3639class NullSafeNEQ(Binary, Predicate):
3640    pass
key = 'nullsafeneq'
class Distance(Binary):
3643class Distance(Binary):
3644    pass
key = 'distance'
class Escape(Binary):
3647class Escape(Binary):
3648    pass
key = 'escape'
class Glob(Binary, Predicate):
3651class Glob(Binary, Predicate):
3652    pass
key = 'glob'
class GT(Binary, Predicate):
3655class GT(Binary, Predicate):
3656    pass
key = 'gt'
class GTE(Binary, Predicate):
3659class GTE(Binary, Predicate):
3660    pass
key = 'gte'
class ILike(Binary, Predicate):
3663class ILike(Binary, Predicate):
3664    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3667class ILikeAny(Binary, Predicate):
3668    pass
key = 'ilikeany'
class IntDiv(Binary):
3671class IntDiv(Binary):
3672    pass
key = 'intdiv'
class Is(Binary, Predicate):
3675class Is(Binary, Predicate):
3676    pass
key = 'is'
class Kwarg(Binary):
3679class Kwarg(Binary):
3680    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3683class Like(Binary, Predicate):
3684    pass
key = 'like'
class LikeAny(Binary, Predicate):
3687class LikeAny(Binary, Predicate):
3688    pass
key = 'likeany'
class LT(Binary, Predicate):
3691class LT(Binary, Predicate):
3692    pass
key = 'lt'
class LTE(Binary, Predicate):
3695class LTE(Binary, Predicate):
3696    pass
key = 'lte'
class Mod(Binary):
3699class Mod(Binary):
3700    pass
key = 'mod'
class Mul(Binary):
3703class Mul(Binary):
3704    pass
key = 'mul'
class NEQ(Binary, Predicate):
3707class NEQ(Binary, Predicate):
3708    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3711class SimilarTo(Binary, Predicate):
3712    pass
key = 'similarto'
class Slice(Binary):
3715class Slice(Binary):
3716    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3719class Sub(Binary):
3720    pass
key = 'sub'
class ArrayOverlaps(Binary):
3723class ArrayOverlaps(Binary):
3724    pass
key = 'arrayoverlaps'
class Unary(Condition):
3729class Unary(Condition):
3730    pass
key = 'unary'
class BitwiseNot(Unary):
3733class BitwiseNot(Unary):
3734    pass
key = 'bitwisenot'
class Not(Unary):
3737class Not(Unary):
3738    pass
key = 'not'
class Paren(Unary):
3741class Paren(Unary):
3742    arg_types = {"this": True, "with": False}
3743
3744    @property
3745    def output_name(self) -> str:
3746        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").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'paren'
class Neg(Unary):
3749class Neg(Unary):
3750    pass
key = 'neg'
class Alias(Expression):
3753class Alias(Expression):
3754    arg_types = {"this": True, "alias": False}
3755
3756    @property
3757    def output_name(self) -> str:
3758        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").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'alias'
class Aliases(Expression):
3761class Aliases(Expression):
3762    arg_types = {"this": True, "expressions": True}
3763
3764    @property
3765    def aliases(self):
3766        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3769class AtTimeZone(Expression):
3770    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3773class Between(Predicate):
3774    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3777class Bracket(Condition):
3778    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3781class SafeBracket(Bracket):
3782    """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):
3785class Distinct(Expression):
3786    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3789class In(Predicate):
3790    arg_types = {
3791        "this": True,
3792        "expressions": False,
3793        "query": False,
3794        "unnest": False,
3795        "field": False,
3796        "is_global": False,
3797    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3800class TimeUnit(Expression):
3801    """Automatically converts unit arg into a var."""
3802
3803    arg_types = {"unit": False}
3804
3805    def __init__(self, **args):
3806        unit = args.get("unit")
3807        if isinstance(unit, (Column, Literal)):
3808            args["unit"] = Var(this=unit.name)
3809        elif isinstance(unit, Week):
3810            unit.set("this", Var(this=unit.this.name))
3811
3812        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3805    def __init__(self, **args):
3806        unit = args.get("unit")
3807        if isinstance(unit, (Column, Literal)):
3808            args["unit"] = Var(this=unit.name)
3809        elif isinstance(unit, Week):
3810            unit.set("this", Var(this=unit.this.name))
3811
3812        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3815class Interval(TimeUnit):
3816    arg_types = {"this": False, "unit": False}
3817
3818    @property
3819    def unit(self) -> t.Optional[Var]:
3820        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3823class IgnoreNulls(Expression):
3824    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3827class RespectNulls(Expression):
3828    pass
key = 'respectnulls'
class Func(Condition):
3832class Func(Condition):
3833    """
3834    The base class for all function expressions.
3835
3836    Attributes:
3837        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3838            treated as a variable length argument and the argument's value will be stored as a list.
3839        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3840            for this function expression. These values are used to map this node to a name during parsing
3841            as well as to provide the function's name during SQL string generation. By default the SQL
3842            name is set to the expression's class name transformed to snake case.
3843    """
3844
3845    is_var_len_args = False
3846
3847    @classmethod
3848    def from_arg_list(cls, args):
3849        if cls.is_var_len_args:
3850            all_arg_keys = list(cls.arg_types)
3851            # If this function supports variable length argument treat the last argument as such.
3852            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3853            num_non_var = len(non_var_len_arg_keys)
3854
3855            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3856            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3857        else:
3858            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3859
3860        return cls(**args_dict)
3861
3862    @classmethod
3863    def sql_names(cls):
3864        if cls is Func:
3865            raise NotImplementedError(
3866                "SQL name is only supported by concrete function implementations"
3867            )
3868        if "_sql_names" not in cls.__dict__:
3869            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3870        return cls._sql_names
3871
3872    @classmethod
3873    def sql_name(cls):
3874        return cls.sql_names()[0]
3875
3876    @classmethod
3877    def default_parser_mappings(cls):
3878        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):
3847    @classmethod
3848    def from_arg_list(cls, args):
3849        if cls.is_var_len_args:
3850            all_arg_keys = list(cls.arg_types)
3851            # If this function supports variable length argument treat the last argument as such.
3852            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3853            num_non_var = len(non_var_len_arg_keys)
3854
3855            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3856            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3857        else:
3858            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3859
3860        return cls(**args_dict)
@classmethod
def sql_names(cls):
3862    @classmethod
3863    def sql_names(cls):
3864        if cls is Func:
3865            raise NotImplementedError(
3866                "SQL name is only supported by concrete function implementations"
3867            )
3868        if "_sql_names" not in cls.__dict__:
3869            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3870        return cls._sql_names
@classmethod
def sql_name(cls):
3872    @classmethod
3873    def sql_name(cls):
3874        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3876    @classmethod
3877    def default_parser_mappings(cls):
3878        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3881class AggFunc(Func):
3882    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3885class ParameterizedAgg(AggFunc):
3886    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3889class Abs(Func):
3890    pass
key = 'abs'
class Transform(Func):
3894class Transform(Func):
3895    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
3898class Anonymous(Func):
3899    arg_types = {"this": True, "expressions": False}
3900    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3905class Hll(AggFunc):
3906    arg_types = {"this": True, "expressions": False}
3907    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3910class ApproxDistinct(AggFunc):
3911    arg_types = {"this": True, "accuracy": False}
3912    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3915class Array(Func):
3916    arg_types = {"expressions": False}
3917    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3921class ToChar(Func):
3922    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3925class GenerateSeries(Func):
3926    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3929class ArrayAgg(AggFunc):
3930    pass
key = 'arrayagg'
class ArrayAll(Func):
3933class ArrayAll(Func):
3934    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3937class ArrayAny(Func):
3938    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3941class ArrayConcat(Func):
3942    arg_types = {"this": True, "expressions": False}
3943    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3946class ArrayContains(Binary, Func):
3947    pass
key = 'arraycontains'
class ArrayContained(Binary):
3950class ArrayContained(Binary):
3951    pass
key = 'arraycontained'
class ArrayFilter(Func):
3954class ArrayFilter(Func):
3955    arg_types = {"this": True, "expression": True}
3956    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3959class ArrayJoin(Func):
3960    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3963class ArraySize(Func):
3964    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3967class ArraySort(Func):
3968    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3971class ArraySum(Func):
3972    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3975class ArrayUnionAgg(AggFunc):
3976    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3979class Avg(AggFunc):
3980    pass
key = 'avg'
class AnyValue(AggFunc):
3983class AnyValue(AggFunc):
3984    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
3987class Case(Func):
3988    arg_types = {"this": False, "ifs": True, "default": False}
3989
3990    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3991        instance = _maybe_copy(self, copy)
3992        instance.append(
3993            "ifs",
3994            If(
3995                this=maybe_parse(condition, copy=copy, **opts),
3996                true=maybe_parse(then, copy=copy, **opts),
3997            ),
3998        )
3999        return instance
4000
4001    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4002        instance = _maybe_copy(self, copy)
4003        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4004        return instance
arg_types = {'this': False, 'ifs': True, 'default': False}
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3990    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3991        instance = _maybe_copy(self, copy)
3992        instance.append(
3993            "ifs",
3994            If(
3995                this=maybe_parse(condition, copy=copy, **opts),
3996                true=maybe_parse(then, copy=copy, **opts),
3997            ),
3998        )
3999        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4001    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4002        instance = _maybe_copy(self, copy)
4003        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4004        return instance
key = 'case'
class Cast(Func):
4007class Cast(Func):
4008    arg_types = {"this": True, "to": True, "format": False}
4009
4010    @property
4011    def name(self) -> str:
4012        return self.this.name
4013
4014    @property
4015    def to(self) -> DataType:
4016        return self.args["to"]
4017
4018    @property
4019    def output_name(self) -> str:
4020        return self.name
4021
4022    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4023        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True, 'format': 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").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
4022    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4023        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
4026class CastToStrType(Func):
4027    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
4030class Collate(Binary):
4031    pass
key = 'collate'
class TryCast(Cast):
4034class TryCast(Cast):
4035    pass
key = 'trycast'
class Ceil(Func):
4038class Ceil(Func):
4039    arg_types = {"this": True, "decimals": False}
4040    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4043class Coalesce(Func):
4044    arg_types = {"this": True, "expressions": False}
4045    is_var_len_args = True
4046    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4049class Concat(Func):
4050    arg_types = {"expressions": True}
4051    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4054class SafeConcat(Concat):
4055    pass
key = 'safeconcat'
class ConcatWs(Concat):
4058class ConcatWs(Concat):
4059    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4062class Count(AggFunc):
4063    arg_types = {"this": False, "expressions": False}
4064    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4067class CountIf(AggFunc):
4068    pass
key = 'countif'
class CurrentDate(Func):
4071class CurrentDate(Func):
4072    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4075class CurrentDatetime(Func):
4076    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4079class CurrentTime(Func):
4080    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4083class CurrentTimestamp(Func):
4084    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4087class CurrentUser(Func):
4088    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4091class DateAdd(Func, TimeUnit):
4092    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4095class DateSub(Func, TimeUnit):
4096    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4099class DateDiff(Func, TimeUnit):
4100    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4101    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4104class DateTrunc(Func):
4105    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4108class DatetimeAdd(Func, TimeUnit):
4109    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4112class DatetimeSub(Func, TimeUnit):
4113    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4116class DatetimeDiff(Func, TimeUnit):
4117    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4120class DatetimeTrunc(Func, TimeUnit):
4121    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4124class DayOfWeek(Func):
4125    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4128class DayOfMonth(Func):
4129    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4132class DayOfYear(Func):
4133    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4136class WeekOfYear(Func):
4137    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4140class MonthsBetween(Func):
4141    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4144class LastDateOfMonth(Func):
4145    pass
key = 'lastdateofmonth'
class Extract(Func):
4148class Extract(Func):
4149    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4152class TimestampAdd(Func, TimeUnit):
4153    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4156class TimestampSub(Func, TimeUnit):
4157    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4160class TimestampDiff(Func, TimeUnit):
4161    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4164class TimestampTrunc(Func, TimeUnit):
4165    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4168class TimeAdd(Func, TimeUnit):
4169    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4172class TimeSub(Func, TimeUnit):
4173    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4176class TimeDiff(Func, TimeUnit):
4177    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4180class TimeTrunc(Func, TimeUnit):
4181    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4184class DateFromParts(Func):
4185    _sql_names = ["DATEFROMPARTS"]
4186    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4189class DateStrToDate(Func):
4190    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4193class DateToDateStr(Func):
4194    pass
key = 'datetodatestr'
class DateToDi(Func):
4197class DateToDi(Func):
4198    pass
key = 'datetodi'
class Date(Func):
4202class Date(Func):
4203    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4206class Day(Func):
4207    pass
key = 'day'
class Decode(Func):
4210class Decode(Func):
4211    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4214class DiToDate(Func):
4215    pass
key = 'ditodate'
class Encode(Func):
4218class Encode(Func):
4219    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4222class Exp(Func):
4223    pass
key = 'exp'
class Explode(Func):
4226class Explode(Func):
4227    pass
key = 'explode'
class Floor(Func):
4230class Floor(Func):
4231    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4234class FromBase64(Func):
4235    pass
key = 'frombase64'
class ToBase64(Func):
4238class ToBase64(Func):
4239    pass
key = 'tobase64'
class Greatest(Func):
4242class Greatest(Func):
4243    arg_types = {"this": True, "expressions": False}
4244    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4247class GroupConcat(Func):
4248    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4251class Hex(Func):
4252    pass
key = 'hex'
class Xor(Connector, Func):
4255class Xor(Connector, Func):
4256    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4259class If(Func):
4260    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4263class Initcap(Func):
4264    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4267class JSONKeyValue(Expression):
4268    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4271class JSONObject(Func):
4272    arg_types = {
4273        "expressions": False,
4274        "null_handling": False,
4275        "unique_keys": False,
4276        "return_type": False,
4277        "format_json": False,
4278        "encoding": False,
4279    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4282class OpenJSONColumnDef(Expression):
4283    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):
4286class OpenJSON(Func):
4287    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4290class JSONBContains(Binary):
4291    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4294class JSONExtract(Binary, Func):
4295    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4298class JSONExtractScalar(JSONExtract):
4299    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4302class JSONBExtract(JSONExtract):
4303    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4306class JSONBExtractScalar(JSONExtract):
4307    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4310class JSONFormat(Func):
4311    arg_types = {"this": False, "options": False}
4312    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4316class JSONArrayContains(Binary, Predicate, Func):
4317    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4320class Least(Func):
4321    arg_types = {"this": True, "expressions": False}
4322    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4325class Left(Func):
4326    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4333class Length(Func):
4334    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4337class Levenshtein(Func):
4338    arg_types = {
4339        "this": True,
4340        "expression": False,
4341        "ins_cost": False,
4342        "del_cost": False,
4343        "sub_cost": False,
4344    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4347class Ln(Func):
4348    pass
key = 'ln'
class Log(Func):
4351class Log(Func):
4352    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4355class Log2(Func):
4356    pass
key = 'log2'
class Log10(Func):
4359class Log10(Func):
4360    pass
key = 'log10'
class LogicalOr(AggFunc):
4363class LogicalOr(AggFunc):
4364    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4367class LogicalAnd(AggFunc):
4368    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4371class Lower(Func):
4372    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4375class Map(Func):
4376    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4379class MapFromEntries(Func):
4380    pass
key = 'mapfromentries'
class StarMap(Func):
4383class StarMap(Func):
4384    pass
key = 'starmap'
class VarMap(Func):
4387class VarMap(Func):
4388    arg_types = {"keys": True, "values": True}
4389    is_var_len_args = True
4390
4391    @property
4392    def keys(self) -> t.List[Expression]:
4393        return self.args["keys"].expressions
4394
4395    @property
4396    def values(self) -> t.List[Expression]:
4397        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4401class MatchAgainst(Func):
4402    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4405class Max(AggFunc):
4406    arg_types = {"this": True, "expressions": False}
4407    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4410class MD5(Func):
4411    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4415class MD5Digest(Func):
4416    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4419class Min(AggFunc):
4420    arg_types = {"this": True, "expressions": False}
4421    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4424class Month(Func):
4425    pass
key = 'month'
class Nvl2(Func):
4428class Nvl2(Func):
4429    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4432class Posexplode(Func):
4433    pass
key = 'posexplode'
class Pow(Binary, Func):
4436class Pow(Binary, Func):
4437    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4440class PercentileCont(AggFunc):
4441    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4444class PercentileDisc(AggFunc):
4445    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4448class Quantile(AggFunc):
4449    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4452class ApproxQuantile(Quantile):
4453    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):
4456class RangeN(Func):
4457    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4460class ReadCSV(Func):
4461    _sql_names = ["READ_CSV"]
4462    is_var_len_args = True
4463    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4466class Reduce(Func):
4467    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):
4470class RegexpExtract(Func):
4471    arg_types = {
4472        "this": True,
4473        "expression": True,
4474        "position": False,
4475        "occurrence": False,
4476        "parameters": False,
4477        "group": False,
4478    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4481class RegexpReplace(Func):
4482    arg_types = {
4483        "this": True,
4484        "expression": True,
4485        "replacement": True,
4486        "position": False,
4487        "occurrence": False,
4488        "parameters": False,
4489    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4492class RegexpLike(Binary, Func):
4493    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4496class RegexpILike(Func):
4497    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4502class RegexpSplit(Func):
4503    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4506class Repeat(Func):
4507    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4510class Round(Func):
4511    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4514class RowNumber(Func):
4515    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4518class SafeDivide(Func):
4519    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4522class SetAgg(AggFunc):
4523    pass
key = 'setagg'
class SHA(Func):
4526class SHA(Func):
4527    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4530class SHA2(Func):
4531    _sql_names = ["SHA2"]
4532    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4535class SortArray(Func):
4536    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4539class Split(Func):
4540    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4545class Substring(Func):
4546    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4549class StandardHash(Func):
4550    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4553class StrPosition(Func):
4554    arg_types = {
4555        "this": True,
4556        "substr": True,
4557        "position": False,
4558        "instance": False,
4559    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4562class StrToDate(Func):
4563    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4566class StrToTime(Func):
4567    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4572class StrToUnix(Func):
4573    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4576class NumberToStr(Func):
4577    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4580class FromBase(Func):
4581    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4584class Struct(Func):
4585    arg_types = {"expressions": True}
4586    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4589class StructExtract(Func):
4590    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4593class Sum(AggFunc):
4594    pass
key = 'sum'
class Sqrt(Func):
4597class Sqrt(Func):
4598    pass
key = 'sqrt'
class Stddev(AggFunc):
4601class Stddev(AggFunc):
4602    pass
key = 'stddev'
class StddevPop(AggFunc):
4605class StddevPop(AggFunc):
4606    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4609class StddevSamp(AggFunc):
4610    pass
key = 'stddevsamp'
class TimeToStr(Func):
4613class TimeToStr(Func):
4614    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4617class TimeToTimeStr(Func):
4618    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4621class TimeToUnix(Func):
4622    pass
key = 'timetounix'
class TimeStrToDate(Func):
4625class TimeStrToDate(Func):
4626    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4629class TimeStrToTime(Func):
4630    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4633class TimeStrToUnix(Func):
4634    pass
key = 'timestrtounix'
class Trim(Func):
4637class Trim(Func):
4638    arg_types = {
4639        "this": True,
4640        "expression": False,
4641        "position": False,
4642        "collation": False,
4643    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4646class TsOrDsAdd(Func, TimeUnit):
4647    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4650class TsOrDsToDateStr(Func):
4651    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4654class TsOrDsToDate(Func):
4655    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4658class TsOrDiToDi(Func):
4659    pass
key = 'tsorditodi'
class Unhex(Func):
4662class Unhex(Func):
4663    pass
key = 'unhex'
class UnixToStr(Func):
4666class UnixToStr(Func):
4667    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4672class UnixToTime(Func):
4673    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4674
4675    SECONDS = Literal.string("seconds")
4676    MILLIS = Literal.string("millis")
4677    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):
4680class UnixToTimeStr(Func):
4681    pass
key = 'unixtotimestr'
class Upper(Func):
4684class Upper(Func):
4685    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4688class Variance(AggFunc):
4689    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4692class VariancePop(AggFunc):
4693    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4696class Week(Func):
4697    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4700class XMLTable(Func):
4701    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):
4704class Year(Func):
4705    pass
key = 'year'
class Use(Expression):
4708class Use(Expression):
4709    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4712class Merge(Expression):
4713    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):
4716class When(Func):
4717    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):
4722class NextValueFor(Func):
4723    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.JSONArrayContains'>, <class 'sqlglot.expressions.JSONBExtract'>, <class 'sqlglot.expressions.JSONBExtractScalar'>, <class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.JSONExtractScalar'>, <class 'sqlglot.expressions.JSONFormat'>, <class 'sqlglot.expressions.JSONObject'>, <class 'sqlglot.expressions.LastDateOfMonth'>, <class 'sqlglot.expressions.Least'>, <class 'sqlglot.expressions.Left'>, <class 'sqlglot.expressions.Length'>, <class 'sqlglot.expressions.Levenshtein'>, <class 'sqlglot.expressions.Ln'>, <class 'sqlglot.expressions.Log'>, <class 'sqlglot.expressions.Log10'>, <class 'sqlglot.expressions.Log2'>, <class 'sqlglot.expressions.LogicalAnd'>, <class 'sqlglot.expressions.LogicalOr'>, <class 'sqlglot.expressions.Lower'>, <class 'sqlglot.expressions.MD5'>, <class 'sqlglot.expressions.MD5Digest'>, <class 'sqlglot.expressions.Map'>, <class 'sqlglot.expressions.MapFromEntries'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <class 'sqlglot.expressions.MonthsBetween'>, <class 'sqlglot.expressions.NextValueFor'>, <class 'sqlglot.expressions.NumberToStr'>, <class 'sqlglot.expressions.Nvl2'>, <class 'sqlglot.expressions.OpenJSON'>, <class 'sqlglot.expressions.ParameterizedAgg'>, <class 'sqlglot.expressions.PercentileCont'>, <class 'sqlglot.expressions.PercentileDisc'>, <class 'sqlglot.expressions.Posexplode'>, <class 'sqlglot.expressions.Pow'>, <class 'sqlglot.expressions.Quantile'>, <class 'sqlglot.expressions.RangeN'>, <class 'sqlglot.expressions.ReadCSV'>, <class 'sqlglot.expressions.Reduce'>, <class 'sqlglot.expressions.RegexpExtract'>, <class 'sqlglot.expressions.RegexpILike'>, <class 'sqlglot.expressions.RegexpLike'>, <class 'sqlglot.expressions.RegexpReplace'>, <class 'sqlglot.expressions.RegexpSplit'>, <class 'sqlglot.expressions.Repeat'>, <class 'sqlglot.expressions.Right'>, <class 'sqlglot.expressions.Round'>, <class 'sqlglot.expressions.RowNumber'>, <class 'sqlglot.expressions.SHA'>, <class 'sqlglot.expressions.SHA2'>, <class 'sqlglot.expressions.SafeConcat'>, <class 'sqlglot.expressions.SafeDivide'>, <class 'sqlglot.expressions.SetAgg'>, <class 'sqlglot.expressions.SortArray'>, <class 'sqlglot.expressions.Split'>, <class 'sqlglot.expressions.Sqrt'>, <class 'sqlglot.expressions.StandardHash'>, <class 'sqlglot.expressions.StarMap'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.Transform'>, <class 'sqlglot.expressions.Trim'>, <class 'sqlglot.expressions.TryCast'>, <class 'sqlglot.expressions.TsOrDiToDi'>, <class 'sqlglot.expressions.TsOrDsAdd'>, <class 'sqlglot.expressions.TsOrDsToDate'>, <class 'sqlglot.expressions.TsOrDsToDateStr'>, <class 'sqlglot.expressions.Unhex'>, <class 'sqlglot.expressions.UnixToStr'>, <class 'sqlglot.expressions.UnixToTime'>, <class 'sqlglot.expressions.UnixToTimeStr'>, <class 'sqlglot.expressions.Upper'>, <class 'sqlglot.expressions.VarMap'>, <class 'sqlglot.expressions.Variance'>, <class 'sqlglot.expressions.VariancePop'>, <class 'sqlglot.expressions.Week'>, <class 'sqlglot.expressions.WeekOfYear'>, <class 'sqlglot.expressions.When'>, <class 'sqlglot.expressions.XMLTable'>, <class 'sqlglot.expressions.Xor'>, <class 'sqlglot.expressions.Year'>]
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.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) -> sqlglot.expressions.Expression:
4760def maybe_parse(
4761    sql_or_expression: ExpOrStr,
4762    *,
4763    into: t.Optional[IntoType] = None,
4764    dialect: DialectType = None,
4765    prefix: t.Optional[str] = None,
4766    copy: bool = False,
4767    **opts,
4768) -> Expression:
4769    """Gracefully handle a possible string or expression.
4770
4771    Example:
4772        >>> maybe_parse("1")
4773        (LITERAL this: 1, is_string: False)
4774        >>> maybe_parse(to_identifier("x"))
4775        (IDENTIFIER this: x, quoted: False)
4776
4777    Args:
4778        sql_or_expression: the SQL code string or an expression
4779        into: the SQLGlot Expression to parse into
4780        dialect: the dialect used to parse the input expressions (in the case that an
4781            input expression is a SQL string).
4782        prefix: a string to prefix the sql with before it gets parsed
4783            (automatically includes a space)
4784        copy: whether or not to copy the expression.
4785        **opts: other options to use to parse the input expressions (again, in the case
4786            that an input expression is a SQL string).
4787
4788    Returns:
4789        Expression: the parsed or given expression.
4790    """
4791    if isinstance(sql_or_expression, Expression):
4792        if copy:
4793            return sql_or_expression.copy()
4794        return sql_or_expression
4795
4796    if sql_or_expression is None:
4797        raise ParseError(f"SQL cannot be None")
4798
4799    import sqlglot
4800
4801    sql = str(sql_or_expression)
4802    if prefix:
4803        sql = f"{prefix} {sql}"
4804
4805    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 union( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Union:
4989def union(
4990    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4991) -> Union:
4992    """
4993    Initializes a syntax tree from one UNION expression.
4994
4995    Example:
4996        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4997        'SELECT * FROM foo UNION SELECT * FROM bla'
4998
4999    Args:
5000        left: the SQL code string corresponding to the left-hand side.
5001            If an `Expression` instance is passed, it will be used as-is.
5002        right: the SQL code string corresponding to the right-hand side.
5003            If an `Expression` instance is passed, it will be used as-is.
5004        distinct: set the DISTINCT flag if and only if this is true.
5005        dialect: the dialect used to parse the input expression.
5006        opts: other options to use to parse the input expressions.
5007
5008    Returns:
5009        The new Union instance.
5010    """
5011    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5012    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5013
5014    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, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Intersect:
5017def intersect(
5018    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5019) -> Intersect:
5020    """
5021    Initializes a syntax tree from one INTERSECT expression.
5022
5023    Example:
5024        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5025        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5026
5027    Args:
5028        left: the SQL code string corresponding to the left-hand side.
5029            If an `Expression` instance is passed, it will be used as-is.
5030        right: the SQL code string corresponding to the right-hand side.
5031            If an `Expression` instance is passed, it will be used as-is.
5032        distinct: set the DISTINCT flag if and only if this is true.
5033        dialect: the dialect used to parse the input expression.
5034        opts: other options to use to parse the input expressions.
5035
5036    Returns:
5037        The new Intersect instance.
5038    """
5039    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5040    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5041
5042    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, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Except:
5045def except_(
5046    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5047) -> Except:
5048    """
5049    Initializes a syntax tree from one EXCEPT expression.
5050
5051    Example:
5052        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5053        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5054
5055    Args:
5056        left: the SQL code string corresponding to the left-hand side.
5057            If an `Expression` instance is passed, it will be used as-is.
5058        right: the SQL code string corresponding to the right-hand side.
5059            If an `Expression` instance is passed, it will be used as-is.
5060        distinct: set the DISTINCT flag if and only if this is true.
5061        dialect: the dialect used to parse the input expression.
5062        opts: other options to use to parse the input expressions.
5063
5064    Returns:
5065        The new Except instance.
5066    """
5067    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5068    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5069
5070    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, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5073def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5074    """
5075    Initializes a syntax tree from one or multiple SELECT expressions.
5076
5077    Example:
5078        >>> select("col1", "col2").from_("tbl").sql()
5079        'SELECT col1, col2 FROM tbl'
5080
5081    Args:
5082        *expressions: the SQL code string to parse as the expressions of a
5083            SELECT statement. If an Expression instance is passed, this is used as-is.
5084        dialect: the dialect used to parse the input expressions (in the case that an
5085            input expression is a SQL string).
5086        **opts: other options to use to parse the input expressions (again, in the case
5087            that an input expression is a SQL string).
5088
5089    Returns:
5090        Select: the syntax tree for the SELECT statement.
5091    """
5092    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, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5095def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5096    """
5097    Initializes a syntax tree from a FROM expression.
5098
5099    Example:
5100        >>> from_("tbl").select("col1", "col2").sql()
5101        'SELECT col1, col2 FROM tbl'
5102
5103    Args:
5104        *expression: the SQL code string to parse as the FROM expressions of a
5105            SELECT statement. If an Expression instance is passed, this is used as-is.
5106        dialect: the dialect used to parse the input expression (in the case that the
5107            input expression is a SQL string).
5108        **opts: other options to use to parse the input expressions (again, in the case
5109            that the input expression is a SQL string).
5110
5111    Returns:
5112        Select: the syntax tree for the SELECT statement.
5113    """
5114    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 | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
5117def update(
5118    table: str | Table,
5119    properties: dict,
5120    where: t.Optional[ExpOrStr] = None,
5121    from_: t.Optional[ExpOrStr] = None,
5122    dialect: DialectType = None,
5123    **opts,
5124) -> Update:
5125    """
5126    Creates an update statement.
5127
5128    Example:
5129        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5130        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5131
5132    Args:
5133        *properties: dictionary of properties to set which are
5134            auto converted to sql objects eg None -> NULL
5135        where: sql conditional parsed into a WHERE statement
5136        from_: sql statement parsed into a FROM statement
5137        dialect: the dialect used to parse the input expressions.
5138        **opts: other options to use to parse the input expressions.
5139
5140    Returns:
5141        Update: the syntax tree for the UPDATE statement.
5142    """
5143    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5144    update_expr.set(
5145        "expressions",
5146        [
5147            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5148            for k, v in properties.items()
5149        ],
5150    )
5151    if from_:
5152        update_expr.set(
5153            "from",
5154            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5155        )
5156    if isinstance(where, Condition):
5157        where = Where(this=where)
5158    if where:
5159        update_expr.set(
5160            "where",
5161            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5162        )
5163    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, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
5166def delete(
5167    table: ExpOrStr,
5168    where: t.Optional[ExpOrStr] = None,
5169    returning: t.Optional[ExpOrStr] = None,
5170    dialect: DialectType = None,
5171    **opts,
5172) -> Delete:
5173    """
5174    Builds a delete statement.
5175
5176    Example:
5177        >>> delete("my_table", where="id > 1").sql()
5178        'DELETE FROM my_table WHERE id > 1'
5179
5180    Args:
5181        where: sql conditional parsed into a WHERE statement
5182        returning: sql conditional parsed into a RETURNING statement
5183        dialect: the dialect used to parse the input expressions.
5184        **opts: other options to use to parse the input expressions.
5185
5186    Returns:
5187        Delete: the syntax tree for the DELETE statement.
5188    """
5189    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5190    if where:
5191        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5192    if returning:
5193        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5194    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, sqlglot.expressions.Expression], into: Union[str, sqlglot.expressions.Expression], columns: Optional[Sequence[Union[str, sqlglot.expressions.Expression]]] = None, overwrite: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Insert:
5197def insert(
5198    expression: ExpOrStr,
5199    into: ExpOrStr,
5200    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5201    overwrite: t.Optional[bool] = None,
5202    dialect: DialectType = None,
5203    copy: bool = True,
5204    **opts,
5205) -> Insert:
5206    """
5207    Builds an INSERT statement.
5208
5209    Example:
5210        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5211        'INSERT INTO tbl VALUES (1, 2, 3)'
5212
5213    Args:
5214        expression: the sql string or expression of the INSERT statement
5215        into: the tbl to insert data to.
5216        columns: optionally the table's column names.
5217        overwrite: whether to INSERT OVERWRITE or not.
5218        dialect: the dialect used to parse the input expressions.
5219        copy: whether or not to copy the expression.
5220        **opts: other options to use to parse the input expressions.
5221
5222    Returns:
5223        Insert: the syntax tree for the INSERT statement.
5224    """
5225    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5226    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5227
5228    if columns:
5229        this = _apply_list_builder(
5230            *columns,
5231            instance=Schema(this=this),
5232            arg="expressions",
5233            into=Identifier,
5234            copy=False,
5235            dialect=dialect,
5236            **opts,
5237        )
5238
5239    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, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5242def condition(
5243    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5244) -> Condition:
5245    """
5246    Initialize a logical condition expression.
5247
5248    Example:
5249        >>> condition("x=1").sql()
5250        'x = 1'
5251
5252        This is helpful for composing larger logical syntax trees:
5253        >>> where = condition("x=1")
5254        >>> where = where.and_("y=1")
5255        >>> Select().from_("tbl").select("*").where(where).sql()
5256        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5257
5258    Args:
5259        *expression: the SQL code string to parse.
5260            If an Expression instance is passed, this is used as-is.
5261        dialect: the dialect used to parse the input expression (in the case that the
5262            input expression is a SQL string).
5263        copy: Whether or not to copy `expression` (only applies to expressions).
5264        **opts: other options to use to parse the input expressions (again, in the case
5265            that the input expression is a SQL string).
5266
5267    Returns:
5268        The new Condition instance
5269    """
5270    return maybe_parse(
5271        expression,
5272        into=Condition,
5273        dialect=dialect,
5274        copy=copy,
5275        **opts,
5276    )

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, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5279def and_(
5280    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5281) -> Condition:
5282    """
5283    Combine multiple conditions with an AND logical operator.
5284
5285    Example:
5286        >>> and_("x=1", and_("y=1", "z=1")).sql()
5287        'x = 1 AND (y = 1 AND z = 1)'
5288
5289    Args:
5290        *expressions: the SQL code strings to parse.
5291            If an Expression instance is passed, this is used as-is.
5292        dialect: the dialect used to parse the input expression.
5293        copy: whether or not to copy `expressions` (only applies to Expressions).
5294        **opts: other options to use to parse the input expressions.
5295
5296    Returns:
5297        And: the new condition
5298    """
5299    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, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5302def or_(
5303    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5304) -> Condition:
5305    """
5306    Combine multiple conditions with an OR logical operator.
5307
5308    Example:
5309        >>> or_("x=1", or_("y=1", "z=1")).sql()
5310        'x = 1 OR (y = 1 OR z = 1)'
5311
5312    Args:
5313        *expressions: the SQL code strings to parse.
5314            If an Expression instance is passed, this is used as-is.
5315        dialect: the dialect used to parse the input expression.
5316        copy: whether or not to copy `expressions` (only applies to Expressions).
5317        **opts: other options to use to parse the input expressions.
5318
5319    Returns:
5320        Or: the new condition
5321    """
5322    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, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Not:
5325def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5326    """
5327    Wrap a condition with a NOT operator.
5328
5329    Example:
5330        >>> not_("this_suit='black'").sql()
5331        "NOT this_suit = 'black'"
5332
5333    Args:
5334        expression: the SQL code string to parse.
5335            If an Expression instance is passed, this is used as-is.
5336        dialect: the dialect used to parse the input expression.
5337        copy: whether to copy the expression or not.
5338        **opts: other options to use to parse the input expressions.
5339
5340    Returns:
5341        The new condition.
5342    """
5343    this = condition(
5344        expression,
5345        dialect=dialect,
5346        copy=copy,
5347        **opts,
5348    )
5349    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, sqlglot.expressions.Expression], copy: bool = True) -> sqlglot.expressions.Paren:
5352def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5353    """
5354    Wrap an expression in parentheses.
5355
5356    Example:
5357        >>> paren("5 + 3").sql()
5358        '(5 + 3)'
5359
5360    Args:
5361        expression: the SQL code string to parse.
5362            If an Expression instance is passed, this is used as-is.
5363        copy: whether to copy the expression or not.
5364
5365    Returns:
5366        The wrapped expression.
5367    """
5368    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):
5386def to_identifier(name, quoted=None, copy=True):
5387    """Builds an identifier.
5388
5389    Args:
5390        name: The name to turn into an identifier.
5391        quoted: Whether or not force quote the identifier.
5392        copy: Whether or not to copy a passed in Identefier node.
5393
5394    Returns:
5395        The identifier ast node.
5396    """
5397
5398    if name is None:
5399        return None
5400
5401    if isinstance(name, Identifier):
5402        identifier = _maybe_copy(name, copy)
5403    elif isinstance(name, str):
5404        identifier = Identifier(
5405            this=name,
5406            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5407        )
5408    else:
5409        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5410    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 | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
5416def to_interval(interval: str | Literal) -> Interval:
5417    """Builds an interval expression from a string like '1 day' or '5 months'."""
5418    if isinstance(interval, Literal):
5419        if not interval.is_string:
5420            raise ValueError("Invalid interval string.")
5421
5422        interval = interval.this
5423
5424    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5425
5426    if not interval_parts:
5427        raise ValueError("Invalid interval string.")
5428
5429    return Interval(
5430        this=Literal.string(interval_parts.group(1)),
5431        unit=Var(this=interval_parts.group(2)),
5432    )

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

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Optional[sqlglot.expressions.Table]:
5445def to_table(
5446    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5447) -> t.Optional[Table]:
5448    """
5449    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5450    If a table is passed in then that table is returned.
5451
5452    Args:
5453        sql_path: a `[catalog].[schema].[table]` string.
5454        dialect: the source dialect according to which the table name will be parsed.
5455        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5456
5457    Returns:
5458        A table expression.
5459    """
5460    if sql_path is None or isinstance(sql_path, Table):
5461        return sql_path
5462    if not isinstance(sql_path, str):
5463        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5464
5465    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5466    if table:
5467        for k, v in kwargs.items():
5468            table.set(k, v)
5469
5470    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 | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
5473def to_column(sql_path: str | Column, **kwargs) -> Column:
5474    """
5475    Create a column from a `[table].[column]` sql path. Schema is optional.
5476
5477    If a column is passed in then that column is returned.
5478
5479    Args:
5480        sql_path: `[table].[column]` string
5481    Returns:
5482        Table: A column expression
5483    """
5484    if sql_path is None or isinstance(sql_path, Column):
5485        return sql_path
5486    if not isinstance(sql_path, str):
5487        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5488    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, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts):
5491def alias_(
5492    expression: ExpOrStr,
5493    alias: str | Identifier,
5494    table: bool | t.Sequence[str | Identifier] = False,
5495    quoted: t.Optional[bool] = None,
5496    dialect: DialectType = None,
5497    copy: bool = True,
5498    **opts,
5499):
5500    """Create an Alias expression.
5501
5502    Example:
5503        >>> alias_('foo', 'bar').sql()
5504        'foo AS bar'
5505
5506        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5507        '(SELECT 1, 2) AS bar(a, b)'
5508
5509    Args:
5510        expression: the SQL code strings to parse.
5511            If an Expression instance is passed, this is used as-is.
5512        alias: the alias name to use. If the name has
5513            special characters it is quoted.
5514        table: Whether or not to create a table alias, can also be a list of columns.
5515        quoted: whether or not to quote the alias
5516        dialect: the dialect used to parse the input expression.
5517        copy: Whether or not to copy the expression.
5518        **opts: other options to use to parse the input expressions.
5519
5520    Returns:
5521        Alias: the aliased expression
5522    """
5523    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5524    alias = to_identifier(alias, quoted=quoted)
5525
5526    if table:
5527        table_alias = TableAlias(this=alias)
5528        exp.set("alias", table_alias)
5529
5530        if not isinstance(table, bool):
5531            for column in table:
5532                table_alias.append("columns", to_identifier(column, quoted=quoted))
5533
5534        return exp
5535
5536    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5537    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5538    # for the complete Window expression.
5539    #
5540    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5541
5542    if "alias" in exp.arg_types and not isinstance(exp, Window):
5543        exp.set("alias", alias)
5544        return exp
5545    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, sqlglot.expressions.Expression], alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5548def subquery(
5549    expression: ExpOrStr,
5550    alias: t.Optional[Identifier | str] = None,
5551    dialect: DialectType = None,
5552    **opts,
5553) -> Select:
5554    """
5555    Build a subquery expression.
5556
5557    Example:
5558        >>> subquery('select x from tbl', 'bar').select('x').sql()
5559        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5560
5561    Args:
5562        expression: the SQL code strings to parse.
5563            If an Expression instance is passed, this is used as-is.
5564        alias: the alias name to use.
5565        dialect: the dialect used to parse the input expression.
5566        **opts: other options to use to parse the input expressions.
5567
5568    Returns:
5569        A new Select instance with the subquery expression included.
5570    """
5571
5572    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5573    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 | sqlglot.expressions.Identifier, table: Union[sqlglot.expressions.Identifier, str, NoneType] = None, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
5576def column(
5577    col: str | Identifier,
5578    table: t.Optional[str | Identifier] = None,
5579    db: t.Optional[str | Identifier] = None,
5580    catalog: t.Optional[str | Identifier] = None,
5581    quoted: t.Optional[bool] = None,
5582) -> Column:
5583    """
5584    Build a Column.
5585
5586    Args:
5587        col: Column name.
5588        table: Table name.
5589        db: Database name.
5590        catalog: Catalog name.
5591        quoted: Whether to force quotes on the column's identifiers.
5592
5593    Returns:
5594        The new Column instance.
5595    """
5596    return Column(
5597        this=to_identifier(col, quoted=quoted),
5598        table=to_identifier(table, quoted=quoted),
5599        db=to_identifier(db, quoted=quoted),
5600        catalog=to_identifier(catalog, quoted=quoted),
5601    )

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, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
5604def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5605    """Cast an expression to a data type.
5606
5607    Example:
5608        >>> cast('x + 1', 'int').sql()
5609        'CAST(x + 1 AS INT)'
5610
5611    Args:
5612        expression: The expression to cast.
5613        to: The datatype to cast to.
5614
5615    Returns:
5616        The new Cast instance.
5617    """
5618    expression = maybe_parse(expression, **opts)
5619    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

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

The new Cast instance.

def table_( table: sqlglot.expressions.Identifier | str, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None, alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None) -> sqlglot.expressions.Table:
5622def table_(
5623    table: Identifier | str,
5624    db: t.Optional[Identifier | str] = None,
5625    catalog: t.Optional[Identifier | str] = None,
5626    quoted: t.Optional[bool] = None,
5627    alias: t.Optional[Identifier | str] = None,
5628) -> Table:
5629    """Build a Table.
5630
5631    Args:
5632        table: Table name.
5633        db: Database name.
5634        catalog: Catalog name.
5635        quote: Whether to force quotes on the table's identifiers.
5636        alias: Table's alias.
5637
5638    Returns:
5639        The new Table instance.
5640    """
5641    return Table(
5642        this=to_identifier(table, quoted=quoted),
5643        db=to_identifier(db, quoted=quoted),
5644        catalog=to_identifier(catalog, quoted=quoted),
5645        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5646    )

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, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
5649def values(
5650    values: t.Iterable[t.Tuple[t.Any, ...]],
5651    alias: t.Optional[str] = None,
5652    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5653) -> Values:
5654    """Build VALUES statement.
5655
5656    Example:
5657        >>> values([(1, '2')]).sql()
5658        "VALUES (1, '2')"
5659
5660    Args:
5661        values: values statements that will be converted to SQL
5662        alias: optional alias
5663        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5664         If either are provided then an alias is also required.
5665
5666    Returns:
5667        Values: the Values expression object
5668    """
5669    if columns and not alias:
5670        raise ValueError("Alias is required when providing columns")
5671
5672    return Values(
5673        expressions=[convert(tup) for tup in values],
5674        alias=(
5675            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5676            if columns
5677            else (TableAlias(this=to_identifier(alias)) if alias else None)
5678        ),
5679    )

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, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
5682def var(name: t.Optional[ExpOrStr]) -> Var:
5683    """Build a SQL variable.
5684
5685    Example:
5686        >>> repr(var('x'))
5687        '(VAR this: x)'
5688
5689        >>> repr(var(column('x', table='y')))
5690        '(VAR this: x)'
5691
5692    Args:
5693        name: The name of the var or an expression who's name will become the var.
5694
5695    Returns:
5696        The new variable node.
5697    """
5698    if not name:
5699        raise ValueError("Cannot convert empty name into var.")
5700
5701    if isinstance(name, Expression):
5702        name = name.name
5703    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 | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
5706def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5707    """Build ALTER TABLE... RENAME... expression
5708
5709    Args:
5710        old_name: The old name of the table
5711        new_name: The new name of the table
5712
5713    Returns:
5714        Alter table expression
5715    """
5716    old_table = to_table(old_name)
5717    new_table = to_table(new_name)
5718    return AlterTable(
5719        this=old_table,
5720        actions=[
5721            RenameTable(this=new_table),
5722        ],
5723    )

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) -> sqlglot.expressions.Expression:
5726def convert(value: t.Any, copy: bool = False) -> Expression:
5727    """Convert a python value into an expression object.
5728
5729    Raises an error if a conversion is not possible.
5730
5731    Args:
5732        value: A python object.
5733        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5734
5735    Returns:
5736        Expression: the equivalent expression object.
5737    """
5738    if isinstance(value, Expression):
5739        return _maybe_copy(value, copy)
5740    if isinstance(value, str):
5741        return Literal.string(value)
5742    if isinstance(value, bool):
5743        return Boolean(this=value)
5744    if value is None or (isinstance(value, float) and math.isnan(value)):
5745        return NULL
5746    if isinstance(value, numbers.Number):
5747        return Literal.number(value)
5748    if isinstance(value, datetime.datetime):
5749        datetime_literal = Literal.string(
5750            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5751        )
5752        return TimeStrToTime(this=datetime_literal)
5753    if isinstance(value, datetime.date):
5754        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5755        return DateStrToDate(this=date_literal)
5756    if isinstance(value, tuple):
5757        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5758    if isinstance(value, list):
5759        return Array(expressions=[convert(v, copy=copy) for v in value])
5760    if isinstance(value, dict):
5761        return Map(
5762            keys=[convert(k, copy=copy) for k in value],
5763            values=[convert(v, copy=copy) for v in value.values()],
5764        )
5765    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: sqlglot.expressions.Expression, fun: Callable, *args, **kwargs) -> None:
5768def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5769    """
5770    Replace children of an expression with the result of a lambda fun(child) -> exp.
5771    """
5772    for k, v in expression.args.items():
5773        is_list_arg = type(v) is list
5774
5775        child_nodes = v if is_list_arg else [v]
5776        new_child_nodes = []
5777
5778        for cn in child_nodes:
5779            if isinstance(cn, Expression):
5780                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5781                    new_child_nodes.append(child_node)
5782                    child_node.parent = expression
5783                    child_node.arg_key = k
5784            else:
5785                new_child_nodes.append(cn)
5786
5787        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: sqlglot.expressions.Expression, exclude: str = '') -> Set[str]:
5790def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5791    """
5792    Return all table names referenced through columns in an expression.
5793
5794    Example:
5795        >>> import sqlglot
5796        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5797        ['a', 'c']
5798
5799    Args:
5800        expression: expression to find table names.
5801        exclude: a table name to exclude
5802
5803    Returns:
5804        A list of unique names.
5805    """
5806    return {
5807        table
5808        for table in (column.table for column in expression.find_all(Column))
5809        if table and table != exclude
5810    }

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: sqlglot.expressions.Table | str, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) -> str:
5813def table_name(table: Table | str, dialect: DialectType = None) -> str:
5814    """Get the full name of a table as a string.
5815
5816    Args:
5817        table: Table expression node or string.
5818        dialect: The dialect to generate the table name for.
5819
5820    Examples:
5821        >>> from sqlglot import exp, parse_one
5822        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5823        'a.b.c'
5824
5825    Returns:
5826        The table name.
5827    """
5828
5829    table = maybe_parse(table, into=Table)
5830
5831    if not table:
5832        raise ValueError(f"Cannot parse {table}")
5833
5834    return ".".join(
5835        part.sql(dialect=dialect, identify=True)
5836        if not SAFE_IDENTIFIER_RE.match(part.name)
5837        else part.name
5838        for part in table.parts
5839    )

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:
5842def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5843    """Replace all tables in expression according to the mapping.
5844
5845    Args:
5846        expression: expression node to be transformed and replaced.
5847        mapping: mapping of table names.
5848        copy: whether or not to copy the expression.
5849
5850    Examples:
5851        >>> from sqlglot import exp, parse_one
5852        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5853        'SELECT * FROM c'
5854
5855    Returns:
5856        The mapped expression.
5857    """
5858
5859    def _replace_tables(node: Expression) -> Expression:
5860        if isinstance(node, Table):
5861            new_name = mapping.get(table_name(node))
5862            if new_name:
5863                return to_table(
5864                    new_name,
5865                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5866                )
5867        return node
5868
5869    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: sqlglot.expressions.Expression, *args, **kwargs) -> sqlglot.expressions.Expression:
5872def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5873    """Replace placeholders in an expression.
5874
5875    Args:
5876        expression: expression node to be transformed and replaced.
5877        args: positional names that will substitute unnamed placeholders in the given order.
5878        kwargs: keyword arguments that will substitute named placeholders.
5879
5880    Examples:
5881        >>> from sqlglot import exp, parse_one
5882        >>> replace_placeholders(
5883        ...     parse_one("select * from :tbl where ? = ?"),
5884        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5885        ... ).sql()
5886        "SELECT * FROM foo WHERE str_col = 'b'"
5887
5888    Returns:
5889        The mapped expression.
5890    """
5891
5892    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5893        if isinstance(node, Placeholder):
5894            if node.name:
5895                new_name = kwargs.get(node.name)
5896                if new_name:
5897                    return convert(new_name)
5898            else:
5899                try:
5900                    return convert(next(args))
5901                except StopIteration:
5902                    pass
5903        return node
5904
5905    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: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy: bool = True) -> sqlglot.expressions.Expression:
5908def expand(
5909    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5910) -> Expression:
5911    """Transforms an expression by expanding all referenced sources into subqueries.
5912
5913    Examples:
5914        >>> from sqlglot import parse_one
5915        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5916        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5917
5918        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5919        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5920
5921    Args:
5922        expression: The expression to expand.
5923        sources: A dictionary of name to Subqueryables.
5924        copy: Whether or not to copy the expression during transformation. Defaults to True.
5925
5926    Returns:
5927        The transformed expression.
5928    """
5929
5930    def _expand(node: Expression):
5931        if isinstance(node, Table):
5932            name = table_name(node)
5933            source = sources.get(name)
5934            if source:
5935                subquery = source.subquery(node.alias or name)
5936                subquery.comments = [f"source: {name}"]
5937                return subquery.transform(_expand, copy=False)
5938        return node
5939
5940    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) -> sqlglot.expressions.Func:
5943def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5944    """
5945    Returns a Func expression.
5946
5947    Examples:
5948        >>> func("abs", 5).sql()
5949        'ABS(5)'
5950
5951        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5952        'CAST(5 AS DOUBLE)'
5953
5954    Args:
5955        name: the name of the function to build.
5956        args: the args used to instantiate the function of interest.
5957        dialect: the source dialect.
5958        kwargs: the kwargs used to instantiate the function of interest.
5959
5960    Note:
5961        The arguments `args` and `kwargs` are mutually exclusive.
5962
5963    Returns:
5964        An instance of the function of interest, or an anonymous function, if `name` doesn't
5965        correspond to an existing `sqlglot.expressions.Func` class.
5966    """
5967    if args and kwargs:
5968        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5969
5970    from sqlglot.dialects.dialect import Dialect
5971
5972    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5973    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5974
5975    parser = Dialect.get_or_raise(dialect)().parser()
5976    from_args_list = parser.FUNCTIONS.get(name.upper())
5977
5978    if from_args_list:
5979        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5980    else:
5981        kwargs = kwargs or {"expressions": converted}
5982        function = Anonymous(this=name, **kwargs)
5983
5984    for error_message in function.error_messages(converted):
5985        raise ValueError(error_message)
5986
5987    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 sqlglot.expressions.Func class.

def true() -> sqlglot.expressions.Boolean:
5990def true() -> Boolean:
5991    """
5992    Returns a true Boolean expression.
5993    """
5994    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5997def false() -> Boolean:
5998    """
5999    Returns a false Boolean expression.
6000    """
6001    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6004def null() -> Null:
6005    """
6006    Returns a Null expression.
6007    """
6008    return Null()

Returns a Null expression.

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