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

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1173class ColumnPosition(Expression):
1174    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1177class ColumnDef(Expression):
1178    arg_types = {
1179        "this": True,
1180        "kind": False,
1181        "constraints": False,
1182        "exists": False,
1183        "position": False,
1184    }
1185
1186    @property
1187    def constraints(self) -> t.List[ColumnConstraint]:
1188        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
key = 'columndef'
class AlterColumn(Expression):
1191class AlterColumn(Expression):
1192    arg_types = {
1193        "this": True,
1194        "dtype": False,
1195        "collate": False,
1196        "using": False,
1197        "default": False,
1198        "drop": False,
1199    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1202class RenameTable(Expression):
1203    pass
key = 'renametable'
class Comment(Expression):
1206class Comment(Expression):
1207    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):
1211class MergeTreeTTLAction(Expression):
1212    arg_types = {
1213        "this": True,
1214        "delete": False,
1215        "recompress": False,
1216        "to_disk": False,
1217        "to_volume": False,
1218    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1222class MergeTreeTTL(Expression):
1223    arg_types = {
1224        "expressions": True,
1225        "where": False,
1226        "group": False,
1227        "aggregates": False,
1228    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class IndexConstraintOption(Expression):
1232class IndexConstraintOption(Expression):
1233    arg_types = {
1234        "key_block_size": False,
1235        "using": False,
1236        "parser": False,
1237        "comment": False,
1238        "visible": False,
1239        "engine_attr": False,
1240        "secondary_engine_attr": False,
1241    }
arg_types = {'key_block_size': False, 'using': False, 'parser': False, 'comment': False, 'visible': False, 'engine_attr': False, 'secondary_engine_attr': False}
key = 'indexconstraintoption'
class ColumnConstraint(Expression):
1244class ColumnConstraint(Expression):
1245    arg_types = {"this": False, "kind": True}
1246
1247    @property
1248    def kind(self) -> ColumnConstraintKind:
1249        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1252class ColumnConstraintKind(Expression):
1253    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1256class AutoIncrementColumnConstraint(ColumnConstraintKind):
1257    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1260class CaseSpecificColumnConstraint(ColumnConstraintKind):
1261    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1264class CharacterSetColumnConstraint(ColumnConstraintKind):
1265    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1268class CheckColumnConstraint(ColumnConstraintKind):
1269    pass
key = 'checkcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1272class CollateColumnConstraint(ColumnConstraintKind):
1273    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1276class CommentColumnConstraint(ColumnConstraintKind):
1277    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1280class CompressColumnConstraint(ColumnConstraintKind):
1281    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1284class DateFormatColumnConstraint(ColumnConstraintKind):
1285    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1288class DefaultColumnConstraint(ColumnConstraintKind):
1289    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1292class EncodeColumnConstraint(ColumnConstraintKind):
1293    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1296class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1297    # this: True -> ALWAYS, this: False -> BY DEFAULT
1298    arg_types = {
1299        "this": False,
1300        "expression": False,
1301        "on_null": False,
1302        "start": False,
1303        "increment": False,
1304        "minvalue": False,
1305        "maxvalue": False,
1306        "cycle": False,
1307    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class IndexColumnConstraint(ColumnConstraintKind):
1311class IndexColumnConstraint(ColumnConstraintKind):
1312    arg_types = {"this": False, "schema": True, "kind": False, "type": False, "options": False}
arg_types = {'this': False, 'schema': True, 'kind': False, 'type': False, 'options': False}
key = 'indexcolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1315class InlineLengthColumnConstraint(ColumnConstraintKind):
1316    pass
key = 'inlinelengthcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1319class NotNullColumnConstraint(ColumnConstraintKind):
1320    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1324class OnUpdateColumnConstraint(ColumnConstraintKind):
1325    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1328class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1329    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1332class TitleColumnConstraint(ColumnConstraintKind):
1333    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1336class UniqueColumnConstraint(ColumnConstraintKind):
1337    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1340class UppercaseColumnConstraint(ColumnConstraintKind):
1341    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1344class PathColumnConstraint(ColumnConstraintKind):
1345    pass
key = 'pathcolumnconstraint'
class Constraint(Expression):
1348class Constraint(Expression):
1349    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1352class Delete(Expression):
1353    arg_types = {
1354        "with": False,
1355        "this": False,
1356        "using": False,
1357        "where": False,
1358        "returning": False,
1359        "limit": False,
1360        "tables": False,  # Multiple-Table Syntax (MySQL)
1361    }
1362
1363    def delete(
1364        self,
1365        table: ExpOrStr,
1366        dialect: DialectType = None,
1367        copy: bool = True,
1368        **opts,
1369    ) -> Delete:
1370        """
1371        Create a DELETE expression or replace the table on an existing DELETE expression.
1372
1373        Example:
1374            >>> delete("tbl").sql()
1375            'DELETE FROM tbl'
1376
1377        Args:
1378            table: the table from which to delete.
1379            dialect: the dialect used to parse the input expression.
1380            copy: if `False`, modify this expression instance in-place.
1381            opts: other options to use to parse the input expressions.
1382
1383        Returns:
1384            Delete: the modified expression.
1385        """
1386        return _apply_builder(
1387            expression=table,
1388            instance=self,
1389            arg="this",
1390            dialect=dialect,
1391            into=Table,
1392            copy=copy,
1393            **opts,
1394        )
1395
1396    def where(
1397        self,
1398        *expressions: t.Optional[ExpOrStr],
1399        append: bool = True,
1400        dialect: DialectType = None,
1401        copy: bool = True,
1402        **opts,
1403    ) -> Delete:
1404        """
1405        Append to or set the WHERE expressions.
1406
1407        Example:
1408            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1409            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1410
1411        Args:
1412            *expressions: the SQL code strings to parse.
1413                If an `Expression` instance is passed, it will be used as-is.
1414                Multiple expressions are combined with an AND operator.
1415            append: if `True`, AND the new expressions to any existing expression.
1416                Otherwise, this resets the expression.
1417            dialect: the dialect used to parse the input expressions.
1418            copy: if `False`, modify this expression instance in-place.
1419            opts: other options to use to parse the input expressions.
1420
1421        Returns:
1422            Delete: the modified expression.
1423        """
1424        return _apply_conjunction_builder(
1425            *expressions,
1426            instance=self,
1427            arg="where",
1428            append=append,
1429            into=Where,
1430            dialect=dialect,
1431            copy=copy,
1432            **opts,
1433        )
1434
1435    def returning(
1436        self,
1437        expression: ExpOrStr,
1438        dialect: DialectType = None,
1439        copy: bool = True,
1440        **opts,
1441    ) -> Delete:
1442        """
1443        Set the RETURNING expression. Not supported by all dialects.
1444
1445        Example:
1446            >>> delete("tbl").returning("*", dialect="postgres").sql()
1447            'DELETE FROM tbl RETURNING *'
1448
1449        Args:
1450            expression: the SQL code strings to parse.
1451                If an `Expression` instance is passed, it will be used as-is.
1452            dialect: the dialect used to parse the input expressions.
1453            copy: if `False`, modify this expression instance in-place.
1454            opts: other options to use to parse the input expressions.
1455
1456        Returns:
1457            Delete: the modified expression.
1458        """
1459        return _apply_builder(
1460            expression=expression,
1461            instance=self,
1462            arg="returning",
1463            prefix="RETURNING",
1464            dialect=dialect,
1465            copy=copy,
1466            into=Returning,
1467            **opts,
1468        )
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:
1363    def delete(
1364        self,
1365        table: ExpOrStr,
1366        dialect: DialectType = None,
1367        copy: bool = True,
1368        **opts,
1369    ) -> Delete:
1370        """
1371        Create a DELETE expression or replace the table on an existing DELETE expression.
1372
1373        Example:
1374            >>> delete("tbl").sql()
1375            'DELETE FROM tbl'
1376
1377        Args:
1378            table: the table from which to delete.
1379            dialect: the dialect used to parse the input expression.
1380            copy: if `False`, modify this expression instance in-place.
1381            opts: other options to use to parse the input expressions.
1382
1383        Returns:
1384            Delete: the modified expression.
1385        """
1386        return _apply_builder(
1387            expression=table,
1388            instance=self,
1389            arg="this",
1390            dialect=dialect,
1391            into=Table,
1392            copy=copy,
1393            **opts,
1394        )

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:
1396    def where(
1397        self,
1398        *expressions: t.Optional[ExpOrStr],
1399        append: bool = True,
1400        dialect: DialectType = None,
1401        copy: bool = True,
1402        **opts,
1403    ) -> Delete:
1404        """
1405        Append to or set the WHERE expressions.
1406
1407        Example:
1408            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1409            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1410
1411        Args:
1412            *expressions: the SQL code strings to parse.
1413                If an `Expression` instance is passed, it will be used as-is.
1414                Multiple expressions are combined with an AND operator.
1415            append: if `True`, AND the new expressions to any existing expression.
1416                Otherwise, this resets the expression.
1417            dialect: the dialect used to parse the input expressions.
1418            copy: if `False`, modify this expression instance in-place.
1419            opts: other options to use to parse the input expressions.
1420
1421        Returns:
1422            Delete: the modified expression.
1423        """
1424        return _apply_conjunction_builder(
1425            *expressions,
1426            instance=self,
1427            arg="where",
1428            append=append,
1429            into=Where,
1430            dialect=dialect,
1431            copy=copy,
1432            **opts,
1433        )

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:
1435    def returning(
1436        self,
1437        expression: ExpOrStr,
1438        dialect: DialectType = None,
1439        copy: bool = True,
1440        **opts,
1441    ) -> Delete:
1442        """
1443        Set the RETURNING expression. Not supported by all dialects.
1444
1445        Example:
1446            >>> delete("tbl").returning("*", dialect="postgres").sql()
1447            'DELETE FROM tbl RETURNING *'
1448
1449        Args:
1450            expression: the SQL code strings to parse.
1451                If an `Expression` instance is passed, it will be used as-is.
1452            dialect: the dialect used to parse the input expressions.
1453            copy: if `False`, modify this expression instance in-place.
1454            opts: other options to use to parse the input expressions.
1455
1456        Returns:
1457            Delete: the modified expression.
1458        """
1459        return _apply_builder(
1460            expression=expression,
1461            instance=self,
1462            arg="returning",
1463            prefix="RETURNING",
1464            dialect=dialect,
1465            copy=copy,
1466            into=Returning,
1467            **opts,
1468        )

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):
1471class Drop(Expression):
1472    arg_types = {
1473        "this": False,
1474        "kind": False,
1475        "exists": False,
1476        "temporary": False,
1477        "materialized": False,
1478        "cascade": False,
1479        "constraints": False,
1480        "purge": False,
1481    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1484class Filter(Expression):
1485    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1488class Check(Expression):
1489    pass
key = 'check'
class Directory(Expression):
1492class Directory(Expression):
1493    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1494    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1497class ForeignKey(Expression):
1498    arg_types = {
1499        "expressions": True,
1500        "reference": False,
1501        "delete": False,
1502        "update": False,
1503    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1506class PrimaryKey(Expression):
1507    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1512class Into(Expression):
1513    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1516class From(Expression):
1517    @property
1518    def name(self) -> str:
1519        return self.this.name
1520
1521    @property
1522    def alias_or_name(self) -> str:
1523        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1526class Having(Expression):
1527    pass
key = 'having'
class Hint(Expression):
1530class Hint(Expression):
1531    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1534class JoinHint(Expression):
1535    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1538class Identifier(Expression):
1539    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1540
1541    @property
1542    def quoted(self) -> bool:
1543        return bool(self.args.get("quoted"))
1544
1545    @property
1546    def hashable_args(self) -> t.Any:
1547        return (self.this, self.quoted)
1548
1549    @property
1550    def output_name(self) -> str:
1551        return self.name
arg_types = {'this': True, 'quoted': False, 'global': False, 'temporary': False}
quoted: bool
hashable_args: Any
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").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):
1554class Index(Expression):
1555    arg_types = {
1556        "this": False,
1557        "table": False,
1558        "using": False,
1559        "where": False,
1560        "columns": False,
1561        "unique": False,
1562        "primary": False,
1563        "amp": False,  # teradata
1564        "partition_by": False,  # teradata
1565    }
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):
1568class Insert(Expression):
1569    arg_types = {
1570        "with": False,
1571        "this": True,
1572        "expression": False,
1573        "conflict": False,
1574        "returning": False,
1575        "overwrite": False,
1576        "exists": False,
1577        "partition": False,
1578        "alternative": False,
1579        "where": False,
1580        "ignore": False,
1581    }
1582
1583    def with_(
1584        self,
1585        alias: ExpOrStr,
1586        as_: ExpOrStr,
1587        recursive: t.Optional[bool] = None,
1588        append: bool = True,
1589        dialect: DialectType = None,
1590        copy: bool = True,
1591        **opts,
1592    ) -> Insert:
1593        """
1594        Append to or set the common table expressions.
1595
1596        Example:
1597            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1598            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1599
1600        Args:
1601            alias: the SQL code string to parse as the table name.
1602                If an `Expression` instance is passed, this is used as-is.
1603            as_: the SQL code string to parse as the table expression.
1604                If an `Expression` instance is passed, it will be used as-is.
1605            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1606            append: if `True`, add to any existing expressions.
1607                Otherwise, this resets the expressions.
1608            dialect: the dialect used to parse the input expression.
1609            copy: if `False`, modify this expression instance in-place.
1610            opts: other options to use to parse the input expressions.
1611
1612        Returns:
1613            The modified expression.
1614        """
1615        return _apply_cte_builder(
1616            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1617        )
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:
1583    def with_(
1584        self,
1585        alias: ExpOrStr,
1586        as_: ExpOrStr,
1587        recursive: t.Optional[bool] = None,
1588        append: bool = True,
1589        dialect: DialectType = None,
1590        copy: bool = True,
1591        **opts,
1592    ) -> Insert:
1593        """
1594        Append to or set the common table expressions.
1595
1596        Example:
1597            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1598            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1599
1600        Args:
1601            alias: the SQL code string to parse as the table name.
1602                If an `Expression` instance is passed, this is used as-is.
1603            as_: the SQL code string to parse as the table expression.
1604                If an `Expression` instance is passed, it will be used as-is.
1605            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1606            append: if `True`, add to any existing expressions.
1607                Otherwise, this resets the expressions.
1608            dialect: the dialect used to parse the input expression.
1609            copy: if `False`, modify this expression instance in-place.
1610            opts: other options to use to parse the input expressions.
1611
1612        Returns:
1613            The modified expression.
1614        """
1615        return _apply_cte_builder(
1616            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1617        )

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):
1620class OnConflict(Expression):
1621    arg_types = {
1622        "duplicate": False,
1623        "expressions": False,
1624        "nothing": False,
1625        "key": False,
1626        "constraint": False,
1627    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1630class Returning(Expression):
1631    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1635class Introducer(Expression):
1636    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1640class National(Expression):
1641    pass
key = 'national'
class LoadData(Expression):
1644class LoadData(Expression):
1645    arg_types = {
1646        "this": True,
1647        "local": False,
1648        "overwrite": False,
1649        "inpath": True,
1650        "partition": False,
1651        "input_format": False,
1652        "serde": False,
1653    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1656class Partition(Expression):
1657    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1660class Fetch(Expression):
1661    arg_types = {
1662        "direction": False,
1663        "count": False,
1664        "percent": False,
1665        "with_ties": False,
1666    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1669class Group(Expression):
1670    arg_types = {
1671        "expressions": False,
1672        "grouping_sets": False,
1673        "cube": False,
1674        "rollup": False,
1675        "totals": False,
1676        "all": False,
1677    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1680class Lambda(Expression):
1681    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1684class Limit(Expression):
1685    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1688class Literal(Condition):
1689    arg_types = {"this": True, "is_string": True}
1690
1691    @property
1692    def hashable_args(self) -> t.Any:
1693        return (self.this, self.args.get("is_string"))
1694
1695    @classmethod
1696    def number(cls, number) -> Literal:
1697        return cls(this=str(number), is_string=False)
1698
1699    @classmethod
1700    def string(cls, string) -> Literal:
1701        return cls(this=str(string), is_string=True)
1702
1703    @property
1704    def output_name(self) -> str:
1705        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1695    @classmethod
1696    def number(cls, number) -> Literal:
1697        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1699    @classmethod
1700    def string(cls, string) -> Literal:
1701        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):
1708class Join(Expression):
1709    arg_types = {
1710        "this": True,
1711        "on": False,
1712        "side": False,
1713        "kind": False,
1714        "using": False,
1715        "method": False,
1716        "global": False,
1717        "hint": False,
1718    }
1719
1720    @property
1721    def method(self) -> str:
1722        return self.text("method").upper()
1723
1724    @property
1725    def kind(self) -> str:
1726        return self.text("kind").upper()
1727
1728    @property
1729    def side(self) -> str:
1730        return self.text("side").upper()
1731
1732    @property
1733    def hint(self) -> str:
1734        return self.text("hint").upper()
1735
1736    @property
1737    def alias_or_name(self) -> str:
1738        return self.this.alias_or_name
1739
1740    def on(
1741        self,
1742        *expressions: t.Optional[ExpOrStr],
1743        append: bool = True,
1744        dialect: DialectType = None,
1745        copy: bool = True,
1746        **opts,
1747    ) -> Join:
1748        """
1749        Append to or set the ON expressions.
1750
1751        Example:
1752            >>> import sqlglot
1753            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1754            'JOIN x ON y = 1'
1755
1756        Args:
1757            *expressions: the SQL code strings to parse.
1758                If an `Expression` instance is passed, it will be used as-is.
1759                Multiple expressions are combined with an AND operator.
1760            append: if `True`, AND the new expressions to any existing expression.
1761                Otherwise, this resets the expression.
1762            dialect: the dialect used to parse the input expressions.
1763            copy: if `False`, modify this expression instance in-place.
1764            opts: other options to use to parse the input expressions.
1765
1766        Returns:
1767            The modified Join expression.
1768        """
1769        join = _apply_conjunction_builder(
1770            *expressions,
1771            instance=self,
1772            arg="on",
1773            append=append,
1774            dialect=dialect,
1775            copy=copy,
1776            **opts,
1777        )
1778
1779        if join.kind == "CROSS":
1780            join.set("kind", None)
1781
1782        return join
1783
1784    def using(
1785        self,
1786        *expressions: t.Optional[ExpOrStr],
1787        append: bool = True,
1788        dialect: DialectType = None,
1789        copy: bool = True,
1790        **opts,
1791    ) -> Join:
1792        """
1793        Append to or set the USING expressions.
1794
1795        Example:
1796            >>> import sqlglot
1797            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1798            'JOIN x USING (foo, bla)'
1799
1800        Args:
1801            *expressions: the SQL code strings to parse.
1802                If an `Expression` instance is passed, it will be used as-is.
1803            append: if `True`, concatenate the new expressions to the existing "using" list.
1804                Otherwise, this resets the expression.
1805            dialect: the dialect used to parse the input expressions.
1806            copy: if `False`, modify this expression instance in-place.
1807            opts: other options to use to parse the input expressions.
1808
1809        Returns:
1810            The modified Join expression.
1811        """
1812        join = _apply_list_builder(
1813            *expressions,
1814            instance=self,
1815            arg="using",
1816            append=append,
1817            dialect=dialect,
1818            copy=copy,
1819            **opts,
1820        )
1821
1822        if join.kind == "CROSS":
1823            join.set("kind", None)
1824
1825        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:
1740    def on(
1741        self,
1742        *expressions: t.Optional[ExpOrStr],
1743        append: bool = True,
1744        dialect: DialectType = None,
1745        copy: bool = True,
1746        **opts,
1747    ) -> Join:
1748        """
1749        Append to or set the ON expressions.
1750
1751        Example:
1752            >>> import sqlglot
1753            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1754            'JOIN x ON y = 1'
1755
1756        Args:
1757            *expressions: the SQL code strings to parse.
1758                If an `Expression` instance is passed, it will be used as-is.
1759                Multiple expressions are combined with an AND operator.
1760            append: if `True`, AND the new expressions to any existing expression.
1761                Otherwise, this resets the expression.
1762            dialect: the dialect used to parse the input expressions.
1763            copy: if `False`, modify this expression instance in-place.
1764            opts: other options to use to parse the input expressions.
1765
1766        Returns:
1767            The modified Join expression.
1768        """
1769        join = _apply_conjunction_builder(
1770            *expressions,
1771            instance=self,
1772            arg="on",
1773            append=append,
1774            dialect=dialect,
1775            copy=copy,
1776            **opts,
1777        )
1778
1779        if join.kind == "CROSS":
1780            join.set("kind", None)
1781
1782        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:
1784    def using(
1785        self,
1786        *expressions: t.Optional[ExpOrStr],
1787        append: bool = True,
1788        dialect: DialectType = None,
1789        copy: bool = True,
1790        **opts,
1791    ) -> Join:
1792        """
1793        Append to or set the USING expressions.
1794
1795        Example:
1796            >>> import sqlglot
1797            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1798            'JOIN x USING (foo, bla)'
1799
1800        Args:
1801            *expressions: the SQL code strings to parse.
1802                If an `Expression` instance is passed, it will be used as-is.
1803            append: if `True`, concatenate the new expressions to the existing "using" list.
1804                Otherwise, this resets the expression.
1805            dialect: the dialect used to parse the input expressions.
1806            copy: if `False`, modify this expression instance in-place.
1807            opts: other options to use to parse the input expressions.
1808
1809        Returns:
1810            The modified Join expression.
1811        """
1812        join = _apply_list_builder(
1813            *expressions,
1814            instance=self,
1815            arg="using",
1816            append=append,
1817            dialect=dialect,
1818            copy=copy,
1819            **opts,
1820        )
1821
1822        if join.kind == "CROSS":
1823            join.set("kind", None)
1824
1825        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):
1828class Lateral(UDTF):
1829    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):
1832class MatchRecognize(Expression):
1833    arg_types = {
1834        "partition_by": False,
1835        "order": False,
1836        "measures": False,
1837        "rows": False,
1838        "after": False,
1839        "pattern": False,
1840        "define": False,
1841        "alias": False,
1842    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1847class Final(Expression):
1848    pass
key = 'final'
class Offset(Expression):
1851class Offset(Expression):
1852    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1855class Order(Expression):
1856    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1861class Cluster(Order):
1862    pass
key = 'cluster'
class Distribute(Order):
1865class Distribute(Order):
1866    pass
key = 'distribute'
class Sort(Order):
1869class Sort(Order):
1870    pass
key = 'sort'
class Ordered(Expression):
1873class Ordered(Expression):
1874    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1877class Property(Expression):
1878    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1881class AlgorithmProperty(Property):
1882    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1885class AutoIncrementProperty(Property):
1886    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1889class BlockCompressionProperty(Property):
1890    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):
1893class CharacterSetProperty(Property):
1894    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1897class ChecksumProperty(Property):
1898    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1901class CollateProperty(Property):
1902    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1905class CopyGrantsProperty(Property):
1906    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1909class DataBlocksizeProperty(Property):
1910    arg_types = {
1911        "size": False,
1912        "units": False,
1913        "minimum": False,
1914        "maximum": False,
1915        "default": False,
1916    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1919class DefinerProperty(Property):
1920    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1923class DistKeyProperty(Property):
1924    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1927class DistStyleProperty(Property):
1928    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1931class EngineProperty(Property):
1932    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
1935class HeapProperty(Property):
1936    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
1939class ToTableProperty(Property):
1940    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1943class ExecuteAsProperty(Property):
1944    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1947class ExternalProperty(Property):
1948    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1951class FallbackProperty(Property):
1952    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1955class FileFormatProperty(Property):
1956    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1959class FreespaceProperty(Property):
1960    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1963class InputOutputFormat(Expression):
1964    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1967class IsolatedLoadingProperty(Property):
1968    arg_types = {
1969        "no": True,
1970        "concurrent": True,
1971        "for_all": True,
1972        "for_insert": True,
1973        "for_none": True,
1974    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1977class JournalProperty(Property):
1978    arg_types = {
1979        "no": False,
1980        "dual": False,
1981        "before": False,
1982        "local": False,
1983        "after": False,
1984    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1987class LanguageProperty(Property):
1988    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1992class ClusteredByProperty(Property):
1993    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1996class DictProperty(Property):
1997    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2000class DictSubProperty(Property):
2001    pass
key = 'dictsubproperty'
class DictRange(Property):
2004class DictRange(Property):
2005    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2010class OnCluster(Property):
2011    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2014class LikeProperty(Property):
2015    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2018class LocationProperty(Property):
2019    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2022class LockingProperty(Property):
2023    arg_types = {
2024        "this": False,
2025        "kind": True,
2026        "for_or_in": True,
2027        "lock_type": True,
2028        "override": False,
2029    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2032class LogProperty(Property):
2033    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2036class MaterializedProperty(Property):
2037    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2040class MergeBlockRatioProperty(Property):
2041    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):
2044class NoPrimaryIndexProperty(Property):
2045    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
2048class OnCommitProperty(Property):
2049    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2052class PartitionedByProperty(Property):
2053    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2056class ReturnsProperty(Property):
2057    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2060class RowFormatProperty(Property):
2061    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2064class RowFormatDelimitedProperty(Property):
2065    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2066    arg_types = {
2067        "fields": False,
2068        "escaped": False,
2069        "collection_items": False,
2070        "map_keys": False,
2071        "lines": False,
2072        "null": False,
2073        "serde": False,
2074    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2077class RowFormatSerdeProperty(Property):
2078    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2082class QueryTransform(Expression):
2083    arg_types = {
2084        "expressions": True,
2085        "command_script": True,
2086        "schema": False,
2087        "row_format_before": False,
2088        "record_writer": False,
2089        "row_format_after": False,
2090        "record_reader": False,
2091    }
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):
2094class SchemaCommentProperty(Property):
2095    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2098class SerdeProperties(Property):
2099    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2102class SetProperty(Property):
2103    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2106class SettingsProperty(Property):
2107    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2110class SortKeyProperty(Property):
2111    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2114class SqlSecurityProperty(Property):
2115    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2118class StabilityProperty(Property):
2119    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2122class TemporaryProperty(Property):
2123    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2126class TransientProperty(Property):
2127    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2130class VolatileProperty(Property):
2131    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2134class WithDataProperty(Property):
2135    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2138class WithJournalTableProperty(Property):
2139    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2142class Properties(Expression):
2143    arg_types = {"expressions": True}
2144
2145    NAME_TO_PROPERTY = {
2146        "ALGORITHM": AlgorithmProperty,
2147        "AUTO_INCREMENT": AutoIncrementProperty,
2148        "CHARACTER SET": CharacterSetProperty,
2149        "CLUSTERED_BY": ClusteredByProperty,
2150        "COLLATE": CollateProperty,
2151        "COMMENT": SchemaCommentProperty,
2152        "DEFINER": DefinerProperty,
2153        "DISTKEY": DistKeyProperty,
2154        "DISTSTYLE": DistStyleProperty,
2155        "ENGINE": EngineProperty,
2156        "EXECUTE AS": ExecuteAsProperty,
2157        "FORMAT": FileFormatProperty,
2158        "LANGUAGE": LanguageProperty,
2159        "LOCATION": LocationProperty,
2160        "PARTITIONED_BY": PartitionedByProperty,
2161        "RETURNS": ReturnsProperty,
2162        "ROW_FORMAT": RowFormatProperty,
2163        "SORTKEY": SortKeyProperty,
2164    }
2165
2166    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2167
2168    # CREATE property locations
2169    # Form: schema specified
2170    #   create [POST_CREATE]
2171    #     table a [POST_NAME]
2172    #     (b int) [POST_SCHEMA]
2173    #     with ([POST_WITH])
2174    #     index (b) [POST_INDEX]
2175    #
2176    # Form: alias selection
2177    #   create [POST_CREATE]
2178    #     table a [POST_NAME]
2179    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2180    #     index (c) [POST_INDEX]
2181    class Location(AutoName):
2182        POST_CREATE = auto()
2183        POST_NAME = auto()
2184        POST_SCHEMA = auto()
2185        POST_WITH = auto()
2186        POST_ALIAS = auto()
2187        POST_EXPRESSION = auto()
2188        POST_INDEX = auto()
2189        UNSUPPORTED = auto()
2190
2191    @classmethod
2192    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2193        expressions = []
2194        for key, value in properties_dict.items():
2195            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2196            if property_cls:
2197                expressions.append(property_cls(this=convert(value)))
2198            else:
2199                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2200
2201        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:
2191    @classmethod
2192    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2193        expressions = []
2194        for key, value in properties_dict.items():
2195            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2196            if property_cls:
2197                expressions.append(property_cls(this=convert(value)))
2198            else:
2199                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2200
2201        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2181    class Location(AutoName):
2182        POST_CREATE = auto()
2183        POST_NAME = auto()
2184        POST_SCHEMA = auto()
2185        POST_WITH = auto()
2186        POST_ALIAS = auto()
2187        POST_EXPRESSION = auto()
2188        POST_INDEX = auto()
2189        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):
2204class Qualify(Expression):
2205    pass
key = 'qualify'
class Return(Expression):
2209class Return(Expression):
2210    pass
key = 'return'
class Reference(Expression):
2213class Reference(Expression):
2214    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2217class Tuple(Expression):
2218    arg_types = {"expressions": False}
2219
2220    def isin(
2221        self,
2222        *expressions: t.Any,
2223        query: t.Optional[ExpOrStr] = None,
2224        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2225        copy: bool = True,
2226        **opts,
2227    ) -> In:
2228        return In(
2229            this=maybe_copy(self, copy),
2230            expressions=[convert(e, copy=copy) for e in expressions],
2231            query=maybe_parse(query, copy=copy, **opts) if query else None,
2232            unnest=Unnest(
2233                expressions=[
2234                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2235                ]
2236            )
2237            if unnest
2238            else None,
2239        )
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:
2220    def isin(
2221        self,
2222        *expressions: t.Any,
2223        query: t.Optional[ExpOrStr] = None,
2224        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2225        copy: bool = True,
2226        **opts,
2227    ) -> In:
2228        return In(
2229            this=maybe_copy(self, copy),
2230            expressions=[convert(e, copy=copy) for e in expressions],
2231            query=maybe_parse(query, copy=copy, **opts) if query else None,
2232            unnest=Unnest(
2233                expressions=[
2234                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2235                ]
2236            )
2237            if unnest
2238            else None,
2239        )
key = 'tuple'
class Subqueryable(Unionable):
2242class Subqueryable(Unionable):
2243    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2244        """
2245        Convert this expression to an aliased expression that can be used as a Subquery.
2246
2247        Example:
2248            >>> subquery = Select().select("x").from_("tbl").subquery()
2249            >>> Select().select("x").from_(subquery).sql()
2250            'SELECT x FROM (SELECT x FROM tbl)'
2251
2252        Args:
2253            alias (str | Identifier): an optional alias for the subquery
2254            copy (bool): if `False`, modify this expression instance in-place.
2255
2256        Returns:
2257            Alias: the subquery
2258        """
2259        instance = maybe_copy(self, copy)
2260        if not isinstance(alias, Expression):
2261            alias = TableAlias(this=to_identifier(alias)) if alias else None
2262
2263        return Subquery(this=instance, alias=alias)
2264
2265    def limit(
2266        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2267    ) -> Select:
2268        raise NotImplementedError
2269
2270    @property
2271    def ctes(self):
2272        with_ = self.args.get("with")
2273        if not with_:
2274            return []
2275        return with_.expressions
2276
2277    @property
2278    def selects(self) -> t.List[Expression]:
2279        raise NotImplementedError("Subqueryable objects must implement `selects`")
2280
2281    @property
2282    def named_selects(self) -> t.List[str]:
2283        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2284
2285    def with_(
2286        self,
2287        alias: ExpOrStr,
2288        as_: ExpOrStr,
2289        recursive: t.Optional[bool] = None,
2290        append: bool = True,
2291        dialect: DialectType = None,
2292        copy: bool = True,
2293        **opts,
2294    ) -> Subqueryable:
2295        """
2296        Append to or set the common table expressions.
2297
2298        Example:
2299            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2300            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2301
2302        Args:
2303            alias: the SQL code string to parse as the table name.
2304                If an `Expression` instance is passed, this is used as-is.
2305            as_: the SQL code string to parse as the table expression.
2306                If an `Expression` instance is passed, it will be used as-is.
2307            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2308            append: if `True`, add to any existing expressions.
2309                Otherwise, this resets the expressions.
2310            dialect: the dialect used to parse the input expression.
2311            copy: if `False`, modify this expression instance in-place.
2312            opts: other options to use to parse the input expressions.
2313
2314        Returns:
2315            The modified expression.
2316        """
2317        return _apply_cte_builder(
2318            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2319        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2243    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2244        """
2245        Convert this expression to an aliased expression that can be used as a Subquery.
2246
2247        Example:
2248            >>> subquery = Select().select("x").from_("tbl").subquery()
2249            >>> Select().select("x").from_(subquery).sql()
2250            'SELECT x FROM (SELECT x FROM tbl)'
2251
2252        Args:
2253            alias (str | Identifier): an optional alias for the subquery
2254            copy (bool): if `False`, modify this expression instance in-place.
2255
2256        Returns:
2257            Alias: the subquery
2258        """
2259        instance = maybe_copy(self, copy)
2260        if not isinstance(alias, Expression):
2261            alias = TableAlias(this=to_identifier(alias)) if alias else None
2262
2263        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:
2265    def limit(
2266        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2267    ) -> Select:
2268        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:
2285    def with_(
2286        self,
2287        alias: ExpOrStr,
2288        as_: ExpOrStr,
2289        recursive: t.Optional[bool] = None,
2290        append: bool = True,
2291        dialect: DialectType = None,
2292        copy: bool = True,
2293        **opts,
2294    ) -> Subqueryable:
2295        """
2296        Append to or set the common table expressions.
2297
2298        Example:
2299            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2300            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2301
2302        Args:
2303            alias: the SQL code string to parse as the table name.
2304                If an `Expression` instance is passed, this is used as-is.
2305            as_: the SQL code string to parse as the table expression.
2306                If an `Expression` instance is passed, it will be used as-is.
2307            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2308            append: if `True`, add to any existing expressions.
2309                Otherwise, this resets the expressions.
2310            dialect: the dialect used to parse the input expression.
2311            copy: if `False`, modify this expression instance in-place.
2312            opts: other options to use to parse the input expressions.
2313
2314        Returns:
2315            The modified expression.
2316        """
2317        return _apply_cte_builder(
2318            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2319        )

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):
2346class WithTableHint(Expression):
2347    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2351class IndexTableHint(Expression):
2352    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2355class Table(Expression):
2356    arg_types = {
2357        "this": True,
2358        "alias": False,
2359        "db": False,
2360        "catalog": False,
2361        "laterals": False,
2362        "joins": False,
2363        "pivots": False,
2364        "hints": False,
2365        "system_time": False,
2366    }
2367
2368    @property
2369    def name(self) -> str:
2370        if isinstance(self.this, Func):
2371            return ""
2372        return self.this.name
2373
2374    @property
2375    def db(self) -> str:
2376        return self.text("db")
2377
2378    @property
2379    def catalog(self) -> str:
2380        return self.text("catalog")
2381
2382    @property
2383    def selects(self) -> t.List[Expression]:
2384        return []
2385
2386    @property
2387    def named_selects(self) -> t.List[str]:
2388        return []
2389
2390    @property
2391    def parts(self) -> t.List[Identifier]:
2392        """Return the parts of a table in order catalog, db, table."""
2393        parts: t.List[Identifier] = []
2394
2395        for arg in ("catalog", "db", "this"):
2396            part = self.args.get(arg)
2397
2398            if isinstance(part, Identifier):
2399                parts.append(part)
2400            elif isinstance(part, Dot):
2401                parts.extend(part.flatten())
2402
2403        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):
2407class SystemTime(Expression):
2408    arg_types = {
2409        "this": False,
2410        "expression": False,
2411        "kind": True,
2412    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2415class Union(Subqueryable):
2416    arg_types = {
2417        "with": False,
2418        "this": True,
2419        "expression": True,
2420        "distinct": False,
2421        **QUERY_MODIFIERS,
2422    }
2423
2424    def limit(
2425        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2426    ) -> Select:
2427        """
2428        Set the LIMIT expression.
2429
2430        Example:
2431            >>> select("1").union(select("1")).limit(1).sql()
2432            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2433
2434        Args:
2435            expression: the SQL code string to parse.
2436                This can also be an integer.
2437                If a `Limit` instance is passed, this is used as-is.
2438                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2439            dialect: the dialect used to parse the input expression.
2440            copy: if `False`, modify this expression instance in-place.
2441            opts: other options to use to parse the input expressions.
2442
2443        Returns:
2444            The limited subqueryable.
2445        """
2446        return (
2447            select("*")
2448            .from_(self.subquery(alias="_l_0", copy=copy))
2449            .limit(expression, dialect=dialect, copy=False, **opts)
2450        )
2451
2452    def select(
2453        self,
2454        *expressions: t.Optional[ExpOrStr],
2455        append: bool = True,
2456        dialect: DialectType = None,
2457        copy: bool = True,
2458        **opts,
2459    ) -> Union:
2460        """Append to or set the SELECT of the union recursively.
2461
2462        Example:
2463            >>> from sqlglot import parse_one
2464            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2465            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2466
2467        Args:
2468            *expressions: the SQL code strings to parse.
2469                If an `Expression` instance is passed, it will be used as-is.
2470            append: if `True`, add to any existing expressions.
2471                Otherwise, this resets the expressions.
2472            dialect: the dialect used to parse the input expressions.
2473            copy: if `False`, modify this expression instance in-place.
2474            opts: other options to use to parse the input expressions.
2475
2476        Returns:
2477            Union: the modified expression.
2478        """
2479        this = self.copy() if copy else self
2480        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2481        this.expression.unnest().select(
2482            *expressions, append=append, dialect=dialect, copy=False, **opts
2483        )
2484        return this
2485
2486    @property
2487    def named_selects(self) -> t.List[str]:
2488        return self.this.unnest().named_selects
2489
2490    @property
2491    def is_star(self) -> bool:
2492        return self.this.is_star or self.expression.is_star
2493
2494    @property
2495    def selects(self) -> t.List[Expression]:
2496        return self.this.unnest().selects
2497
2498    @property
2499    def left(self):
2500        return self.this
2501
2502    @property
2503    def right(self):
2504        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:
2424    def limit(
2425        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2426    ) -> Select:
2427        """
2428        Set the LIMIT expression.
2429
2430        Example:
2431            >>> select("1").union(select("1")).limit(1).sql()
2432            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2433
2434        Args:
2435            expression: the SQL code string to parse.
2436                This can also be an integer.
2437                If a `Limit` instance is passed, this is used as-is.
2438                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2439            dialect: the dialect used to parse the input expression.
2440            copy: if `False`, modify this expression instance in-place.
2441            opts: other options to use to parse the input expressions.
2442
2443        Returns:
2444            The limited subqueryable.
2445        """
2446        return (
2447            select("*")
2448            .from_(self.subquery(alias="_l_0", copy=copy))
2449            .limit(expression, dialect=dialect, copy=False, **opts)
2450        )

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

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:
2602    def group_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 GROUP BY expression.
2612
2613        Example:
2614            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2615            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
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 `Group`.
2621                If nothing is passed in then a group by is not applied to the expression
2622            append: if `True`, add to any existing expressions.
2623                Otherwise, this flattens all the `Group` 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        if not expressions:
2632            return self if not copy else self.copy()
2633
2634        return _apply_child_list_builder(
2635            *expressions,
2636            instance=self,
2637            arg="group",
2638            append=append,
2639            copy=copy,
2640            prefix="GROUP BY",
2641            into=Group,
2642            dialect=dialect,
2643            **opts,
2644        )

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

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

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

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:
2766    def limit(
2767        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2768    ) -> Select:
2769        """
2770        Set the LIMIT expression.
2771
2772        Example:
2773            >>> Select().from_("tbl").select("x").limit(10).sql()
2774            'SELECT x FROM tbl LIMIT 10'
2775
2776        Args:
2777            expression: the SQL code string to parse.
2778                This can also be an integer.
2779                If a `Limit` instance is passed, this is used as-is.
2780                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2781            dialect: the dialect used to parse the input expression.
2782            copy: if `False`, modify this expression instance in-place.
2783            opts: other options to use to parse the input expressions.
2784
2785        Returns:
2786            Select: the modified expression.
2787        """
2788        return _apply_builder(
2789            expression=expression,
2790            instance=self,
2791            arg="limit",
2792            into=Limit,
2793            prefix="LIMIT",
2794            dialect=dialect,
2795            copy=copy,
2796            **opts,
2797        )

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:
2799    def offset(
2800        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2801    ) -> Select:
2802        """
2803        Set the OFFSET expression.
2804
2805        Example:
2806            >>> Select().from_("tbl").select("x").offset(10).sql()
2807            'SELECT x FROM tbl OFFSET 10'
2808
2809        Args:
2810            expression: the SQL code string to parse.
2811                This can also be an integer.
2812                If a `Offset` instance is passed, this is used as-is.
2813                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2814            dialect: the dialect used to parse the input expression.
2815            copy: if `False`, modify this expression instance in-place.
2816            opts: other options to use to parse the input expressions.
2817
2818        Returns:
2819            The modified Select expression.
2820        """
2821        return _apply_builder(
2822            expression=expression,
2823            instance=self,
2824            arg="offset",
2825            into=Offset,
2826            prefix="OFFSET",
2827            dialect=dialect,
2828            copy=copy,
2829            **opts,
2830        )

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:
2832    def select(
2833        self,
2834        *expressions: t.Optional[ExpOrStr],
2835        append: bool = True,
2836        dialect: DialectType = None,
2837        copy: bool = True,
2838        **opts,
2839    ) -> Select:
2840        """
2841        Append to or set the SELECT expressions.
2842
2843        Example:
2844            >>> Select().select("x", "y").sql()
2845            'SELECT x, y'
2846
2847        Args:
2848            *expressions: the SQL code strings to parse.
2849                If an `Expression` instance is passed, it will be used as-is.
2850            append: if `True`, add to any existing expressions.
2851                Otherwise, this resets the expressions.
2852            dialect: the dialect used to parse the input expressions.
2853            copy: if `False`, modify this expression instance in-place.
2854            opts: other options to use to parse the input expressions.
2855
2856        Returns:
2857            The modified Select expression.
2858        """
2859        return _apply_list_builder(
2860            *expressions,
2861            instance=self,
2862            arg="expressions",
2863            append=append,
2864            dialect=dialect,
2865            copy=copy,
2866            **opts,
2867        )

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:
2869    def lateral(
2870        self,
2871        *expressions: t.Optional[ExpOrStr],
2872        append: bool = True,
2873        dialect: DialectType = None,
2874        copy: bool = True,
2875        **opts,
2876    ) -> Select:
2877        """
2878        Append to or set the LATERAL expressions.
2879
2880        Example:
2881            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2882            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2883
2884        Args:
2885            *expressions: the SQL code strings to parse.
2886                If an `Expression` instance is passed, it will be used as-is.
2887            append: if `True`, add to any existing expressions.
2888                Otherwise, this resets the expressions.
2889            dialect: the dialect used to parse the input expressions.
2890            copy: if `False`, modify this expression instance in-place.
2891            opts: other options to use to parse the input expressions.
2892
2893        Returns:
2894            The modified Select expression.
2895        """
2896        return _apply_list_builder(
2897            *expressions,
2898            instance=self,
2899            arg="laterals",
2900            append=append,
2901            into=Lateral,
2902            prefix="LATERAL VIEW",
2903            dialect=dialect,
2904            copy=copy,
2905            **opts,
2906        )

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, Collection[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:
2908    def join(
2909        self,
2910        expression: ExpOrStr,
2911        on: t.Optional[ExpOrStr] = None,
2912        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
2913        append: bool = True,
2914        join_type: t.Optional[str] = None,
2915        join_alias: t.Optional[Identifier | str] = None,
2916        dialect: DialectType = None,
2917        copy: bool = True,
2918        **opts,
2919    ) -> Select:
2920        """
2921        Append to or set the JOIN expressions.
2922
2923        Example:
2924            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2925            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2926
2927            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2928            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2929
2930            Use `join_type` to change the type of join:
2931
2932            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2933            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2934
2935        Args:
2936            expression: the SQL code string to parse.
2937                If an `Expression` instance is passed, it will be used as-is.
2938            on: optionally specify the join "on" criteria as a SQL string.
2939                If an `Expression` instance is passed, it will be used as-is.
2940            using: optionally specify the join "using" criteria as a SQL string.
2941                If an `Expression` instance is passed, it will be used as-is.
2942            append: if `True`, add to any existing expressions.
2943                Otherwise, this resets the expressions.
2944            join_type: if set, alter the parsed join type.
2945            join_alias: an optional alias for the joined source.
2946            dialect: the dialect used to parse the input expressions.
2947            copy: if `False`, modify this expression instance in-place.
2948            opts: other options to use to parse the input expressions.
2949
2950        Returns:
2951            Select: the modified expression.
2952        """
2953        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2954
2955        try:
2956            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2957        except ParseError:
2958            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2959
2960        join = expression if isinstance(expression, Join) else Join(this=expression)
2961
2962        if isinstance(join.this, Select):
2963            join.this.replace(join.this.subquery())
2964
2965        if join_type:
2966            method: t.Optional[Token]
2967            side: t.Optional[Token]
2968            kind: t.Optional[Token]
2969
2970            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2971
2972            if method:
2973                join.set("method", method.text)
2974            if side:
2975                join.set("side", side.text)
2976            if kind:
2977                join.set("kind", kind.text)
2978
2979        if on:
2980            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2981            join.set("on", on)
2982
2983        if using:
2984            join = _apply_list_builder(
2985                *ensure_list(using),
2986                instance=join,
2987                arg="using",
2988                append=append,
2989                copy=copy,
2990                into=Identifier,
2991                **opts,
2992            )
2993
2994        if join_alias:
2995            join.set("this", alias_(join.this, join_alias, table=True))
2996
2997        return _apply_list_builder(
2998            join,
2999            instance=self,
3000            arg="joins",
3001            append=append,
3002            copy=copy,
3003            **opts,
3004        )

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:
3006    def where(
3007        self,
3008        *expressions: t.Optional[ExpOrStr],
3009        append: bool = True,
3010        dialect: DialectType = None,
3011        copy: bool = True,
3012        **opts,
3013    ) -> Select:
3014        """
3015        Append to or set the WHERE expressions.
3016
3017        Example:
3018            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3019            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3020
3021        Args:
3022            *expressions: the SQL code strings to parse.
3023                If an `Expression` instance is passed, it will be used as-is.
3024                Multiple expressions are combined with an AND operator.
3025            append: if `True`, AND the new expressions to any existing expression.
3026                Otherwise, this resets the expression.
3027            dialect: the dialect used to parse the input expressions.
3028            copy: if `False`, modify this expression instance in-place.
3029            opts: other options to use to parse the input expressions.
3030
3031        Returns:
3032            Select: the modified expression.
3033        """
3034        return _apply_conjunction_builder(
3035            *expressions,
3036            instance=self,
3037            arg="where",
3038            append=append,
3039            into=Where,
3040            dialect=dialect,
3041            copy=copy,
3042            **opts,
3043        )

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:
3045    def having(
3046        self,
3047        *expressions: t.Optional[ExpOrStr],
3048        append: bool = True,
3049        dialect: DialectType = None,
3050        copy: bool = True,
3051        **opts,
3052    ) -> Select:
3053        """
3054        Append to or set the HAVING expressions.
3055
3056        Example:
3057            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3058            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3059
3060        Args:
3061            *expressions: the SQL code strings to parse.
3062                If an `Expression` instance is passed, it will be used as-is.
3063                Multiple expressions are combined with an AND operator.
3064            append: if `True`, AND the new expressions to any existing expression.
3065                Otherwise, this resets the expression.
3066            dialect: the dialect used to parse the input expressions.
3067            copy: if `False`, modify this expression instance in-place.
3068            opts: other options to use to parse the input expressions.
3069
3070        Returns:
3071            The modified Select expression.
3072        """
3073        return _apply_conjunction_builder(
3074            *expressions,
3075            instance=self,
3076            arg="having",
3077            append=append,
3078            into=Having,
3079            dialect=dialect,
3080            copy=copy,
3081            **opts,
3082        )

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:
3084    def window(
3085        self,
3086        *expressions: t.Optional[ExpOrStr],
3087        append: bool = True,
3088        dialect: DialectType = None,
3089        copy: bool = True,
3090        **opts,
3091    ) -> Select:
3092        return _apply_list_builder(
3093            *expressions,
3094            instance=self,
3095            arg="windows",
3096            append=append,
3097            into=Window,
3098            dialect=dialect,
3099            copy=copy,
3100            **opts,
3101        )
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:
3103    def qualify(
3104        self,
3105        *expressions: t.Optional[ExpOrStr],
3106        append: bool = True,
3107        dialect: DialectType = None,
3108        copy: bool = True,
3109        **opts,
3110    ) -> Select:
3111        return _apply_conjunction_builder(
3112            *expressions,
3113            instance=self,
3114            arg="qualify",
3115            append=append,
3116            into=Qualify,
3117            dialect=dialect,
3118            copy=copy,
3119            **opts,
3120        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3122    def distinct(
3123        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3124    ) -> Select:
3125        """
3126        Set the OFFSET expression.
3127
3128        Example:
3129            >>> Select().from_("tbl").select("x").distinct().sql()
3130            'SELECT DISTINCT x FROM tbl'
3131
3132        Args:
3133            ons: the expressions to distinct on
3134            distinct: whether the Select should be distinct
3135            copy: if `False`, modify this expression instance in-place.
3136
3137        Returns:
3138            Select: the modified expression.
3139        """
3140        instance = maybe_copy(self, copy)
3141        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3142        instance.set("distinct", Distinct(on=on) if distinct else None)
3143        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:
3145    def ctas(
3146        self,
3147        table: ExpOrStr,
3148        properties: t.Optional[t.Dict] = None,
3149        dialect: DialectType = None,
3150        copy: bool = True,
3151        **opts,
3152    ) -> Create:
3153        """
3154        Convert this expression to a CREATE TABLE AS statement.
3155
3156        Example:
3157            >>> Select().select("*").from_("tbl").ctas("x").sql()
3158            'CREATE TABLE x AS SELECT * FROM tbl'
3159
3160        Args:
3161            table: the SQL code string to parse as the table name.
3162                If another `Expression` instance is passed, it will be used as-is.
3163            properties: an optional mapping of table properties
3164            dialect: the dialect used to parse the input table.
3165            copy: if `False`, modify this expression instance in-place.
3166            opts: other options to use to parse the input table.
3167
3168        Returns:
3169            The new Create expression.
3170        """
3171        instance = maybe_copy(self, copy)
3172        table_expression = maybe_parse(
3173            table,
3174            into=Table,
3175            dialect=dialect,
3176            **opts,
3177        )
3178        properties_expression = None
3179        if properties:
3180            properties_expression = Properties.from_dict(properties)
3181
3182        return Create(
3183            this=table_expression,
3184            kind="table",
3185            expression=instance,
3186            properties=properties_expression,
3187        )

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:
3189    def lock(self, update: bool = True, copy: bool = True) -> Select:
3190        """
3191        Set the locking read mode for this expression.
3192
3193        Examples:
3194            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3195            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3196
3197            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3198            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3199
3200        Args:
3201            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3202            copy: if `False`, modify this expression instance in-place.
3203
3204        Returns:
3205            The modified expression.
3206        """
3207        inst = maybe_copy(self, copy)
3208        inst.set("locks", [Lock(update=update)])
3209
3210        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:
3212    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3213        """
3214        Set hints for this expression.
3215
3216        Examples:
3217            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3218            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3219
3220        Args:
3221            hints: The SQL code strings to parse as the hints.
3222                If an `Expression` instance is passed, it will be used as-is.
3223            dialect: The dialect used to parse the hints.
3224            copy: If `False`, modify this expression instance in-place.
3225
3226        Returns:
3227            The modified expression.
3228        """
3229        inst = maybe_copy(self, copy)
3230        inst.set(
3231            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3232        )
3233
3234        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):
3249class Subquery(DerivedTable, Unionable):
3250    arg_types = {
3251        "this": True,
3252        "alias": False,
3253        "with": False,
3254        **QUERY_MODIFIERS,
3255    }
3256
3257    def unnest(self):
3258        """
3259        Returns the first non subquery.
3260        """
3261        expression = self
3262        while isinstance(expression, Subquery):
3263            expression = expression.this
3264        return expression
3265
3266    @property
3267    def is_star(self) -> bool:
3268        return self.this.is_star
3269
3270    @property
3271    def output_name(self) -> str:
3272        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):
3257    def unnest(self):
3258        """
3259        Returns the first non subquery.
3260        """
3261        expression = self
3262        while isinstance(expression, Subquery):
3263            expression = expression.this
3264        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):
3275class TableSample(Expression):
3276    arg_types = {
3277        "this": False,
3278        "method": False,
3279        "bucket_numerator": False,
3280        "bucket_denominator": False,
3281        "bucket_field": False,
3282        "percent": False,
3283        "rows": False,
3284        "size": False,
3285        "seed": False,
3286        "kind": False,
3287    }
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):
3290class Tag(Expression):
3291    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3292
3293    arg_types = {
3294        "this": False,
3295        "prefix": False,
3296        "postfix": False,
3297    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3302class Pivot(Expression):
3303    arg_types = {
3304        "this": False,
3305        "alias": False,
3306        "expressions": True,
3307        "field": False,
3308        "unpivot": False,
3309        "using": False,
3310        "group": False,
3311        "columns": False,
3312    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3315class Window(Expression):
3316    arg_types = {
3317        "this": True,
3318        "partition_by": False,
3319        "order": False,
3320        "spec": False,
3321        "alias": False,
3322        "over": False,
3323        "first": False,
3324    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3327class WindowSpec(Expression):
3328    arg_types = {
3329        "kind": False,
3330        "start": False,
3331        "start_side": False,
3332        "end": False,
3333        "end_side": False,
3334    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3337class Where(Expression):
3338    pass
key = 'where'
class Star(Expression):
3341class Star(Expression):
3342    arg_types = {"except": False, "replace": False}
3343
3344    @property
3345    def name(self) -> str:
3346        return "*"
3347
3348    @property
3349    def output_name(self) -> str:
3350        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):
3353class Parameter(Condition):
3354    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3357class SessionParameter(Condition):
3358    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3361class Placeholder(Condition):
3362    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3365class Null(Condition):
3366    arg_types: t.Dict[str, t.Any] = {}
3367
3368    @property
3369    def name(self) -> str:
3370        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3373class Boolean(Condition):
3374    pass
key = 'boolean'
class DataTypeSize(Expression):
3377class DataTypeSize(Expression):
3378    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3381class DataType(Expression):
3382    arg_types = {
3383        "this": True,
3384        "expressions": False,
3385        "nested": False,
3386        "values": False,
3387        "prefix": False,
3388    }
3389
3390    class Type(AutoName):
3391        ARRAY = auto()
3392        BIGDECIMAL = auto()
3393        BIGINT = auto()
3394        BIGSERIAL = auto()
3395        BINARY = auto()
3396        BIT = auto()
3397        BOOLEAN = auto()
3398        CHAR = auto()
3399        DATE = auto()
3400        DATETIME = auto()
3401        DATETIME64 = auto()
3402        ENUM = auto()
3403        INT4RANGE = auto()
3404        INT4MULTIRANGE = auto()
3405        INT8RANGE = auto()
3406        INT8MULTIRANGE = auto()
3407        NUMRANGE = auto()
3408        NUMMULTIRANGE = auto()
3409        TSRANGE = auto()
3410        TSMULTIRANGE = auto()
3411        TSTZRANGE = auto()
3412        TSTZMULTIRANGE = auto()
3413        DATERANGE = auto()
3414        DATEMULTIRANGE = auto()
3415        DECIMAL = auto()
3416        DOUBLE = auto()
3417        FLOAT = auto()
3418        GEOGRAPHY = auto()
3419        GEOMETRY = auto()
3420        HLLSKETCH = auto()
3421        HSTORE = auto()
3422        IMAGE = auto()
3423        INET = auto()
3424        IPADDRESS = auto()
3425        IPPREFIX = auto()
3426        INT = auto()
3427        INT128 = auto()
3428        INT256 = auto()
3429        INTERVAL = auto()
3430        JSON = auto()
3431        JSONB = auto()
3432        LONGBLOB = auto()
3433        LONGTEXT = auto()
3434        MAP = auto()
3435        MEDIUMBLOB = auto()
3436        MEDIUMTEXT = auto()
3437        MONEY = auto()
3438        NCHAR = auto()
3439        NULL = auto()
3440        NULLABLE = auto()
3441        NVARCHAR = auto()
3442        OBJECT = auto()
3443        ROWVERSION = auto()
3444        SERIAL = auto()
3445        SET = auto()
3446        SMALLINT = auto()
3447        SMALLMONEY = auto()
3448        SMALLSERIAL = auto()
3449        STRUCT = auto()
3450        SUPER = auto()
3451        TEXT = auto()
3452        TIME = auto()
3453        TIMESTAMP = auto()
3454        TIMESTAMPTZ = auto()
3455        TIMESTAMPLTZ = auto()
3456        TINYINT = auto()
3457        UBIGINT = auto()
3458        UINT = auto()
3459        USMALLINT = auto()
3460        UTINYINT = auto()
3461        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3462        UINT128 = auto()
3463        UINT256 = auto()
3464        UNIQUEIDENTIFIER = auto()
3465        USERDEFINED = "USER-DEFINED"
3466        UUID = auto()
3467        VARBINARY = auto()
3468        VARCHAR = auto()
3469        VARIANT = auto()
3470        XML = auto()
3471
3472    TEXT_TYPES = {
3473        Type.CHAR,
3474        Type.NCHAR,
3475        Type.VARCHAR,
3476        Type.NVARCHAR,
3477        Type.TEXT,
3478    }
3479
3480    INTEGER_TYPES = {
3481        Type.INT,
3482        Type.TINYINT,
3483        Type.SMALLINT,
3484        Type.BIGINT,
3485        Type.INT128,
3486        Type.INT256,
3487    }
3488
3489    FLOAT_TYPES = {
3490        Type.FLOAT,
3491        Type.DOUBLE,
3492    }
3493
3494    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3495
3496    TEMPORAL_TYPES = {
3497        Type.TIME,
3498        Type.TIMESTAMP,
3499        Type.TIMESTAMPTZ,
3500        Type.TIMESTAMPLTZ,
3501        Type.DATE,
3502        Type.DATETIME,
3503        Type.DATETIME64,
3504    }
3505
3506    META_TYPES = {"UNKNOWN", "NULL"}
3507
3508    @classmethod
3509    def build(
3510        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3511    ) -> DataType:
3512        from sqlglot import parse_one
3513
3514        if isinstance(dtype, str):
3515            upper = dtype.upper()
3516            if upper in DataType.META_TYPES:
3517                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3518            else:
3519                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3520
3521            if data_type_exp is None:
3522                raise ValueError(f"Unparsable data type value: {dtype}")
3523        elif isinstance(dtype, DataType.Type):
3524            data_type_exp = DataType(this=dtype)
3525        elif isinstance(dtype, DataType):
3526            return dtype
3527        else:
3528            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3529
3530        return DataType(**{**data_type_exp.args, **kwargs})
3531
3532    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3533        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.TEXT: 'TEXT'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>}
INTEGER_TYPES = {<Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT256: 'INT256'>, <Type.INT128: 'INT128'>, <Type.BIGINT: 'BIGINT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.TINYINT: 'TINYINT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.INT: 'INT'>, <Type.INT128: 'INT128'>, <Type.SMALLINT: 'SMALLINT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT256: 'INT256'>}
TEMPORAL_TYPES = {<Type.DATE: 'DATE'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.TIME: 'TIME'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATETIME: 'DATETIME'>, <Type.DATETIME64: 'DATETIME64'>}
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:
3508    @classmethod
3509    def build(
3510        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3511    ) -> DataType:
3512        from sqlglot import parse_one
3513
3514        if isinstance(dtype, str):
3515            upper = dtype.upper()
3516            if upper in DataType.META_TYPES:
3517                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3518            else:
3519                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3520
3521            if data_type_exp is None:
3522                raise ValueError(f"Unparsable data type value: {dtype}")
3523        elif isinstance(dtype, DataType.Type):
3524            data_type_exp = DataType(this=dtype)
3525        elif isinstance(dtype, DataType):
3526            return dtype
3527        else:
3528            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3529
3530        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3532    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3533        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3390    class Type(AutoName):
3391        ARRAY = auto()
3392        BIGDECIMAL = auto()
3393        BIGINT = auto()
3394        BIGSERIAL = auto()
3395        BINARY = auto()
3396        BIT = auto()
3397        BOOLEAN = auto()
3398        CHAR = auto()
3399        DATE = auto()
3400        DATETIME = auto()
3401        DATETIME64 = auto()
3402        ENUM = auto()
3403        INT4RANGE = auto()
3404        INT4MULTIRANGE = auto()
3405        INT8RANGE = auto()
3406        INT8MULTIRANGE = auto()
3407        NUMRANGE = auto()
3408        NUMMULTIRANGE = auto()
3409        TSRANGE = auto()
3410        TSMULTIRANGE = auto()
3411        TSTZRANGE = auto()
3412        TSTZMULTIRANGE = auto()
3413        DATERANGE = auto()
3414        DATEMULTIRANGE = auto()
3415        DECIMAL = auto()
3416        DOUBLE = auto()
3417        FLOAT = auto()
3418        GEOGRAPHY = auto()
3419        GEOMETRY = auto()
3420        HLLSKETCH = auto()
3421        HSTORE = auto()
3422        IMAGE = auto()
3423        INET = auto()
3424        IPADDRESS = auto()
3425        IPPREFIX = auto()
3426        INT = auto()
3427        INT128 = auto()
3428        INT256 = auto()
3429        INTERVAL = auto()
3430        JSON = auto()
3431        JSONB = auto()
3432        LONGBLOB = auto()
3433        LONGTEXT = auto()
3434        MAP = auto()
3435        MEDIUMBLOB = auto()
3436        MEDIUMTEXT = auto()
3437        MONEY = auto()
3438        NCHAR = auto()
3439        NULL = auto()
3440        NULLABLE = auto()
3441        NVARCHAR = auto()
3442        OBJECT = auto()
3443        ROWVERSION = auto()
3444        SERIAL = auto()
3445        SET = auto()
3446        SMALLINT = auto()
3447        SMALLMONEY = auto()
3448        SMALLSERIAL = auto()
3449        STRUCT = auto()
3450        SUPER = auto()
3451        TEXT = auto()
3452        TIME = auto()
3453        TIMESTAMP = auto()
3454        TIMESTAMPTZ = auto()
3455        TIMESTAMPLTZ = auto()
3456        TINYINT = auto()
3457        UBIGINT = auto()
3458        UINT = auto()
3459        USMALLINT = auto()
3460        UTINYINT = auto()
3461        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3462        UINT128 = auto()
3463        UINT256 = auto()
3464        UNIQUEIDENTIFIER = auto()
3465        USERDEFINED = "USER-DEFINED"
3466        UUID = auto()
3467        VARBINARY = auto()
3468        VARCHAR = auto()
3469        VARIANT = auto()
3470        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'>
IPADDRESS = <Type.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <Type.IPPREFIX: 'IPPREFIX'>
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):
3537class PseudoType(Expression):
3538    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3542class SubqueryPredicate(Predicate):
3543    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3546class All(SubqueryPredicate):
3547    pass
key = 'all'
class Any(SubqueryPredicate):
3550class Any(SubqueryPredicate):
3551    pass
key = 'any'
class Exists(SubqueryPredicate):
3554class Exists(SubqueryPredicate):
3555    pass
key = 'exists'
class Command(Expression):
3560class Command(Expression):
3561    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3564class Transaction(Expression):
3565    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3568class Commit(Expression):
3569    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3572class Rollback(Expression):
3573    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3576class AlterTable(Expression):
3577    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3580class AddConstraint(Expression):
3581    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3584class DropPartition(Expression):
3585    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3589class Binary(Condition):
3590    arg_types = {"this": True, "expression": True}
3591
3592    @property
3593    def left(self):
3594        return self.this
3595
3596    @property
3597    def right(self):
3598        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3601class Add(Binary):
3602    pass
key = 'add'
class Connector(Binary):
3605class Connector(Binary):
3606    pass
key = 'connector'
class And(Connector):
3609class And(Connector):
3610    pass
key = 'and'
class Or(Connector):
3613class Or(Connector):
3614    pass
key = 'or'
class BitwiseAnd(Binary):
3617class BitwiseAnd(Binary):
3618    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3621class BitwiseLeftShift(Binary):
3622    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3625class BitwiseOr(Binary):
3626    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3629class BitwiseRightShift(Binary):
3630    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3633class BitwiseXor(Binary):
3634    pass
key = 'bitwisexor'
class Div(Binary):
3637class Div(Binary):
3638    pass
key = 'div'
class Overlaps(Binary):
3641class Overlaps(Binary):
3642    pass
key = 'overlaps'
class Dot(Binary):
3645class Dot(Binary):
3646    @property
3647    def name(self) -> str:
3648        return self.expression.name
3649
3650    @property
3651    def output_name(self) -> str:
3652        return self.name
3653
3654    @classmethod
3655    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3656        """Build a Dot object with a sequence of expressions."""
3657        if len(expressions) < 2:
3658            raise ValueError(f"Dot requires >= 2 expressions.")
3659
3660        a, b, *expressions = expressions
3661        dot = Dot(this=a, expression=b)
3662
3663        for expression in expressions:
3664            dot = Dot(this=dot, expression=expression)
3665
3666        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:
3654    @classmethod
3655    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3656        """Build a Dot object with a sequence of expressions."""
3657        if len(expressions) < 2:
3658            raise ValueError(f"Dot requires >= 2 expressions.")
3659
3660        a, b, *expressions = expressions
3661        dot = Dot(this=a, expression=b)
3662
3663        for expression in expressions:
3664            dot = Dot(this=dot, expression=expression)
3665
3666        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3669class DPipe(Binary):
3670    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3673class SafeDPipe(DPipe):
3674    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3677class EQ(Binary, Predicate):
3678    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3681class NullSafeEQ(Binary, Predicate):
3682    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3685class NullSafeNEQ(Binary, Predicate):
3686    pass
key = 'nullsafeneq'
class Distance(Binary):
3689class Distance(Binary):
3690    pass
key = 'distance'
class Escape(Binary):
3693class Escape(Binary):
3694    pass
key = 'escape'
class Glob(Binary, Predicate):
3697class Glob(Binary, Predicate):
3698    pass
key = 'glob'
class GT(Binary, Predicate):
3701class GT(Binary, Predicate):
3702    pass
key = 'gt'
class GTE(Binary, Predicate):
3705class GTE(Binary, Predicate):
3706    pass
key = 'gte'
class ILike(Binary, Predicate):
3709class ILike(Binary, Predicate):
3710    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3713class ILikeAny(Binary, Predicate):
3714    pass
key = 'ilikeany'
class IntDiv(Binary):
3717class IntDiv(Binary):
3718    pass
key = 'intdiv'
class Is(Binary, Predicate):
3721class Is(Binary, Predicate):
3722    pass
key = 'is'
class Kwarg(Binary):
3725class Kwarg(Binary):
3726    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3729class Like(Binary, Predicate):
3730    pass
key = 'like'
class LikeAny(Binary, Predicate):
3733class LikeAny(Binary, Predicate):
3734    pass
key = 'likeany'
class LT(Binary, Predicate):
3737class LT(Binary, Predicate):
3738    pass
key = 'lt'
class LTE(Binary, Predicate):
3741class LTE(Binary, Predicate):
3742    pass
key = 'lte'
class Mod(Binary):
3745class Mod(Binary):
3746    pass
key = 'mod'
class Mul(Binary):
3749class Mul(Binary):
3750    pass
key = 'mul'
class NEQ(Binary, Predicate):
3753class NEQ(Binary, Predicate):
3754    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3757class SimilarTo(Binary, Predicate):
3758    pass
key = 'similarto'
class Slice(Binary):
3761class Slice(Binary):
3762    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3765class Sub(Binary):
3766    pass
key = 'sub'
class ArrayOverlaps(Binary):
3769class ArrayOverlaps(Binary):
3770    pass
key = 'arrayoverlaps'
class Unary(Condition):
3775class Unary(Condition):
3776    pass
key = 'unary'
class BitwiseNot(Unary):
3779class BitwiseNot(Unary):
3780    pass
key = 'bitwisenot'
class Not(Unary):
3783class Not(Unary):
3784    pass
key = 'not'
class Paren(Unary):
3787class Paren(Unary):
3788    arg_types = {"this": True, "with": False}
3789
3790    @property
3791    def output_name(self) -> str:
3792        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):
3795class Neg(Unary):
3796    pass
key = 'neg'
class Alias(Expression):
3799class Alias(Expression):
3800    arg_types = {"this": True, "alias": False}
3801
3802    @property
3803    def output_name(self) -> str:
3804        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):
3807class Aliases(Expression):
3808    arg_types = {"this": True, "expressions": True}
3809
3810    @property
3811    def aliases(self):
3812        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3815class AtTimeZone(Expression):
3816    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3819class Between(Predicate):
3820    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3823class Bracket(Condition):
3824    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3827class SafeBracket(Bracket):
3828    """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):
3831class Distinct(Expression):
3832    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3835class In(Predicate):
3836    arg_types = {
3837        "this": True,
3838        "expressions": False,
3839        "query": False,
3840        "unnest": False,
3841        "field": False,
3842        "is_global": False,
3843    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3846class TimeUnit(Expression):
3847    """Automatically converts unit arg into a var."""
3848
3849    arg_types = {"unit": False}
3850
3851    def __init__(self, **args):
3852        unit = args.get("unit")
3853        if isinstance(unit, (Column, Literal)):
3854            args["unit"] = Var(this=unit.name)
3855        elif isinstance(unit, Week):
3856            unit.set("this", Var(this=unit.this.name))
3857
3858        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3851    def __init__(self, **args):
3852        unit = args.get("unit")
3853        if isinstance(unit, (Column, Literal)):
3854            args["unit"] = Var(this=unit.name)
3855        elif isinstance(unit, Week):
3856            unit.set("this", Var(this=unit.this.name))
3857
3858        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3861class Interval(TimeUnit):
3862    arg_types = {"this": False, "unit": False}
3863
3864    @property
3865    def unit(self) -> t.Optional[Var]:
3866        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3869class IgnoreNulls(Expression):
3870    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3873class RespectNulls(Expression):
3874    pass
key = 'respectnulls'
class Func(Condition):
3878class Func(Condition):
3879    """
3880    The base class for all function expressions.
3881
3882    Attributes:
3883        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3884            treated as a variable length argument and the argument's value will be stored as a list.
3885        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3886            for this function expression. These values are used to map this node to a name during parsing
3887            as well as to provide the function's name during SQL string generation. By default the SQL
3888            name is set to the expression's class name transformed to snake case.
3889    """
3890
3891    is_var_len_args = False
3892
3893    @classmethod
3894    def from_arg_list(cls, args):
3895        if cls.is_var_len_args:
3896            all_arg_keys = list(cls.arg_types)
3897            # If this function supports variable length argument treat the last argument as such.
3898            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3899            num_non_var = len(non_var_len_arg_keys)
3900
3901            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3902            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3903        else:
3904            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3905
3906        return cls(**args_dict)
3907
3908    @classmethod
3909    def sql_names(cls):
3910        if cls is Func:
3911            raise NotImplementedError(
3912                "SQL name is only supported by concrete function implementations"
3913            )
3914        if "_sql_names" not in cls.__dict__:
3915            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3916        return cls._sql_names
3917
3918    @classmethod
3919    def sql_name(cls):
3920        return cls.sql_names()[0]
3921
3922    @classmethod
3923    def default_parser_mappings(cls):
3924        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):
3893    @classmethod
3894    def from_arg_list(cls, args):
3895        if cls.is_var_len_args:
3896            all_arg_keys = list(cls.arg_types)
3897            # If this function supports variable length argument treat the last argument as such.
3898            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3899            num_non_var = len(non_var_len_arg_keys)
3900
3901            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3902            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3903        else:
3904            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3905
3906        return cls(**args_dict)
@classmethod
def sql_names(cls):
3908    @classmethod
3909    def sql_names(cls):
3910        if cls is Func:
3911            raise NotImplementedError(
3912                "SQL name is only supported by concrete function implementations"
3913            )
3914        if "_sql_names" not in cls.__dict__:
3915            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3916        return cls._sql_names
@classmethod
def sql_name(cls):
3918    @classmethod
3919    def sql_name(cls):
3920        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3922    @classmethod
3923    def default_parser_mappings(cls):
3924        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3927class AggFunc(Func):
3928    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3931class ParameterizedAgg(AggFunc):
3932    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3935class Abs(Func):
3936    pass
key = 'abs'
class Transform(Func):
3940class Transform(Func):
3941    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
3944class Anonymous(Func):
3945    arg_types = {"this": True, "expressions": False}
3946    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3951class Hll(AggFunc):
3952    arg_types = {"this": True, "expressions": False}
3953    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3956class ApproxDistinct(AggFunc):
3957    arg_types = {"this": True, "accuracy": False}
3958    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3961class Array(Func):
3962    arg_types = {"expressions": False}
3963    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3967class ToChar(Func):
3968    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3971class GenerateSeries(Func):
3972    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3975class ArrayAgg(AggFunc):
3976    pass
key = 'arrayagg'
class ArrayAll(Func):
3979class ArrayAll(Func):
3980    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3983class ArrayAny(Func):
3984    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3987class ArrayConcat(Func):
3988    arg_types = {"this": True, "expressions": False}
3989    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3992class ArrayContains(Binary, Func):
3993    pass
key = 'arraycontains'
class ArrayContained(Binary):
3996class ArrayContained(Binary):
3997    pass
key = 'arraycontained'
class ArrayFilter(Func):
4000class ArrayFilter(Func):
4001    arg_types = {"this": True, "expression": True}
4002    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4005class ArrayJoin(Func):
4006    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4009class ArraySize(Func):
4010    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4013class ArraySort(Func):
4014    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4017class ArraySum(Func):
4018    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4021class ArrayUnionAgg(AggFunc):
4022    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4025class Avg(AggFunc):
4026    pass
key = 'avg'
class AnyValue(AggFunc):
4029class AnyValue(AggFunc):
4030    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
4033class Case(Func):
4034    arg_types = {"this": False, "ifs": True, "default": False}
4035
4036    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4037        instance = maybe_copy(self, copy)
4038        instance.append(
4039            "ifs",
4040            If(
4041                this=maybe_parse(condition, copy=copy, **opts),
4042                true=maybe_parse(then, copy=copy, **opts),
4043            ),
4044        )
4045        return instance
4046
4047    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4048        instance = maybe_copy(self, copy)
4049        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4050        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:
4036    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4037        instance = maybe_copy(self, copy)
4038        instance.append(
4039            "ifs",
4040            If(
4041                this=maybe_parse(condition, copy=copy, **opts),
4042                true=maybe_parse(then, copy=copy, **opts),
4043            ),
4044        )
4045        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4047    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4048        instance = maybe_copy(self, copy)
4049        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4050        return instance
key = 'case'
class Cast(Func):
4053class Cast(Func):
4054    arg_types = {"this": True, "to": True, "format": False}
4055
4056    @property
4057    def name(self) -> str:
4058        return self.this.name
4059
4060    @property
4061    def to(self) -> DataType:
4062        return self.args["to"]
4063
4064    @property
4065    def output_name(self) -> str:
4066        return self.name
4067
4068    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4069        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:
4068    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4069        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
4072class CastToStrType(Func):
4073    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
4076class Collate(Binary):
4077    pass
key = 'collate'
class TryCast(Cast):
4080class TryCast(Cast):
4081    pass
key = 'trycast'
class Ceil(Func):
4084class Ceil(Func):
4085    arg_types = {"this": True, "decimals": False}
4086    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4089class Coalesce(Func):
4090    arg_types = {"this": True, "expressions": False}
4091    is_var_len_args = True
4092    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4095class Concat(Func):
4096    arg_types = {"expressions": True}
4097    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4100class SafeConcat(Concat):
4101    pass
key = 'safeconcat'
class ConcatWs(Concat):
4104class ConcatWs(Concat):
4105    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4108class Count(AggFunc):
4109    arg_types = {"this": False, "expressions": False}
4110    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4113class CountIf(AggFunc):
4114    pass
key = 'countif'
class CurrentDate(Func):
4117class CurrentDate(Func):
4118    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4121class CurrentDatetime(Func):
4122    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4125class CurrentTime(Func):
4126    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4129class CurrentTimestamp(Func):
4130    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4133class CurrentUser(Func):
4134    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4137class DateAdd(Func, TimeUnit):
4138    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4141class DateSub(Func, TimeUnit):
4142    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4145class DateDiff(Func, TimeUnit):
4146    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4147    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4150class DateTrunc(Func):
4151    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4154class DatetimeAdd(Func, TimeUnit):
4155    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4158class DatetimeSub(Func, TimeUnit):
4159    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4162class DatetimeDiff(Func, TimeUnit):
4163    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4166class DatetimeTrunc(Func, TimeUnit):
4167    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4170class DayOfWeek(Func):
4171    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4174class DayOfMonth(Func):
4175    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4178class DayOfYear(Func):
4179    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4182class WeekOfYear(Func):
4183    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4186class MonthsBetween(Func):
4187    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4190class LastDateOfMonth(Func):
4191    pass
key = 'lastdateofmonth'
class Extract(Func):
4194class Extract(Func):
4195    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4198class TimestampAdd(Func, TimeUnit):
4199    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4202class TimestampSub(Func, TimeUnit):
4203    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4206class TimestampDiff(Func, TimeUnit):
4207    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4210class TimestampTrunc(Func, TimeUnit):
4211    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4214class TimeAdd(Func, TimeUnit):
4215    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4218class TimeSub(Func, TimeUnit):
4219    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4222class TimeDiff(Func, TimeUnit):
4223    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4226class TimeTrunc(Func, TimeUnit):
4227    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4230class DateFromParts(Func):
4231    _sql_names = ["DATEFROMPARTS"]
4232    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4235class DateStrToDate(Func):
4236    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4239class DateToDateStr(Func):
4240    pass
key = 'datetodatestr'
class DateToDi(Func):
4243class DateToDi(Func):
4244    pass
key = 'datetodi'
class Date(Func):
4248class Date(Func):
4249    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4252class Day(Func):
4253    pass
key = 'day'
class Decode(Func):
4256class Decode(Func):
4257    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4260class DiToDate(Func):
4261    pass
key = 'ditodate'
class Encode(Func):
4264class Encode(Func):
4265    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4268class Exp(Func):
4269    pass
key = 'exp'
class Explode(Func):
4272class Explode(Func):
4273    pass
key = 'explode'
class Floor(Func):
4276class Floor(Func):
4277    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4280class FromBase64(Func):
4281    pass
key = 'frombase64'
class ToBase64(Func):
4284class ToBase64(Func):
4285    pass
key = 'tobase64'
class Greatest(Func):
4288class Greatest(Func):
4289    arg_types = {"this": True, "expressions": False}
4290    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4293class GroupConcat(Func):
4294    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4297class Hex(Func):
4298    pass
key = 'hex'
class Xor(Connector, Func):
4301class Xor(Connector, Func):
4302    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4305class If(Func):
4306    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4309class Initcap(Func):
4310    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4313class IsNan(Func):
4314    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class JSONKeyValue(Expression):
4317class JSONKeyValue(Expression):
4318    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4321class JSONObject(Func):
4322    arg_types = {
4323        "expressions": False,
4324        "null_handling": False,
4325        "unique_keys": False,
4326        "return_type": False,
4327        "format_json": False,
4328        "encoding": False,
4329    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4332class OpenJSONColumnDef(Expression):
4333    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):
4336class OpenJSON(Func):
4337    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4340class JSONBContains(Binary):
4341    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4344class JSONExtract(Binary, Func):
4345    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4348class JSONExtractScalar(JSONExtract):
4349    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4352class JSONBExtract(JSONExtract):
4353    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4356class JSONBExtractScalar(JSONExtract):
4357    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4360class JSONFormat(Func):
4361    arg_types = {"this": False, "options": False}
4362    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4366class JSONArrayContains(Binary, Predicate, Func):
4367    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4370class Least(Func):
4371    arg_types = {"this": True, "expressions": False}
4372    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4375class Left(Func):
4376    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4383class Length(Func):
4384    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4387class Levenshtein(Func):
4388    arg_types = {
4389        "this": True,
4390        "expression": False,
4391        "ins_cost": False,
4392        "del_cost": False,
4393        "sub_cost": False,
4394    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4397class Ln(Func):
4398    pass
key = 'ln'
class Log(Func):
4401class Log(Func):
4402    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4405class Log2(Func):
4406    pass
key = 'log2'
class Log10(Func):
4409class Log10(Func):
4410    pass
key = 'log10'
class LogicalOr(AggFunc):
4413class LogicalOr(AggFunc):
4414    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4417class LogicalAnd(AggFunc):
4418    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4421class Lower(Func):
4422    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4425class Map(Func):
4426    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4429class MapFromEntries(Func):
4430    pass
key = 'mapfromentries'
class StarMap(Func):
4433class StarMap(Func):
4434    pass
key = 'starmap'
class VarMap(Func):
4437class VarMap(Func):
4438    arg_types = {"keys": True, "values": True}
4439    is_var_len_args = True
4440
4441    @property
4442    def keys(self) -> t.List[Expression]:
4443        return self.args["keys"].expressions
4444
4445    @property
4446    def values(self) -> t.List[Expression]:
4447        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4451class MatchAgainst(Func):
4452    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4455class Max(AggFunc):
4456    arg_types = {"this": True, "expressions": False}
4457    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4460class MD5(Func):
4461    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4465class MD5Digest(Func):
4466    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4469class Min(AggFunc):
4470    arg_types = {"this": True, "expressions": False}
4471    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4474class Month(Func):
4475    pass
key = 'month'
class Nvl2(Func):
4478class Nvl2(Func):
4479    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4482class Posexplode(Func):
4483    pass
key = 'posexplode'
class Pow(Binary, Func):
4486class Pow(Binary, Func):
4487    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4490class PercentileCont(AggFunc):
4491    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4494class PercentileDisc(AggFunc):
4495    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4498class Quantile(AggFunc):
4499    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4502class ApproxQuantile(Quantile):
4503    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):
4506class RangeN(Func):
4507    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4510class ReadCSV(Func):
4511    _sql_names = ["READ_CSV"]
4512    is_var_len_args = True
4513    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4516class Reduce(Func):
4517    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):
4520class RegexpExtract(Func):
4521    arg_types = {
4522        "this": True,
4523        "expression": True,
4524        "position": False,
4525        "occurrence": False,
4526        "parameters": False,
4527        "group": False,
4528    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4531class RegexpReplace(Func):
4532    arg_types = {
4533        "this": True,
4534        "expression": True,
4535        "replacement": True,
4536        "position": False,
4537        "occurrence": False,
4538        "parameters": False,
4539    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4542class RegexpLike(Binary, Func):
4543    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4546class RegexpILike(Func):
4547    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4552class RegexpSplit(Func):
4553    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4556class Repeat(Func):
4557    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4560class Round(Func):
4561    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4564class RowNumber(Func):
4565    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4568class SafeDivide(Func):
4569    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4572class SetAgg(AggFunc):
4573    pass
key = 'setagg'
class SHA(Func):
4576class SHA(Func):
4577    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4580class SHA2(Func):
4581    _sql_names = ["SHA2"]
4582    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4585class SortArray(Func):
4586    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4589class Split(Func):
4590    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4595class Substring(Func):
4596    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4599class StandardHash(Func):
4600    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4603class StartsWith(Func):
4604    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4605    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4608class StrPosition(Func):
4609    arg_types = {
4610        "this": True,
4611        "substr": True,
4612        "position": False,
4613        "instance": False,
4614    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4617class StrToDate(Func):
4618    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4621class StrToTime(Func):
4622    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4627class StrToUnix(Func):
4628    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4631class NumberToStr(Func):
4632    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4635class FromBase(Func):
4636    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4639class Struct(Func):
4640    arg_types = {"expressions": True}
4641    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4644class StructExtract(Func):
4645    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4648class Sum(AggFunc):
4649    pass
key = 'sum'
class Sqrt(Func):
4652class Sqrt(Func):
4653    pass
key = 'sqrt'
class Stddev(AggFunc):
4656class Stddev(AggFunc):
4657    pass
key = 'stddev'
class StddevPop(AggFunc):
4660class StddevPop(AggFunc):
4661    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4664class StddevSamp(AggFunc):
4665    pass
key = 'stddevsamp'
class TimeToStr(Func):
4668class TimeToStr(Func):
4669    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4672class TimeToTimeStr(Func):
4673    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4676class TimeToUnix(Func):
4677    pass
key = 'timetounix'
class TimeStrToDate(Func):
4680class TimeStrToDate(Func):
4681    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4684class TimeStrToTime(Func):
4685    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4688class TimeStrToUnix(Func):
4689    pass
key = 'timestrtounix'
class Trim(Func):
4692class Trim(Func):
4693    arg_types = {
4694        "this": True,
4695        "expression": False,
4696        "position": False,
4697        "collation": False,
4698    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4701class TsOrDsAdd(Func, TimeUnit):
4702    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4705class TsOrDsToDateStr(Func):
4706    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4709class TsOrDsToDate(Func):
4710    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4713class TsOrDiToDi(Func):
4714    pass
key = 'tsorditodi'
class Unhex(Func):
4717class Unhex(Func):
4718    pass
key = 'unhex'
class UnixToStr(Func):
4721class UnixToStr(Func):
4722    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4727class UnixToTime(Func):
4728    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4729
4730    SECONDS = Literal.string("seconds")
4731    MILLIS = Literal.string("millis")
4732    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):
4735class UnixToTimeStr(Func):
4736    pass
key = 'unixtotimestr'
class Upper(Func):
4739class Upper(Func):
4740    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4743class Variance(AggFunc):
4744    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4747class VariancePop(AggFunc):
4748    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4751class Week(Func):
4752    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4755class XMLTable(Func):
4756    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):
4759class Year(Func):
4760    pass
key = 'year'
class Use(Expression):
4763class Use(Expression):
4764    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4767class Merge(Expression):
4768    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):
4771class When(Func):
4772    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):
4777class NextValueFor(Func):
4778    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.IsNan'>, <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.StartsWith'>, <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:
4815def maybe_parse(
4816    sql_or_expression: ExpOrStr,
4817    *,
4818    into: t.Optional[IntoType] = None,
4819    dialect: DialectType = None,
4820    prefix: t.Optional[str] = None,
4821    copy: bool = False,
4822    **opts,
4823) -> Expression:
4824    """Gracefully handle a possible string or expression.
4825
4826    Example:
4827        >>> maybe_parse("1")
4828        (LITERAL this: 1, is_string: False)
4829        >>> maybe_parse(to_identifier("x"))
4830        (IDENTIFIER this: x, quoted: False)
4831
4832    Args:
4833        sql_or_expression: the SQL code string or an expression
4834        into: the SQLGlot Expression to parse into
4835        dialect: the dialect used to parse the input expressions (in the case that an
4836            input expression is a SQL string).
4837        prefix: a string to prefix the sql with before it gets parsed
4838            (automatically includes a space)
4839        copy: whether or not to copy the expression.
4840        **opts: other options to use to parse the input expressions (again, in the case
4841            that an input expression is a SQL string).
4842
4843    Returns:
4844        Expression: the parsed or given expression.
4845    """
4846    if isinstance(sql_or_expression, Expression):
4847        if copy:
4848            return sql_or_expression.copy()
4849        return sql_or_expression
4850
4851    if sql_or_expression is None:
4852        raise ParseError(f"SQL cannot be None")
4853
4854    import sqlglot
4855
4856    sql = str(sql_or_expression)
4857    if prefix:
4858        sql = f"{prefix} {sql}"
4859
4860    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def maybe_copy(instance: ~E, copy: bool = True) -> ~E:
4863def maybe_copy(instance: E, copy: bool = True) -> E:
4864    return instance.copy() if copy else instance
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:
5044def union(
5045    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5046) -> Union:
5047    """
5048    Initializes a syntax tree from one UNION expression.
5049
5050    Example:
5051        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5052        'SELECT * FROM foo UNION 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 Union 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 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:
5072def intersect(
5073    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5074) -> Intersect:
5075    """
5076    Initializes a syntax tree from one INTERSECT expression.
5077
5078    Example:
5079        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5080        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5081
5082    Args:
5083        left: the SQL code string corresponding to the left-hand side.
5084            If an `Expression` instance is passed, it will be used as-is.
5085        right: the SQL code string corresponding to the right-hand side.
5086            If an `Expression` instance is passed, it will be used as-is.
5087        distinct: set the DISTINCT flag if and only if this is true.
5088        dialect: the dialect used to parse the input expression.
5089        opts: other options to use to parse the input expressions.
5090
5091    Returns:
5092        The new Intersect instance.
5093    """
5094    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5095    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5096
5097    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:
5100def except_(
5101    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5102) -> Except:
5103    """
5104    Initializes a syntax tree from one EXCEPT expression.
5105
5106    Example:
5107        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5108        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5109
5110    Args:
5111        left: the SQL code string corresponding to the left-hand side.
5112            If an `Expression` instance is passed, it will be used as-is.
5113        right: the SQL code string corresponding to the right-hand side.
5114            If an `Expression` instance is passed, it will be used as-is.
5115        distinct: set the DISTINCT flag if and only if this is true.
5116        dialect: the dialect used to parse the input expression.
5117        opts: other options to use to parse the input expressions.
5118
5119    Returns:
5120        The new Except instance.
5121    """
5122    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5123    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5124
5125    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:
5128def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5129    """
5130    Initializes a syntax tree from one or multiple SELECT expressions.
5131
5132    Example:
5133        >>> select("col1", "col2").from_("tbl").sql()
5134        'SELECT col1, col2 FROM tbl'
5135
5136    Args:
5137        *expressions: the SQL code string to parse as the expressions of a
5138            SELECT statement. If an Expression instance is passed, this is used as-is.
5139        dialect: the dialect used to parse the input expressions (in the case that an
5140            input expression is a SQL string).
5141        **opts: other options to use to parse the input expressions (again, in the case
5142            that an input expression is a SQL string).
5143
5144    Returns:
5145        Select: the syntax tree for the SELECT statement.
5146    """
5147    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:
5150def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5151    """
5152    Initializes a syntax tree from a FROM expression.
5153
5154    Example:
5155        >>> from_("tbl").select("col1", "col2").sql()
5156        'SELECT col1, col2 FROM tbl'
5157
5158    Args:
5159        *expression: the SQL code string to parse as the FROM expressions of a
5160            SELECT statement. If an Expression instance is passed, this is used as-is.
5161        dialect: the dialect used to parse the input expression (in the case that the
5162            input expression is a SQL string).
5163        **opts: other options to use to parse the input expressions (again, in the case
5164            that the input expression is a SQL string).
5165
5166    Returns:
5167        Select: the syntax tree for the SELECT statement.
5168    """
5169    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:
5172def update(
5173    table: str | Table,
5174    properties: dict,
5175    where: t.Optional[ExpOrStr] = None,
5176    from_: t.Optional[ExpOrStr] = None,
5177    dialect: DialectType = None,
5178    **opts,
5179) -> Update:
5180    """
5181    Creates an update statement.
5182
5183    Example:
5184        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5185        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5186
5187    Args:
5188        *properties: dictionary of properties to set which are
5189            auto converted to sql objects eg None -> NULL
5190        where: sql conditional parsed into a WHERE statement
5191        from_: sql statement parsed into a FROM statement
5192        dialect: the dialect used to parse the input expressions.
5193        **opts: other options to use to parse the input expressions.
5194
5195    Returns:
5196        Update: the syntax tree for the UPDATE statement.
5197    """
5198    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5199    update_expr.set(
5200        "expressions",
5201        [
5202            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5203            for k, v in properties.items()
5204        ],
5205    )
5206    if from_:
5207        update_expr.set(
5208            "from",
5209            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5210        )
5211    if isinstance(where, Condition):
5212        where = Where(this=where)
5213    if where:
5214        update_expr.set(
5215            "where",
5216            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5217        )
5218    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:
5221def delete(
5222    table: ExpOrStr,
5223    where: t.Optional[ExpOrStr] = None,
5224    returning: t.Optional[ExpOrStr] = None,
5225    dialect: DialectType = None,
5226    **opts,
5227) -> Delete:
5228    """
5229    Builds a delete statement.
5230
5231    Example:
5232        >>> delete("my_table", where="id > 1").sql()
5233        'DELETE FROM my_table WHERE id > 1'
5234
5235    Args:
5236        where: sql conditional parsed into a WHERE statement
5237        returning: sql conditional parsed into a RETURNING statement
5238        dialect: the dialect used to parse the input expressions.
5239        **opts: other options to use to parse the input expressions.
5240
5241    Returns:
5242        Delete: the syntax tree for the DELETE statement.
5243    """
5244    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5245    if where:
5246        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5247    if returning:
5248        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5249    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:
5252def insert(
5253    expression: ExpOrStr,
5254    into: ExpOrStr,
5255    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5256    overwrite: t.Optional[bool] = None,
5257    dialect: DialectType = None,
5258    copy: bool = True,
5259    **opts,
5260) -> Insert:
5261    """
5262    Builds an INSERT statement.
5263
5264    Example:
5265        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5266        'INSERT INTO tbl VALUES (1, 2, 3)'
5267
5268    Args:
5269        expression: the sql string or expression of the INSERT statement
5270        into: the tbl to insert data to.
5271        columns: optionally the table's column names.
5272        overwrite: whether to INSERT OVERWRITE or not.
5273        dialect: the dialect used to parse the input expressions.
5274        copy: whether or not to copy the expression.
5275        **opts: other options to use to parse the input expressions.
5276
5277    Returns:
5278        Insert: the syntax tree for the INSERT statement.
5279    """
5280    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5281    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5282
5283    if columns:
5284        this = _apply_list_builder(
5285            *columns,
5286            instance=Schema(this=this),
5287            arg="expressions",
5288            into=Identifier,
5289            copy=False,
5290            dialect=dialect,
5291            **opts,
5292        )
5293
5294    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:
5297def condition(
5298    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5299) -> Condition:
5300    """
5301    Initialize a logical condition expression.
5302
5303    Example:
5304        >>> condition("x=1").sql()
5305        'x = 1'
5306
5307        This is helpful for composing larger logical syntax trees:
5308        >>> where = condition("x=1")
5309        >>> where = where.and_("y=1")
5310        >>> Select().from_("tbl").select("*").where(where).sql()
5311        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5312
5313    Args:
5314        *expression: the SQL code string to parse.
5315            If an Expression instance is passed, this is used as-is.
5316        dialect: the dialect used to parse the input expression (in the case that the
5317            input expression is a SQL string).
5318        copy: Whether or not to copy `expression` (only applies to expressions).
5319        **opts: other options to use to parse the input expressions (again, in the case
5320            that the input expression is a SQL string).
5321
5322    Returns:
5323        The new Condition instance
5324    """
5325    return maybe_parse(
5326        expression,
5327        into=Condition,
5328        dialect=dialect,
5329        copy=copy,
5330        **opts,
5331    )

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:
5334def and_(
5335    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5336) -> Condition:
5337    """
5338    Combine multiple conditions with an AND logical operator.
5339
5340    Example:
5341        >>> and_("x=1", and_("y=1", "z=1")).sql()
5342        'x = 1 AND (y = 1 AND z = 1)'
5343
5344    Args:
5345        *expressions: the SQL code strings to parse.
5346            If an Expression instance is passed, this is used as-is.
5347        dialect: the dialect used to parse the input expression.
5348        copy: whether or not to copy `expressions` (only applies to Expressions).
5349        **opts: other options to use to parse the input expressions.
5350
5351    Returns:
5352        And: the new condition
5353    """
5354    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:
5357def or_(
5358    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5359) -> Condition:
5360    """
5361    Combine multiple conditions with an OR logical operator.
5362
5363    Example:
5364        >>> or_("x=1", or_("y=1", "z=1")).sql()
5365        'x = 1 OR (y = 1 OR z = 1)'
5366
5367    Args:
5368        *expressions: the SQL code strings to parse.
5369            If an Expression instance is passed, this is used as-is.
5370        dialect: the dialect used to parse the input expression.
5371        copy: whether or not to copy `expressions` (only applies to Expressions).
5372        **opts: other options to use to parse the input expressions.
5373
5374    Returns:
5375        Or: the new condition
5376    """
5377    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:
5380def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5381    """
5382    Wrap a condition with a NOT operator.
5383
5384    Example:
5385        >>> not_("this_suit='black'").sql()
5386        "NOT this_suit = 'black'"
5387
5388    Args:
5389        expression: the SQL code string to parse.
5390            If an Expression instance is passed, this is used as-is.
5391        dialect: the dialect used to parse the input expression.
5392        copy: whether to copy the expression or not.
5393        **opts: other options to use to parse the input expressions.
5394
5395    Returns:
5396        The new condition.
5397    """
5398    this = condition(
5399        expression,
5400        dialect=dialect,
5401        copy=copy,
5402        **opts,
5403    )
5404    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:
5407def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5408    """
5409    Wrap an expression in parentheses.
5410
5411    Example:
5412        >>> paren("5 + 3").sql()
5413        '(5 + 3)'
5414
5415    Args:
5416        expression: the SQL code string to parse.
5417            If an Expression instance is passed, this is used as-is.
5418        copy: whether to copy the expression or not.
5419
5420    Returns:
5421        The wrapped expression.
5422    """
5423    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):
5441def to_identifier(name, quoted=None, copy=True):
5442    """Builds an identifier.
5443
5444    Args:
5445        name: The name to turn into an identifier.
5446        quoted: Whether or not force quote the identifier.
5447        copy: Whether or not to copy a passed in Identefier node.
5448
5449    Returns:
5450        The identifier ast node.
5451    """
5452
5453    if name is None:
5454        return None
5455
5456    if isinstance(name, Identifier):
5457        identifier = maybe_copy(name, copy)
5458    elif isinstance(name, str):
5459        identifier = Identifier(
5460            this=name,
5461            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5462        )
5463    else:
5464        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5465    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:
5471def to_interval(interval: str | Literal) -> Interval:
5472    """Builds an interval expression from a string like '1 day' or '5 months'."""
5473    if isinstance(interval, Literal):
5474        if not interval.is_string:
5475            raise ValueError("Invalid interval string.")
5476
5477        interval = interval.this
5478
5479    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5480
5481    if not interval_parts:
5482        raise ValueError("Invalid interval string.")
5483
5484    return Interval(
5485        this=Literal.string(interval_parts.group(1)),
5486        unit=Var(this=interval_parts.group(2)),
5487    )

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]:
5500def to_table(
5501    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5502) -> t.Optional[Table]:
5503    """
5504    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5505    If a table is passed in then that table is returned.
5506
5507    Args:
5508        sql_path: a `[catalog].[schema].[table]` string.
5509        dialect: the source dialect according to which the table name will be parsed.
5510        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5511
5512    Returns:
5513        A table expression.
5514    """
5515    if sql_path is None or isinstance(sql_path, Table):
5516        return sql_path
5517    if not isinstance(sql_path, str):
5518        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5519
5520    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5521    if table:
5522        for k, v in kwargs.items():
5523            table.set(k, v)
5524
5525    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:
5528def to_column(sql_path: str | Column, **kwargs) -> Column:
5529    """
5530    Create a column from a `[table].[column]` sql path. Schema is optional.
5531
5532    If a column is passed in then that column is returned.
5533
5534    Args:
5535        sql_path: `[table].[column]` string
5536    Returns:
5537        Table: A column expression
5538    """
5539    if sql_path is None or isinstance(sql_path, Column):
5540        return sql_path
5541    if not isinstance(sql_path, str):
5542        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5543    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):
5546def alias_(
5547    expression: ExpOrStr,
5548    alias: str | Identifier,
5549    table: bool | t.Sequence[str | Identifier] = False,
5550    quoted: t.Optional[bool] = None,
5551    dialect: DialectType = None,
5552    copy: bool = True,
5553    **opts,
5554):
5555    """Create an Alias expression.
5556
5557    Example:
5558        >>> alias_('foo', 'bar').sql()
5559        'foo AS bar'
5560
5561        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5562        '(SELECT 1, 2) AS bar(a, b)'
5563
5564    Args:
5565        expression: the SQL code strings to parse.
5566            If an Expression instance is passed, this is used as-is.
5567        alias: the alias name to use. If the name has
5568            special characters it is quoted.
5569        table: Whether or not to create a table alias, can also be a list of columns.
5570        quoted: whether or not to quote the alias
5571        dialect: the dialect used to parse the input expression.
5572        copy: Whether or not to copy the expression.
5573        **opts: other options to use to parse the input expressions.
5574
5575    Returns:
5576        Alias: the aliased expression
5577    """
5578    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5579    alias = to_identifier(alias, quoted=quoted)
5580
5581    if table:
5582        table_alias = TableAlias(this=alias)
5583        exp.set("alias", table_alias)
5584
5585        if not isinstance(table, bool):
5586            for column in table:
5587                table_alias.append("columns", to_identifier(column, quoted=quoted))
5588
5589        return exp
5590
5591    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5592    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5593    # for the complete Window expression.
5594    #
5595    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5596
5597    if "alias" in exp.arg_types and not isinstance(exp, Window):
5598        exp.set("alias", alias)
5599        return exp
5600    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:
5603def subquery(
5604    expression: ExpOrStr,
5605    alias: t.Optional[Identifier | str] = None,
5606    dialect: DialectType = None,
5607    **opts,
5608) -> Select:
5609    """
5610    Build a subquery expression.
5611
5612    Example:
5613        >>> subquery('select x from tbl', 'bar').select('x').sql()
5614        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5615
5616    Args:
5617        expression: the SQL code strings to parse.
5618            If an Expression instance is passed, this is used as-is.
5619        alias: the alias name to use.
5620        dialect: the dialect used to parse the input expression.
5621        **opts: other options to use to parse the input expressions.
5622
5623    Returns:
5624        A new Select instance with the subquery expression included.
5625    """
5626
5627    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5628    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:
5631def column(
5632    col: str | Identifier,
5633    table: t.Optional[str | Identifier] = None,
5634    db: t.Optional[str | Identifier] = None,
5635    catalog: t.Optional[str | Identifier] = None,
5636    quoted: t.Optional[bool] = None,
5637) -> Column:
5638    """
5639    Build a Column.
5640
5641    Args:
5642        col: Column name.
5643        table: Table name.
5644        db: Database name.
5645        catalog: Catalog name.
5646        quoted: Whether to force quotes on the column's identifiers.
5647
5648    Returns:
5649        The new Column instance.
5650    """
5651    return Column(
5652        this=to_identifier(col, quoted=quoted),
5653        table=to_identifier(table, quoted=quoted),
5654        db=to_identifier(db, quoted=quoted),
5655        catalog=to_identifier(catalog, quoted=quoted),
5656    )

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:
5659def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5660    """Cast an expression to a data type.
5661
5662    Example:
5663        >>> cast('x + 1', 'int').sql()
5664        'CAST(x + 1 AS INT)'
5665
5666    Args:
5667        expression: The expression to cast.
5668        to: The datatype to cast to.
5669
5670    Returns:
5671        The new Cast instance.
5672    """
5673    expression = maybe_parse(expression, **opts)
5674    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:
5677def table_(
5678    table: Identifier | str,
5679    db: t.Optional[Identifier | str] = None,
5680    catalog: t.Optional[Identifier | str] = None,
5681    quoted: t.Optional[bool] = None,
5682    alias: t.Optional[Identifier | str] = None,
5683) -> Table:
5684    """Build a Table.
5685
5686    Args:
5687        table: Table name.
5688        db: Database name.
5689        catalog: Catalog name.
5690        quote: Whether to force quotes on the table's identifiers.
5691        alias: Table's alias.
5692
5693    Returns:
5694        The new Table instance.
5695    """
5696    return Table(
5697        this=to_identifier(table, quoted=quoted),
5698        db=to_identifier(db, quoted=quoted),
5699        catalog=to_identifier(catalog, quoted=quoted),
5700        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5701    )

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:
5704def values(
5705    values: t.Iterable[t.Tuple[t.Any, ...]],
5706    alias: t.Optional[str] = None,
5707    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5708) -> Values:
5709    """Build VALUES statement.
5710
5711    Example:
5712        >>> values([(1, '2')]).sql()
5713        "VALUES (1, '2')"
5714
5715    Args:
5716        values: values statements that will be converted to SQL
5717        alias: optional alias
5718        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5719         If either are provided then an alias is also required.
5720
5721    Returns:
5722        Values: the Values expression object
5723    """
5724    if columns and not alias:
5725        raise ValueError("Alias is required when providing columns")
5726
5727    return Values(
5728        expressions=[convert(tup) for tup in values],
5729        alias=(
5730            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5731            if columns
5732            else (TableAlias(this=to_identifier(alias)) if alias else None)
5733        ),
5734    )

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:
5737def var(name: t.Optional[ExpOrStr]) -> Var:
5738    """Build a SQL variable.
5739
5740    Example:
5741        >>> repr(var('x'))
5742        '(VAR this: x)'
5743
5744        >>> repr(var(column('x', table='y')))
5745        '(VAR this: x)'
5746
5747    Args:
5748        name: The name of the var or an expression who's name will become the var.
5749
5750    Returns:
5751        The new variable node.
5752    """
5753    if not name:
5754        raise ValueError("Cannot convert empty name into var.")
5755
5756    if isinstance(name, Expression):
5757        name = name.name
5758    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:
5761def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5762    """Build ALTER TABLE... RENAME... expression
5763
5764    Args:
5765        old_name: The old name of the table
5766        new_name: The new name of the table
5767
5768    Returns:
5769        Alter table expression
5770    """
5771    old_table = to_table(old_name)
5772    new_table = to_table(new_name)
5773    return AlterTable(
5774        this=old_table,
5775        actions=[
5776            RenameTable(this=new_table),
5777        ],
5778    )

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:
5781def convert(value: t.Any, copy: bool = False) -> Expression:
5782    """Convert a python value into an expression object.
5783
5784    Raises an error if a conversion is not possible.
5785
5786    Args:
5787        value: A python object.
5788        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5789
5790    Returns:
5791        Expression: the equivalent expression object.
5792    """
5793    if isinstance(value, Expression):
5794        return maybe_copy(value, copy)
5795    if isinstance(value, str):
5796        return Literal.string(value)
5797    if isinstance(value, bool):
5798        return Boolean(this=value)
5799    if value is None or (isinstance(value, float) and math.isnan(value)):
5800        return NULL
5801    if isinstance(value, numbers.Number):
5802        return Literal.number(value)
5803    if isinstance(value, datetime.datetime):
5804        datetime_literal = Literal.string(
5805            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5806        )
5807        return TimeStrToTime(this=datetime_literal)
5808    if isinstance(value, datetime.date):
5809        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5810        return DateStrToDate(this=date_literal)
5811    if isinstance(value, tuple):
5812        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5813    if isinstance(value, list):
5814        return Array(expressions=[convert(v, copy=copy) for v in value])
5815    if isinstance(value, dict):
5816        return Map(
5817            keys=[convert(k, copy=copy) for k in value],
5818            values=[convert(v, copy=copy) for v in value.values()],
5819        )
5820    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:
5823def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5824    """
5825    Replace children of an expression with the result of a lambda fun(child) -> exp.
5826    """
5827    for k, v in expression.args.items():
5828        is_list_arg = type(v) is list
5829
5830        child_nodes = v if is_list_arg else [v]
5831        new_child_nodes = []
5832
5833        for cn in child_nodes:
5834            if isinstance(cn, Expression):
5835                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5836                    new_child_nodes.append(child_node)
5837                    child_node.parent = expression
5838                    child_node.arg_key = k
5839            else:
5840                new_child_nodes.append(cn)
5841
5842        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]:
5845def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5846    """
5847    Return all table names referenced through columns in an expression.
5848
5849    Example:
5850        >>> import sqlglot
5851        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5852        ['a', 'c']
5853
5854    Args:
5855        expression: expression to find table names.
5856        exclude: a table name to exclude
5857
5858    Returns:
5859        A list of unique names.
5860    """
5861    return {
5862        table
5863        for table in (column.table for column in expression.find_all(Column))
5864        if table and table != exclude
5865    }

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:
5868def table_name(table: Table | str, dialect: DialectType = None) -> str:
5869    """Get the full name of a table as a string.
5870
5871    Args:
5872        table: Table expression node or string.
5873        dialect: The dialect to generate the table name for.
5874
5875    Examples:
5876        >>> from sqlglot import exp, parse_one
5877        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5878        'a.b.c'
5879
5880    Returns:
5881        The table name.
5882    """
5883
5884    table = maybe_parse(table, into=Table)
5885
5886    if not table:
5887        raise ValueError(f"Cannot parse {table}")
5888
5889    return ".".join(
5890        part.sql(dialect=dialect, identify=True)
5891        if not SAFE_IDENTIFIER_RE.match(part.name)
5892        else part.name
5893        for part in table.parts
5894    )

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:
5897def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5898    """Replace all tables in expression according to the mapping.
5899
5900    Args:
5901        expression: expression node to be transformed and replaced.
5902        mapping: mapping of table names.
5903        copy: whether or not to copy the expression.
5904
5905    Examples:
5906        >>> from sqlglot import exp, parse_one
5907        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5908        'SELECT * FROM c'
5909
5910    Returns:
5911        The mapped expression.
5912    """
5913
5914    def _replace_tables(node: Expression) -> Expression:
5915        if isinstance(node, Table):
5916            new_name = mapping.get(table_name(node))
5917            if new_name:
5918                return to_table(
5919                    new_name,
5920                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5921                )
5922        return node
5923
5924    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:
5927def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5928    """Replace placeholders in an expression.
5929
5930    Args:
5931        expression: expression node to be transformed and replaced.
5932        args: positional names that will substitute unnamed placeholders in the given order.
5933        kwargs: keyword arguments that will substitute named placeholders.
5934
5935    Examples:
5936        >>> from sqlglot import exp, parse_one
5937        >>> replace_placeholders(
5938        ...     parse_one("select * from :tbl where ? = ?"),
5939        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5940        ... ).sql()
5941        "SELECT * FROM foo WHERE str_col = 'b'"
5942
5943    Returns:
5944        The mapped expression.
5945    """
5946
5947    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5948        if isinstance(node, Placeholder):
5949            if node.name:
5950                new_name = kwargs.get(node.name)
5951                if new_name:
5952                    return convert(new_name)
5953            else:
5954                try:
5955                    return convert(next(args))
5956                except StopIteration:
5957                    pass
5958        return node
5959
5960    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:
5963def expand(
5964    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5965) -> Expression:
5966    """Transforms an expression by expanding all referenced sources into subqueries.
5967
5968    Examples:
5969        >>> from sqlglot import parse_one
5970        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5971        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5972
5973        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5974        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5975
5976    Args:
5977        expression: The expression to expand.
5978        sources: A dictionary of name to Subqueryables.
5979        copy: Whether or not to copy the expression during transformation. Defaults to True.
5980
5981    Returns:
5982        The transformed expression.
5983    """
5984
5985    def _expand(node: Expression):
5986        if isinstance(node, Table):
5987            name = table_name(node)
5988            source = sources.get(name)
5989            if source:
5990                subquery = source.subquery(node.alias or name)
5991                subquery.comments = [f"source: {name}"]
5992                return subquery.transform(_expand, copy=False)
5993        return node
5994
5995    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:
5998def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5999    """
6000    Returns a Func expression.
6001
6002    Examples:
6003        >>> func("abs", 5).sql()
6004        'ABS(5)'
6005
6006        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6007        'CAST(5 AS DOUBLE)'
6008
6009    Args:
6010        name: the name of the function to build.
6011        args: the args used to instantiate the function of interest.
6012        dialect: the source dialect.
6013        kwargs: the kwargs used to instantiate the function of interest.
6014
6015    Note:
6016        The arguments `args` and `kwargs` are mutually exclusive.
6017
6018    Returns:
6019        An instance of the function of interest, or an anonymous function, if `name` doesn't
6020        correspond to an existing `sqlglot.expressions.Func` class.
6021    """
6022    if args and kwargs:
6023        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6024
6025    from sqlglot.dialects.dialect import Dialect
6026
6027    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6028    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6029
6030    parser = Dialect.get_or_raise(dialect)().parser()
6031    from_args_list = parser.FUNCTIONS.get(name.upper())
6032
6033    if from_args_list:
6034        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6035    else:
6036        kwargs = kwargs or {"expressions": converted}
6037        function = Anonymous(this=name, **kwargs)
6038
6039    for error_message in function.error_messages(converted):
6040        raise ValueError(error_message)
6041
6042    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:
6045def true() -> Boolean:
6046    """
6047    Returns a true Boolean expression.
6048    """
6049    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
6052def false() -> Boolean:
6053    """
6054    Returns a false Boolean expression.
6055    """
6056    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6059def null() -> Null:
6060    """
6061    Returns a Null expression.
6062    """
6063    return Null()

Returns a Null expression.

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