Edit on GitHub

Expressions

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

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


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

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

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
Expression(**args: Any)
89    def __init__(self, **args: t.Any):
90        self.args: t.Dict[str, t.Any] = args
91        self.parent: t.Optional[Expression] = None
92        self.arg_key: t.Optional[str] = None
93        self.comments: t.Optional[t.List[str]] = None
94        self._type: t.Optional[DataType] = None
95        self._meta: t.Optional[t.Dict[str, t.Any]] = None
96        self._hash: t.Optional[int] = None
97
98        for arg_key, value in self.args.items():
99            self._set_parent(arg_key, value)
key = 'expression'
arg_types = {'this': True}
args: Dict[str, Any]
parent: Optional[sqlglot.expressions.Expression]
arg_key: Optional[str]
comments: Optional[List[str]]
hashable_args: Any
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
139    def text(self, key) -> str:
140        """
141        Returns a textual representation of the argument corresponding to "key". This can only be used
142        for args that are strings or leaf Expression instances, such as identifiers and literals.
143        """
144        field = self.args.get(key)
145        if isinstance(field, str):
146            return field
147        if isinstance(field, (Identifier, Literal, Var)):
148            return field.this
149        if isinstance(field, (Star, Null)):
150            return field.name
151        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

name: str
alias_or_name: str
output_name: str

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

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

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

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
257    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
258        if self.comments is None:
259            self.comments = []
260        if comments:
261            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
263    def append(self, arg_key: str, value: t.Any) -> None:
264        """
265        Appends value to arg_key if it's a list or sets it as a new list.
266
267        Args:
268            arg_key (str): name of the list expression arg
269            value (Any): value to append to the list
270        """
271        if not isinstance(self.args.get(arg_key), list):
272            self.args[arg_key] = []
273        self.args[arg_key].append(value)
274        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key: str, value: Any) -> None:
276    def set(self, arg_key: str, value: t.Any) -> None:
277        """
278        Sets arg_key to value.
279
280        Args:
281            arg_key: name of the expression arg.
282            value: value to set the arg to.
283        """
284        if value is None:
285            self.args.pop(arg_key, None)
286            return
287
288        self.args[arg_key] = value
289        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key: name of the expression arg.
  • value: value to set the arg to.
depth: int

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
310    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
311        """Yields the key and expression for all arguments, exploding list args."""
312        for k, vs in self.args.items():
313            if type(vs) is list:
314                for v in vs:
315                    if hasattr(v, "parent"):
316                        yield k, v
317            else:
318                if hasattr(vs, "parent"):
319                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs: bool = True) -> Optional[~E]:
321    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
322        """
323        Returns the first node in this tree which matches at least one of
324        the specified types.
325
326        Args:
327            expression_types: the expression type(s) to match.
328            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
329
330        Returns:
331            The node which matches the criteria or None if no such node was found.
332        """
333        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs: bool = True) -> Iterator[~E]:
335    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
336        """
337        Returns a generator object which visits all nodes in this tree and only
338        yields those that match at least one of the specified expression types.
339
340        Args:
341            expression_types: the expression type(s) to match.
342            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
343
344        Returns:
345            The generator object.
346        """
347        for expression, *_ in self.walk(bfs=bfs):
348            if isinstance(expression, expression_types):
349                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
351    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
352        """
353        Returns a nearest parent matching expression_types.
354
355        Args:
356            expression_types: the expression type(s) to match.
357
358        Returns:
359            The parent node.
360        """
361        ancestor = self.parent
362        while ancestor and not isinstance(ancestor, expression_types):
363            ancestor = ancestor.parent
364        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

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

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
387    def walk(self, bfs=True, prune=None):
388        """
389        Returns a generator object which visits all nodes in this tree.
390
391        Args:
392            bfs (bool): if set to True the BFS traversal order will be applied,
393                otherwise the DFS traversal will be used instead.
394            prune ((node, parent, arg_key) -> bool): callable that returns True if
395                the generator should stop traversing this branch of the tree.
396
397        Returns:
398            the generator object.
399        """
400        if bfs:
401            yield from self.bfs(prune=prune)
402        else:
403            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
405    def dfs(self, parent=None, key=None, prune=None):
406        """
407        Returns a generator object which visits all nodes in this tree in
408        the DFS (Depth-first) order.
409
410        Returns:
411            The generator object.
412        """
413        parent = parent or self.parent
414        yield self, parent, key
415        if prune and prune(self, parent, key):
416            return
417
418        for k, v in self.iter_expressions():
419            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
421    def bfs(self, prune=None):
422        """
423        Returns a generator object which visits all nodes in this tree in
424        the BFS (Breadth-first) order.
425
426        Returns:
427            The generator object.
428        """
429        queue = deque([(self, self.parent, None)])
430
431        while queue:
432            item, parent, key = queue.popleft()
433
434            yield item, parent, key
435            if prune and prune(item, parent, key):
436                continue
437
438            for k, v in item.iter_expressions():
439                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
441    def unnest(self):
442        """
443        Returns the first non parenthesis child or self.
444        """
445        expression = self
446        while type(expression) is Paren:
447            expression = expression.this
448        return expression

Returns the first non parenthesis child or self.

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

Returns the inner expression if this is an Alias.

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

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
464    def flatten(self, unnest=True):
465        """
466        Returns a generator which yields child nodes who's parents are the same class.
467
468        A AND B AND C -> [A, B, C]
469        """
470        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
471            if not type(node) is self.__class__:
472                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
480    def sql(self, dialect: DialectType = None, **opts) -> str:
481        """
482        Returns SQL string representation of this tree.
483
484        Args:
485            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
486            opts: other `sqlglot.generator.Generator` options.
487
488        Returns:
489            The SQL string.
490        """
491        from sqlglot.dialects import Dialect
492
493        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
519    def transform(self, fun, *args, copy=True, **kwargs):
520        """
521        Recursively visits all tree nodes (excluding already transformed ones)
522        and applies the given transformation function to each node.
523
524        Args:
525            fun (function): a function which takes a node as an argument and returns a
526                new transformed node or the same node without modifications. If the function
527                returns None, then the corresponding node will be removed from the syntax tree.
528            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
529                modified in place.
530
531        Returns:
532            The transformed tree.
533        """
534        node = self.copy() if copy else self
535        new_node = fun(node, *args, **kwargs)
536
537        if new_node is None or not isinstance(new_node, Expression):
538            return new_node
539        if new_node is not node:
540            new_node.parent = node.parent
541            return new_node
542
543        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
544        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
554    def replace(self, expression):
555        """
556        Swap out this expression with a new expression.
557
558        For example::
559
560            >>> tree = Select().select("x").from_("tbl")
561            >>> tree.find(Column).replace(Column(this="y"))
562            (COLUMN this: y)
563            >>> tree.sql()
564            'SELECT y FROM tbl'
565
566        Args:
567            expression: new node
568
569        Returns:
570            The new expression or expressions.
571        """
572        if not self.parent:
573            return expression
574
575        parent = self.parent
576        self.parent = None
577
578        replace_children(parent, lambda child: expression if child is self else child)
579        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression: new node
Returns:

The new expression or expressions.

def pop(self: ~E) -> ~E:
581    def pop(self: E) -> E:
582        """
583        Remove this expression from its AST.
584
585        Returns:
586            The popped expression.
587        """
588        self.replace(None)
589        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_: Type[~E]) -> ~E:
591    def assert_is(self, type_: t.Type[E]) -> E:
592        """
593        Assert that this `Expression` is an instance of `type_`.
594
595        If it is NOT an instance of `type_`, this raises an assertion error.
596        Otherwise, this returns this expression.
597
598        Examples:
599            This is useful for type security in chained expressions:
600
601            >>> import sqlglot
602            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
603            'SELECT x, z FROM y'
604        """
605        assert isinstance(self, type_)
606        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
608    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
609        """
610        Checks if this expression is valid (e.g. all mandatory args are set).
611
612        Args:
613            args: a sequence of values that were used to instantiate a Func expression. This is used
614                to check that the provided arguments don't exceed the function argument limit.
615
616        Returns:
617            A list of error messages for all possible errors that were found.
618        """
619        errors: t.List[str] = []
620
621        for k in self.args:
622            if k not in self.arg_types:
623                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
624        for k, mandatory in self.arg_types.items():
625            v = self.args.get(k)
626            if mandatory and (v is None or (isinstance(v, list) and not v)):
627                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
628
629        if (
630            args
631            and isinstance(self, Func)
632            and len(args) > len(self.arg_types)
633            and not self.is_var_len_args
634        ):
635            errors.append(
636                f"The number of provided arguments ({len(args)}) is greater than "
637                f"the maximum number of supported arguments ({len(self.arg_types)})"
638            )
639
640        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
642    def dump(self):
643        """
644        Dump this Expression to a JSON-serializable dict.
645        """
646        from sqlglot.serde import dump
647
648        return dump(self)

Dump this Expression to a JSON-serializable dict.

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

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

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

AND this condition with one or multiple expressions.

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

The new And condition.

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

OR this condition with one or multiple expressions.

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

The new Or condition.

def not_(self, copy: bool = True):
721    def not_(self, copy: bool = True):
722        """
723        Wrap this condition with NOT.
724
725        Example:
726            >>> condition("x=1").not_().sql()
727            'NOT x = 1'
728
729        Args:
730            copy: whether or not to copy this object.
731
732        Returns:
733            The new Not instance.
734        """
735        return not_(self, copy=copy)

Wrap this condition with NOT.

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

The new Not instance.

def as_( self, alias: str | sqlglot.expressions.Identifier, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Alias:
737    def as_(
738        self,
739        alias: str | Identifier,
740        quoted: t.Optional[bool] = None,
741        dialect: DialectType = None,
742        copy: bool = True,
743        **opts,
744    ) -> Alias:
745        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, unnest: Union[str, sqlglot.expressions.Expression, NoneType, Collection[Union[str, sqlglot.expressions.Expression]]] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
762    def isin(
763        self,
764        *expressions: t.Any,
765        query: t.Optional[ExpOrStr] = None,
766        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
767        copy: bool = True,
768        **opts,
769    ) -> In:
770        return In(
771            this=maybe_copy(self, copy),
772            expressions=[convert(e, copy=copy) for e in expressions],
773            query=maybe_parse(query, copy=copy, **opts) if query else None,
774            unnest=Unnest(
775                expressions=[
776                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
777                ]
778            )
779            if unnest
780            else None,
781        )
def between( self, low: Any, high: Any, copy: bool = True, **opts) -> sqlglot.expressions.Between:
783    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
784        return Between(
785            this=maybe_copy(self, copy),
786            low=convert(low, copy=copy, **opts),
787            high=convert(high, copy=copy, **opts),
788        )
def is_( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Is:
790    def is_(self, other: ExpOrStr) -> Is:
791        return self._binop(Is, other)
def like( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Like:
793    def like(self, other: ExpOrStr) -> Like:
794        return self._binop(Like, other)
def ilike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.ILike:
796    def ilike(self, other: ExpOrStr) -> ILike:
797        return self._binop(ILike, other)
def eq(self, other: Any) -> sqlglot.expressions.EQ:
799    def eq(self, other: t.Any) -> EQ:
800        return self._binop(EQ, other)
def neq(self, other: Any) -> sqlglot.expressions.NEQ:
802    def neq(self, other: t.Any) -> NEQ:
803        return self._binop(NEQ, other)
def rlike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.RegexpLike:
805    def rlike(self, other: ExpOrStr) -> RegexpLike:
806        return self._binop(RegexpLike, other)
key = 'condition'
class Predicate(Condition):
881class Predicate(Condition):
882    """Relationships like x = y, x > 1, x >= y."""

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

key = 'predicate'
class DerivedTable(Expression):
885class DerivedTable(Expression):
886    @property
887    def alias_column_names(self) -> t.List[str]:
888        table_alias = self.args.get("alias")
889        if not table_alias:
890            return []
891        return [c.name for c in table_alias.args.get("columns") or []]
892
893    @property
894    def selects(self) -> t.List[Expression]:
895        return self.this.selects if isinstance(self.this, Subqueryable) else []
896
897    @property
898    def named_selects(self) -> t.List[str]:
899        return [select.output_name for select in self.selects]
alias_column_names: List[str]
named_selects: List[str]
key = 'derivedtable'
class Unionable(Expression):
902class Unionable(Expression):
903    def union(
904        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
905    ) -> Unionable:
906        """
907        Builds a UNION expression.
908
909        Example:
910            >>> import sqlglot
911            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
912            'SELECT * FROM foo UNION SELECT * FROM bla'
913
914        Args:
915            expression: the SQL code string.
916                If an `Expression` instance is passed, it will be used as-is.
917            distinct: set the DISTINCT flag if and only if this is true.
918            dialect: the dialect used to parse the input expression.
919            opts: other options to use to parse the input expressions.
920
921        Returns:
922            The new Union expression.
923        """
924        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
925
926    def intersect(
927        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
928    ) -> Unionable:
929        """
930        Builds an INTERSECT expression.
931
932        Example:
933            >>> import sqlglot
934            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
935            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
936
937        Args:
938            expression: the SQL code string.
939                If an `Expression` instance is passed, it will be used as-is.
940            distinct: set the DISTINCT flag if and only if this is true.
941            dialect: the dialect used to parse the input expression.
942            opts: other options to use to parse the input expressions.
943
944        Returns:
945            The new Intersect expression.
946        """
947        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
948
949    def except_(
950        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
951    ) -> Unionable:
952        """
953        Builds an EXCEPT expression.
954
955        Example:
956            >>> import sqlglot
957            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
958            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
959
960        Args:
961            expression: the SQL code string.
962                If an `Expression` instance is passed, it will be used as-is.
963            distinct: set the DISTINCT flag if and only if this is true.
964            dialect: the dialect used to parse the input expression.
965            opts: other options to use to parse the input expressions.
966
967        Returns:
968            The new Except expression.
969        """
970        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
903    def union(
904        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
905    ) -> Unionable:
906        """
907        Builds a UNION expression.
908
909        Example:
910            >>> import sqlglot
911            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
912            'SELECT * FROM foo UNION SELECT * FROM bla'
913
914        Args:
915            expression: the SQL code string.
916                If an `Expression` instance is passed, it will be used as-is.
917            distinct: set the DISTINCT flag if and only if this is true.
918            dialect: the dialect used to parse the input expression.
919            opts: other options to use to parse the input expressions.
920
921        Returns:
922            The new Union expression.
923        """
924        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

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

The new Union expression.

def intersect( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
926    def intersect(
927        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
928    ) -> Unionable:
929        """
930        Builds an INTERSECT expression.
931
932        Example:
933            >>> import sqlglot
934            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
935            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
936
937        Args:
938            expression: the SQL code string.
939                If an `Expression` instance is passed, it will be used as-is.
940            distinct: set the DISTINCT flag if and only if this is true.
941            dialect: the dialect used to parse the input expression.
942            opts: other options to use to parse the input expressions.
943
944        Returns:
945            The new Intersect expression.
946        """
947        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

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

The new Intersect expression.

def except_( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
949    def except_(
950        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
951    ) -> Unionable:
952        """
953        Builds an EXCEPT expression.
954
955        Example:
956            >>> import sqlglot
957            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
958            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
959
960        Args:
961            expression: the SQL code string.
962                If an `Expression` instance is passed, it will be used as-is.
963            distinct: set the DISTINCT flag if and only if this is true.
964            dialect: the dialect used to parse the input expression.
965            opts: other options to use to parse the input expressions.
966
967        Returns:
968            The new Except expression.
969        """
970        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

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

The new Except expression.

key = 'unionable'
class UDTF(DerivedTable, Unionable):
973class UDTF(DerivedTable, Unionable):
974    @property
975    def selects(self) -> t.List[Expression]:
976        alias = self.args.get("alias")
977        return alias.columns if alias else []
key = 'udtf'
class Cache(Expression):
980class Cache(Expression):
981    arg_types = {
982        "with": False,
983        "this": True,
984        "lazy": False,
985        "options": False,
986        "expression": False,
987    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
990class Uncache(Expression):
991    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class Create(Expression):
 994class Create(Expression):
 995    arg_types = {
 996        "with": False,
 997        "this": True,
 998        "kind": True,
 999        "expression": False,
1000        "exists": False,
1001        "properties": False,
1002        "replace": False,
1003        "unique": False,
1004        "indexes": False,
1005        "no_schema_binding": False,
1006        "begin": False,
1007        "clone": False,
1008    }
arg_types = {'with': False, 'this': True, 'kind': True, 'expression': False, 'exists': False, 'properties': False, 'replace': False, 'unique': False, 'indexes': False, 'no_schema_binding': False, 'begin': False, 'clone': False}
key = 'create'
class Clone(Expression):
1012class Clone(Expression):
1013    arg_types = {
1014        "this": True,
1015        "when": False,
1016        "kind": False,
1017        "expression": False,
1018    }
arg_types = {'this': True, 'when': False, 'kind': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1021class Describe(Expression):
1022    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'describe'
class Pragma(Expression):
1025class Pragma(Expression):
1026    pass
key = 'pragma'
class Set(Expression):
1029class Set(Expression):
1030    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1033class SetItem(Expression):
1034    arg_types = {
1035        "this": False,
1036        "expressions": False,
1037        "kind": False,
1038        "collate": False,  # MySQL SET NAMES statement
1039        "global": False,
1040    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1043class Show(Expression):
1044    arg_types = {
1045        "this": True,
1046        "target": False,
1047        "offset": False,
1048        "limit": False,
1049        "like": False,
1050        "where": False,
1051        "db": False,
1052        "full": False,
1053        "mutex": False,
1054        "query": False,
1055        "channel": False,
1056        "global": False,
1057        "log": False,
1058        "position": False,
1059        "types": False,
1060    }
arg_types = {'this': True, 'target': False, 'offset': False, 'limit': False, 'like': False, 'where': False, 'db': False, 'full': False, 'mutex': False, 'query': False, 'channel': False, 'global': False, 'log': False, 'position': False, 'types': False}
key = 'show'
class UserDefinedFunction(Expression):
1063class UserDefinedFunction(Expression):
1064    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1067class CharacterSet(Expression):
1068    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1071class With(Expression):
1072    arg_types = {"expressions": True, "recursive": False}
1073
1074    @property
1075    def recursive(self) -> bool:
1076        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1079class WithinGroup(Expression):
1080    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1083class CTE(DerivedTable):
1084    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1087class TableAlias(Expression):
1088    arg_types = {"this": False, "columns": False}
1089
1090    @property
1091    def columns(self):
1092        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1095class BitString(Condition):
1096    pass
key = 'bitstring'
class HexString(Condition):
1099class HexString(Condition):
1100    pass
key = 'hexstring'
class ByteString(Condition):
1103class ByteString(Condition):
1104    pass
key = 'bytestring'
class RawString(Condition):
1107class RawString(Condition):
1108    pass
key = 'rawstring'
class Column(Condition):
1111class Column(Condition):
1112    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1113
1114    @property
1115    def table(self) -> str:
1116        return self.text("table")
1117
1118    @property
1119    def db(self) -> str:
1120        return self.text("db")
1121
1122    @property
1123    def catalog(self) -> str:
1124        return self.text("catalog")
1125
1126    @property
1127    def output_name(self) -> str:
1128        return self.name
1129
1130    @property
1131    def parts(self) -> t.List[Identifier]:
1132        """Return the parts of a column in order catalog, db, table, name."""
1133        return [
1134            t.cast(Identifier, self.args[part])
1135            for part in ("catalog", "db", "table", "this")
1136            if self.args.get(part)
1137        ]
1138
1139    def to_dot(self) -> Dot:
1140        """Converts the column into a dot expression."""
1141        parts = self.parts
1142        parent = self.parent
1143
1144        while parent:
1145            if isinstance(parent, Dot):
1146                parts.append(parent.expression)
1147            parent = parent.parent
1148
1149        return Dot.build(parts)
arg_types = {'this': True, 'table': False, 'db': False, 'catalog': False, 'join_mark': False}
table: str
db: str
catalog: str
output_name: str

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

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

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

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

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

Converts the column into a dot expression.

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

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:
1375    def where(
1376        self,
1377        *expressions: t.Optional[ExpOrStr],
1378        append: bool = True,
1379        dialect: DialectType = None,
1380        copy: bool = True,
1381        **opts,
1382    ) -> Delete:
1383        """
1384        Append to or set the WHERE expressions.
1385
1386        Example:
1387            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1388            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1389
1390        Args:
1391            *expressions: the SQL code strings to parse.
1392                If an `Expression` instance is passed, it will be used as-is.
1393                Multiple expressions are combined with an AND operator.
1394            append: if `True`, AND the new expressions to any existing expression.
1395                Otherwise, this resets the expression.
1396            dialect: the dialect used to parse the input expressions.
1397            copy: if `False`, modify this expression instance in-place.
1398            opts: other options to use to parse the input expressions.
1399
1400        Returns:
1401            Delete: the modified expression.
1402        """
1403        return _apply_conjunction_builder(
1404            *expressions,
1405            instance=self,
1406            arg="where",
1407            append=append,
1408            into=Where,
1409            dialect=dialect,
1410            copy=copy,
1411            **opts,
1412        )

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:
1414    def returning(
1415        self,
1416        expression: ExpOrStr,
1417        dialect: DialectType = None,
1418        copy: bool = True,
1419        **opts,
1420    ) -> Delete:
1421        """
1422        Set the RETURNING expression. Not supported by all dialects.
1423
1424        Example:
1425            >>> delete("tbl").returning("*", dialect="postgres").sql()
1426            'DELETE FROM tbl RETURNING *'
1427
1428        Args:
1429            expression: the SQL code strings to parse.
1430                If an `Expression` instance is passed, it will be used as-is.
1431            dialect: the dialect used to parse the input expressions.
1432            copy: if `False`, modify this expression instance in-place.
1433            opts: other options to use to parse the input expressions.
1434
1435        Returns:
1436            Delete: the modified expression.
1437        """
1438        return _apply_builder(
1439            expression=expression,
1440            instance=self,
1441            arg="returning",
1442            prefix="RETURNING",
1443            dialect=dialect,
1444            copy=copy,
1445            into=Returning,
1446            **opts,
1447        )

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):
1450class Drop(Expression):
1451    arg_types = {
1452        "this": False,
1453        "kind": False,
1454        "exists": False,
1455        "temporary": False,
1456        "materialized": False,
1457        "cascade": False,
1458        "constraints": False,
1459        "purge": False,
1460    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1463class Filter(Expression):
1464    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1467class Check(Expression):
1468    pass
key = 'check'
class Directory(Expression):
1471class Directory(Expression):
1472    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1473    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1476class ForeignKey(Expression):
1477    arg_types = {
1478        "expressions": True,
1479        "reference": False,
1480        "delete": False,
1481        "update": False,
1482    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1485class PrimaryKey(Expression):
1486    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1491class Into(Expression):
1492    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1495class From(Expression):
1496    @property
1497    def name(self) -> str:
1498        return self.this.name
1499
1500    @property
1501    def alias_or_name(self) -> str:
1502        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1505class Having(Expression):
1506    pass
key = 'having'
class Hint(Expression):
1509class Hint(Expression):
1510    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1513class JoinHint(Expression):
1514    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1517class Identifier(Expression):
1518    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1519
1520    @property
1521    def quoted(self) -> bool:
1522        return bool(self.args.get("quoted"))
1523
1524    @property
1525    def hashable_args(self) -> t.Any:
1526        return (self.this, self.quoted)
1527
1528    @property
1529    def output_name(self) -> str:
1530        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):
1533class Index(Expression):
1534    arg_types = {
1535        "this": False,
1536        "table": False,
1537        "using": False,
1538        "where": False,
1539        "columns": False,
1540        "unique": False,
1541        "primary": False,
1542        "amp": False,  # teradata
1543        "partition_by": False,  # teradata
1544    }
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):
1547class Insert(Expression):
1548    arg_types = {
1549        "with": False,
1550        "this": True,
1551        "expression": False,
1552        "conflict": False,
1553        "returning": False,
1554        "overwrite": False,
1555        "exists": False,
1556        "partition": False,
1557        "alternative": False,
1558        "where": False,
1559        "ignore": False,
1560    }
1561
1562    def with_(
1563        self,
1564        alias: ExpOrStr,
1565        as_: ExpOrStr,
1566        recursive: t.Optional[bool] = None,
1567        append: bool = True,
1568        dialect: DialectType = None,
1569        copy: bool = True,
1570        **opts,
1571    ) -> Insert:
1572        """
1573        Append to or set the common table expressions.
1574
1575        Example:
1576            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1577            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1578
1579        Args:
1580            alias: the SQL code string to parse as the table name.
1581                If an `Expression` instance is passed, this is used as-is.
1582            as_: the SQL code string to parse as the table expression.
1583                If an `Expression` instance is passed, it will be used as-is.
1584            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1585            append: if `True`, add to any existing expressions.
1586                Otherwise, this resets the expressions.
1587            dialect: the dialect used to parse the input expression.
1588            copy: if `False`, modify this expression instance in-place.
1589            opts: other options to use to parse the input expressions.
1590
1591        Returns:
1592            The modified expression.
1593        """
1594        return _apply_cte_builder(
1595            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1596        )
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:
1562    def with_(
1563        self,
1564        alias: ExpOrStr,
1565        as_: ExpOrStr,
1566        recursive: t.Optional[bool] = None,
1567        append: bool = True,
1568        dialect: DialectType = None,
1569        copy: bool = True,
1570        **opts,
1571    ) -> Insert:
1572        """
1573        Append to or set the common table expressions.
1574
1575        Example:
1576            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1577            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1578
1579        Args:
1580            alias: the SQL code string to parse as the table name.
1581                If an `Expression` instance is passed, this is used as-is.
1582            as_: the SQL code string to parse as the table expression.
1583                If an `Expression` instance is passed, it will be used as-is.
1584            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1585            append: if `True`, add to any existing expressions.
1586                Otherwise, this resets the expressions.
1587            dialect: the dialect used to parse the input expression.
1588            copy: if `False`, modify this expression instance in-place.
1589            opts: other options to use to parse the input expressions.
1590
1591        Returns:
1592            The modified expression.
1593        """
1594        return _apply_cte_builder(
1595            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1596        )

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):
1599class OnConflict(Expression):
1600    arg_types = {
1601        "duplicate": False,
1602        "expressions": False,
1603        "nothing": False,
1604        "key": False,
1605        "constraint": False,
1606    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1609class Returning(Expression):
1610    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1614class Introducer(Expression):
1615    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1619class National(Expression):
1620    pass
key = 'national'
class LoadData(Expression):
1623class LoadData(Expression):
1624    arg_types = {
1625        "this": True,
1626        "local": False,
1627        "overwrite": False,
1628        "inpath": True,
1629        "partition": False,
1630        "input_format": False,
1631        "serde": False,
1632    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1635class Partition(Expression):
1636    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1639class Fetch(Expression):
1640    arg_types = {
1641        "direction": False,
1642        "count": False,
1643        "percent": False,
1644        "with_ties": False,
1645    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1648class Group(Expression):
1649    arg_types = {
1650        "expressions": False,
1651        "grouping_sets": False,
1652        "cube": False,
1653        "rollup": False,
1654        "totals": False,
1655        "all": False,
1656    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1659class Lambda(Expression):
1660    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1663class Limit(Expression):
1664    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1667class Literal(Condition):
1668    arg_types = {"this": True, "is_string": True}
1669
1670    @property
1671    def hashable_args(self) -> t.Any:
1672        return (self.this, self.args.get("is_string"))
1673
1674    @classmethod
1675    def number(cls, number) -> Literal:
1676        return cls(this=str(number), is_string=False)
1677
1678    @classmethod
1679    def string(cls, string) -> Literal:
1680        return cls(this=str(string), is_string=True)
1681
1682    @property
1683    def output_name(self) -> str:
1684        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1674    @classmethod
1675    def number(cls, number) -> Literal:
1676        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1678    @classmethod
1679    def string(cls, string) -> Literal:
1680        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):
1687class Join(Expression):
1688    arg_types = {
1689        "this": True,
1690        "on": False,
1691        "side": False,
1692        "kind": False,
1693        "using": False,
1694        "method": False,
1695        "global": False,
1696        "hint": False,
1697    }
1698
1699    @property
1700    def method(self) -> str:
1701        return self.text("method").upper()
1702
1703    @property
1704    def kind(self) -> str:
1705        return self.text("kind").upper()
1706
1707    @property
1708    def side(self) -> str:
1709        return self.text("side").upper()
1710
1711    @property
1712    def hint(self) -> str:
1713        return self.text("hint").upper()
1714
1715    @property
1716    def alias_or_name(self) -> str:
1717        return self.this.alias_or_name
1718
1719    def on(
1720        self,
1721        *expressions: t.Optional[ExpOrStr],
1722        append: bool = True,
1723        dialect: DialectType = None,
1724        copy: bool = True,
1725        **opts,
1726    ) -> Join:
1727        """
1728        Append to or set the ON expressions.
1729
1730        Example:
1731            >>> import sqlglot
1732            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1733            'JOIN x ON y = 1'
1734
1735        Args:
1736            *expressions: the SQL code strings to parse.
1737                If an `Expression` instance is passed, it will be used as-is.
1738                Multiple expressions are combined with an AND operator.
1739            append: if `True`, AND the new expressions to any existing expression.
1740                Otherwise, this resets the expression.
1741            dialect: the dialect used to parse the input expressions.
1742            copy: if `False`, modify this expression instance in-place.
1743            opts: other options to use to parse the input expressions.
1744
1745        Returns:
1746            The modified Join expression.
1747        """
1748        join = _apply_conjunction_builder(
1749            *expressions,
1750            instance=self,
1751            arg="on",
1752            append=append,
1753            dialect=dialect,
1754            copy=copy,
1755            **opts,
1756        )
1757
1758        if join.kind == "CROSS":
1759            join.set("kind", None)
1760
1761        return join
1762
1763    def using(
1764        self,
1765        *expressions: t.Optional[ExpOrStr],
1766        append: bool = True,
1767        dialect: DialectType = None,
1768        copy: bool = True,
1769        **opts,
1770    ) -> Join:
1771        """
1772        Append to or set the USING expressions.
1773
1774        Example:
1775            >>> import sqlglot
1776            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1777            'JOIN x USING (foo, bla)'
1778
1779        Args:
1780            *expressions: the SQL code strings to parse.
1781                If an `Expression` instance is passed, it will be used as-is.
1782            append: if `True`, concatenate the new expressions to the existing "using" list.
1783                Otherwise, this resets the expression.
1784            dialect: the dialect used to parse the input expressions.
1785            copy: if `False`, modify this expression instance in-place.
1786            opts: other options to use to parse the input expressions.
1787
1788        Returns:
1789            The modified Join expression.
1790        """
1791        join = _apply_list_builder(
1792            *expressions,
1793            instance=self,
1794            arg="using",
1795            append=append,
1796            dialect=dialect,
1797            copy=copy,
1798            **opts,
1799        )
1800
1801        if join.kind == "CROSS":
1802            join.set("kind", None)
1803
1804        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:
1719    def on(
1720        self,
1721        *expressions: t.Optional[ExpOrStr],
1722        append: bool = True,
1723        dialect: DialectType = None,
1724        copy: bool = True,
1725        **opts,
1726    ) -> Join:
1727        """
1728        Append to or set the ON expressions.
1729
1730        Example:
1731            >>> import sqlglot
1732            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1733            'JOIN x ON y = 1'
1734
1735        Args:
1736            *expressions: the SQL code strings to parse.
1737                If an `Expression` instance is passed, it will be used as-is.
1738                Multiple expressions are combined with an AND operator.
1739            append: if `True`, AND the new expressions to any existing expression.
1740                Otherwise, this resets the expression.
1741            dialect: the dialect used to parse the input expressions.
1742            copy: if `False`, modify this expression instance in-place.
1743            opts: other options to use to parse the input expressions.
1744
1745        Returns:
1746            The modified Join expression.
1747        """
1748        join = _apply_conjunction_builder(
1749            *expressions,
1750            instance=self,
1751            arg="on",
1752            append=append,
1753            dialect=dialect,
1754            copy=copy,
1755            **opts,
1756        )
1757
1758        if join.kind == "CROSS":
1759            join.set("kind", None)
1760
1761        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:
1763    def using(
1764        self,
1765        *expressions: t.Optional[ExpOrStr],
1766        append: bool = True,
1767        dialect: DialectType = None,
1768        copy: bool = True,
1769        **opts,
1770    ) -> Join:
1771        """
1772        Append to or set the USING expressions.
1773
1774        Example:
1775            >>> import sqlglot
1776            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1777            'JOIN x USING (foo, bla)'
1778
1779        Args:
1780            *expressions: the SQL code strings to parse.
1781                If an `Expression` instance is passed, it will be used as-is.
1782            append: if `True`, concatenate the new expressions to the existing "using" list.
1783                Otherwise, this resets the expression.
1784            dialect: the dialect used to parse the input expressions.
1785            copy: if `False`, modify this expression instance in-place.
1786            opts: other options to use to parse the input expressions.
1787
1788        Returns:
1789            The modified Join expression.
1790        """
1791        join = _apply_list_builder(
1792            *expressions,
1793            instance=self,
1794            arg="using",
1795            append=append,
1796            dialect=dialect,
1797            copy=copy,
1798            **opts,
1799        )
1800
1801        if join.kind == "CROSS":
1802            join.set("kind", None)
1803
1804        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):
1807class Lateral(UDTF):
1808    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):
1811class MatchRecognize(Expression):
1812    arg_types = {
1813        "partition_by": False,
1814        "order": False,
1815        "measures": False,
1816        "rows": False,
1817        "after": False,
1818        "pattern": False,
1819        "define": False,
1820        "alias": False,
1821    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1826class Final(Expression):
1827    pass
key = 'final'
class Offset(Expression):
1830class Offset(Expression):
1831    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1834class Order(Expression):
1835    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1840class Cluster(Order):
1841    pass
key = 'cluster'
class Distribute(Order):
1844class Distribute(Order):
1845    pass
key = 'distribute'
class Sort(Order):
1848class Sort(Order):
1849    pass
key = 'sort'
class Ordered(Expression):
1852class Ordered(Expression):
1853    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1856class Property(Expression):
1857    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1860class AlgorithmProperty(Property):
1861    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1864class AutoIncrementProperty(Property):
1865    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1868class BlockCompressionProperty(Property):
1869    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):
1872class CharacterSetProperty(Property):
1873    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1876class ChecksumProperty(Property):
1877    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1880class CollateProperty(Property):
1881    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1884class CopyGrantsProperty(Property):
1885    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1888class DataBlocksizeProperty(Property):
1889    arg_types = {
1890        "size": False,
1891        "units": False,
1892        "minimum": False,
1893        "maximum": False,
1894        "default": False,
1895    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1898class DefinerProperty(Property):
1899    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1902class DistKeyProperty(Property):
1903    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1906class DistStyleProperty(Property):
1907    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1910class EngineProperty(Property):
1911    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
1914class HeapProperty(Property):
1915    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
1918class ToTableProperty(Property):
1919    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1922class ExecuteAsProperty(Property):
1923    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1926class ExternalProperty(Property):
1927    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1930class FallbackProperty(Property):
1931    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1934class FileFormatProperty(Property):
1935    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1938class FreespaceProperty(Property):
1939    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1942class InputOutputFormat(Expression):
1943    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1946class IsolatedLoadingProperty(Property):
1947    arg_types = {
1948        "no": True,
1949        "concurrent": True,
1950        "for_all": True,
1951        "for_insert": True,
1952        "for_none": True,
1953    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1956class JournalProperty(Property):
1957    arg_types = {
1958        "no": False,
1959        "dual": False,
1960        "before": False,
1961        "local": False,
1962        "after": False,
1963    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1966class LanguageProperty(Property):
1967    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1971class ClusteredByProperty(Property):
1972    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1975class DictProperty(Property):
1976    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1979class DictSubProperty(Property):
1980    pass
key = 'dictsubproperty'
class DictRange(Property):
1983class DictRange(Property):
1984    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1989class OnCluster(Property):
1990    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1993class LikeProperty(Property):
1994    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1997class LocationProperty(Property):
1998    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2001class LockingProperty(Property):
2002    arg_types = {
2003        "this": False,
2004        "kind": True,
2005        "for_or_in": True,
2006        "lock_type": True,
2007        "override": False,
2008    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2011class LogProperty(Property):
2012    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2015class MaterializedProperty(Property):
2016    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2019class MergeBlockRatioProperty(Property):
2020    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):
2023class NoPrimaryIndexProperty(Property):
2024    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
2027class OnCommitProperty(Property):
2028    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2031class PartitionedByProperty(Property):
2032    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2035class ReturnsProperty(Property):
2036    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2039class RowFormatProperty(Property):
2040    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2043class RowFormatDelimitedProperty(Property):
2044    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2045    arg_types = {
2046        "fields": False,
2047        "escaped": False,
2048        "collection_items": False,
2049        "map_keys": False,
2050        "lines": False,
2051        "null": False,
2052        "serde": False,
2053    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2056class RowFormatSerdeProperty(Property):
2057    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2061class QueryTransform(Expression):
2062    arg_types = {
2063        "expressions": True,
2064        "command_script": True,
2065        "schema": False,
2066        "row_format_before": False,
2067        "record_writer": False,
2068        "row_format_after": False,
2069        "record_reader": False,
2070    }
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):
2073class SchemaCommentProperty(Property):
2074    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2077class SerdeProperties(Property):
2078    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2081class SetProperty(Property):
2082    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2085class SettingsProperty(Property):
2086    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2089class SortKeyProperty(Property):
2090    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2093class SqlSecurityProperty(Property):
2094    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2097class StabilityProperty(Property):
2098    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2101class TemporaryProperty(Property):
2102    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2105class TransientProperty(Property):
2106    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2109class VolatileProperty(Property):
2110    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2113class WithDataProperty(Property):
2114    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2117class WithJournalTableProperty(Property):
2118    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2121class Properties(Expression):
2122    arg_types = {"expressions": True}
2123
2124    NAME_TO_PROPERTY = {
2125        "ALGORITHM": AlgorithmProperty,
2126        "AUTO_INCREMENT": AutoIncrementProperty,
2127        "CHARACTER SET": CharacterSetProperty,
2128        "CLUSTERED_BY": ClusteredByProperty,
2129        "COLLATE": CollateProperty,
2130        "COMMENT": SchemaCommentProperty,
2131        "DEFINER": DefinerProperty,
2132        "DISTKEY": DistKeyProperty,
2133        "DISTSTYLE": DistStyleProperty,
2134        "ENGINE": EngineProperty,
2135        "EXECUTE AS": ExecuteAsProperty,
2136        "FORMAT": FileFormatProperty,
2137        "LANGUAGE": LanguageProperty,
2138        "LOCATION": LocationProperty,
2139        "PARTITIONED_BY": PartitionedByProperty,
2140        "RETURNS": ReturnsProperty,
2141        "ROW_FORMAT": RowFormatProperty,
2142        "SORTKEY": SortKeyProperty,
2143    }
2144
2145    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2146
2147    # CREATE property locations
2148    # Form: schema specified
2149    #   create [POST_CREATE]
2150    #     table a [POST_NAME]
2151    #     (b int) [POST_SCHEMA]
2152    #     with ([POST_WITH])
2153    #     index (b) [POST_INDEX]
2154    #
2155    # Form: alias selection
2156    #   create [POST_CREATE]
2157    #     table a [POST_NAME]
2158    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2159    #     index (c) [POST_INDEX]
2160    class Location(AutoName):
2161        POST_CREATE = auto()
2162        POST_NAME = auto()
2163        POST_SCHEMA = auto()
2164        POST_WITH = auto()
2165        POST_ALIAS = auto()
2166        POST_EXPRESSION = auto()
2167        POST_INDEX = auto()
2168        UNSUPPORTED = auto()
2169
2170    @classmethod
2171    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2172        expressions = []
2173        for key, value in properties_dict.items():
2174            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2175            if property_cls:
2176                expressions.append(property_cls(this=convert(value)))
2177            else:
2178                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2179
2180        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:
2170    @classmethod
2171    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2172        expressions = []
2173        for key, value in properties_dict.items():
2174            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2175            if property_cls:
2176                expressions.append(property_cls(this=convert(value)))
2177            else:
2178                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2179
2180        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2160    class Location(AutoName):
2161        POST_CREATE = auto()
2162        POST_NAME = auto()
2163        POST_SCHEMA = auto()
2164        POST_WITH = auto()
2165        POST_ALIAS = auto()
2166        POST_EXPRESSION = auto()
2167        POST_INDEX = auto()
2168        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):
2183class Qualify(Expression):
2184    pass
key = 'qualify'
class Return(Expression):
2188class Return(Expression):
2189    pass
key = 'return'
class Reference(Expression):
2192class Reference(Expression):
2193    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2196class Tuple(Expression):
2197    arg_types = {"expressions": False}
2198
2199    def isin(
2200        self,
2201        *expressions: t.Any,
2202        query: t.Optional[ExpOrStr] = None,
2203        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2204        copy: bool = True,
2205        **opts,
2206    ) -> In:
2207        return In(
2208            this=maybe_copy(self, copy),
2209            expressions=[convert(e, copy=copy) for e in expressions],
2210            query=maybe_parse(query, copy=copy, **opts) if query else None,
2211            unnest=Unnest(
2212                expressions=[
2213                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2214                ]
2215            )
2216            if unnest
2217            else None,
2218        )
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:
2199    def isin(
2200        self,
2201        *expressions: t.Any,
2202        query: t.Optional[ExpOrStr] = None,
2203        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2204        copy: bool = True,
2205        **opts,
2206    ) -> In:
2207        return In(
2208            this=maybe_copy(self, copy),
2209            expressions=[convert(e, copy=copy) for e in expressions],
2210            query=maybe_parse(query, copy=copy, **opts) if query else None,
2211            unnest=Unnest(
2212                expressions=[
2213                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2214                ]
2215            )
2216            if unnest
2217            else None,
2218        )
key = 'tuple'
class Subqueryable(Unionable):
2221class Subqueryable(Unionable):
2222    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2223        """
2224        Convert this expression to an aliased expression that can be used as a Subquery.
2225
2226        Example:
2227            >>> subquery = Select().select("x").from_("tbl").subquery()
2228            >>> Select().select("x").from_(subquery).sql()
2229            'SELECT x FROM (SELECT x FROM tbl)'
2230
2231        Args:
2232            alias (str | Identifier): an optional alias for the subquery
2233            copy (bool): if `False`, modify this expression instance in-place.
2234
2235        Returns:
2236            Alias: the subquery
2237        """
2238        instance = maybe_copy(self, copy)
2239        if not isinstance(alias, Expression):
2240            alias = TableAlias(this=to_identifier(alias)) if alias else None
2241
2242        return Subquery(this=instance, alias=alias)
2243
2244    def limit(
2245        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2246    ) -> Select:
2247        raise NotImplementedError
2248
2249    @property
2250    def ctes(self):
2251        with_ = self.args.get("with")
2252        if not with_:
2253            return []
2254        return with_.expressions
2255
2256    @property
2257    def selects(self) -> t.List[Expression]:
2258        raise NotImplementedError("Subqueryable objects must implement `selects`")
2259
2260    @property
2261    def named_selects(self) -> t.List[str]:
2262        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2263
2264    def with_(
2265        self,
2266        alias: ExpOrStr,
2267        as_: ExpOrStr,
2268        recursive: t.Optional[bool] = None,
2269        append: bool = True,
2270        dialect: DialectType = None,
2271        copy: bool = True,
2272        **opts,
2273    ) -> Subqueryable:
2274        """
2275        Append to or set the common table expressions.
2276
2277        Example:
2278            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2279            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2280
2281        Args:
2282            alias: the SQL code string to parse as the table name.
2283                If an `Expression` instance is passed, this is used as-is.
2284            as_: the SQL code string to parse as the table expression.
2285                If an `Expression` instance is passed, it will be used as-is.
2286            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2287            append: if `True`, add to any existing expressions.
2288                Otherwise, this resets the expressions.
2289            dialect: the dialect used to parse the input expression.
2290            copy: if `False`, modify this expression instance in-place.
2291            opts: other options to use to parse the input expressions.
2292
2293        Returns:
2294            The modified expression.
2295        """
2296        return _apply_cte_builder(
2297            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2298        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2222    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2223        """
2224        Convert this expression to an aliased expression that can be used as a Subquery.
2225
2226        Example:
2227            >>> subquery = Select().select("x").from_("tbl").subquery()
2228            >>> Select().select("x").from_(subquery).sql()
2229            'SELECT x FROM (SELECT x FROM tbl)'
2230
2231        Args:
2232            alias (str | Identifier): an optional alias for the subquery
2233            copy (bool): if `False`, modify this expression instance in-place.
2234
2235        Returns:
2236            Alias: the subquery
2237        """
2238        instance = maybe_copy(self, copy)
2239        if not isinstance(alias, Expression):
2240            alias = TableAlias(this=to_identifier(alias)) if alias else None
2241
2242        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:
2244    def limit(
2245        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2246    ) -> Select:
2247        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:
2264    def with_(
2265        self,
2266        alias: ExpOrStr,
2267        as_: ExpOrStr,
2268        recursive: t.Optional[bool] = None,
2269        append: bool = True,
2270        dialect: DialectType = None,
2271        copy: bool = True,
2272        **opts,
2273    ) -> Subqueryable:
2274        """
2275        Append to or set the common table expressions.
2276
2277        Example:
2278            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2279            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2280
2281        Args:
2282            alias: the SQL code string to parse as the table name.
2283                If an `Expression` instance is passed, this is used as-is.
2284            as_: the SQL code string to parse as the table expression.
2285                If an `Expression` instance is passed, it will be used as-is.
2286            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2287            append: if `True`, add to any existing expressions.
2288                Otherwise, this resets the expressions.
2289            dialect: the dialect used to parse the input expression.
2290            copy: if `False`, modify this expression instance in-place.
2291            opts: other options to use to parse the input expressions.
2292
2293        Returns:
2294            The modified expression.
2295        """
2296        return _apply_cte_builder(
2297            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2298        )

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

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

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:
2581    def group_by(
2582        self,
2583        *expressions: t.Optional[ExpOrStr],
2584        append: bool = True,
2585        dialect: DialectType = None,
2586        copy: bool = True,
2587        **opts,
2588    ) -> Select:
2589        """
2590        Set the GROUP BY expression.
2591
2592        Example:
2593            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2594            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2595
2596        Args:
2597            *expressions: the SQL code strings to parse.
2598                If a `Group` instance is passed, this is used as-is.
2599                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2600                If nothing is passed in then a group by is not applied to the expression
2601            append: if `True`, add to any existing expressions.
2602                Otherwise, this flattens all the `Group` expression into a single expression.
2603            dialect: the dialect used to parse the input expression.
2604            copy: if `False`, modify this expression instance in-place.
2605            opts: other options to use to parse the input expressions.
2606
2607        Returns:
2608            The modified Select expression.
2609        """
2610        if not expressions:
2611            return self if not copy else self.copy()
2612
2613        return _apply_child_list_builder(
2614            *expressions,
2615            instance=self,
2616            arg="group",
2617            append=append,
2618            copy=copy,
2619            prefix="GROUP BY",
2620            into=Group,
2621            dialect=dialect,
2622            **opts,
2623        )

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:
2625    def order_by(
2626        self,
2627        *expressions: t.Optional[ExpOrStr],
2628        append: bool = True,
2629        dialect: DialectType = None,
2630        copy: bool = True,
2631        **opts,
2632    ) -> Select:
2633        """
2634        Set the ORDER BY expression.
2635
2636        Example:
2637            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2638            'SELECT x FROM tbl ORDER BY x DESC'
2639
2640        Args:
2641            *expressions: the SQL code strings to parse.
2642                If a `Group` instance is passed, this is used as-is.
2643                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2644            append: if `True`, add to any existing expressions.
2645                Otherwise, this flattens all the `Order` expression into a single expression.
2646            dialect: the dialect used to parse the input expression.
2647            copy: if `False`, modify this expression instance in-place.
2648            opts: other options to use to parse the input expressions.
2649
2650        Returns:
2651            The modified Select expression.
2652        """
2653        return _apply_child_list_builder(
2654            *expressions,
2655            instance=self,
2656            arg="order",
2657            append=append,
2658            copy=copy,
2659            prefix="ORDER BY",
2660            into=Order,
2661            dialect=dialect,
2662            **opts,
2663        )

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:
2665    def sort_by(
2666        self,
2667        *expressions: t.Optional[ExpOrStr],
2668        append: bool = True,
2669        dialect: DialectType = None,
2670        copy: bool = True,
2671        **opts,
2672    ) -> Select:
2673        """
2674        Set the SORT BY expression.
2675
2676        Example:
2677            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2678            'SELECT x FROM tbl SORT BY x DESC'
2679
2680        Args:
2681            *expressions: the SQL code strings to parse.
2682                If a `Group` instance is passed, this is used as-is.
2683                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2684            append: if `True`, add to any existing expressions.
2685                Otherwise, this flattens all the `Order` expression into a single expression.
2686            dialect: the dialect used to parse the input expression.
2687            copy: if `False`, modify this expression instance in-place.
2688            opts: other options to use to parse the input expressions.
2689
2690        Returns:
2691            The modified Select expression.
2692        """
2693        return _apply_child_list_builder(
2694            *expressions,
2695            instance=self,
2696            arg="sort",
2697            append=append,
2698            copy=copy,
2699            prefix="SORT BY",
2700            into=Sort,
2701            dialect=dialect,
2702            **opts,
2703        )

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:
2705    def cluster_by(
2706        self,
2707        *expressions: t.Optional[ExpOrStr],
2708        append: bool = True,
2709        dialect: DialectType = None,
2710        copy: bool = True,
2711        **opts,
2712    ) -> Select:
2713        """
2714        Set the CLUSTER BY expression.
2715
2716        Example:
2717            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2718            'SELECT x FROM tbl CLUSTER BY x DESC'
2719
2720        Args:
2721            *expressions: the SQL code strings to parse.
2722                If a `Group` instance is passed, this is used as-is.
2723                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2724            append: if `True`, add to any existing expressions.
2725                Otherwise, this flattens all the `Order` expression into a single expression.
2726            dialect: the dialect used to parse the input expression.
2727            copy: if `False`, modify this expression instance in-place.
2728            opts: other options to use to parse the input expressions.
2729
2730        Returns:
2731            The modified Select expression.
2732        """
2733        return _apply_child_list_builder(
2734            *expressions,
2735            instance=self,
2736            arg="cluster",
2737            append=append,
2738            copy=copy,
2739            prefix="CLUSTER BY",
2740            into=Cluster,
2741            dialect=dialect,
2742            **opts,
2743        )

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:
2745    def limit(
2746        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2747    ) -> Select:
2748        """
2749        Set the LIMIT expression.
2750
2751        Example:
2752            >>> Select().from_("tbl").select("x").limit(10).sql()
2753            'SELECT x FROM tbl LIMIT 10'
2754
2755        Args:
2756            expression: the SQL code string to parse.
2757                This can also be an integer.
2758                If a `Limit` instance is passed, this is used as-is.
2759                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2760            dialect: the dialect used to parse the input expression.
2761            copy: if `False`, modify this expression instance in-place.
2762            opts: other options to use to parse the input expressions.
2763
2764        Returns:
2765            Select: the modified expression.
2766        """
2767        return _apply_builder(
2768            expression=expression,
2769            instance=self,
2770            arg="limit",
2771            into=Limit,
2772            prefix="LIMIT",
2773            dialect=dialect,
2774            copy=copy,
2775            **opts,
2776        )

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:
2778    def offset(
2779        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2780    ) -> Select:
2781        """
2782        Set the OFFSET expression.
2783
2784        Example:
2785            >>> Select().from_("tbl").select("x").offset(10).sql()
2786            'SELECT x FROM tbl OFFSET 10'
2787
2788        Args:
2789            expression: the SQL code string to parse.
2790                This can also be an integer.
2791                If a `Offset` instance is passed, this is used as-is.
2792                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2793            dialect: the dialect used to parse the input expression.
2794            copy: if `False`, modify this expression instance in-place.
2795            opts: other options to use to parse the input expressions.
2796
2797        Returns:
2798            The modified Select expression.
2799        """
2800        return _apply_builder(
2801            expression=expression,
2802            instance=self,
2803            arg="offset",
2804            into=Offset,
2805            prefix="OFFSET",
2806            dialect=dialect,
2807            copy=copy,
2808            **opts,
2809        )

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:
2811    def select(
2812        self,
2813        *expressions: t.Optional[ExpOrStr],
2814        append: bool = True,
2815        dialect: DialectType = None,
2816        copy: bool = True,
2817        **opts,
2818    ) -> Select:
2819        """
2820        Append to or set the SELECT expressions.
2821
2822        Example:
2823            >>> Select().select("x", "y").sql()
2824            'SELECT x, y'
2825
2826        Args:
2827            *expressions: the SQL code strings to parse.
2828                If an `Expression` instance is passed, it will be used as-is.
2829            append: if `True`, add to any existing expressions.
2830                Otherwise, this resets the expressions.
2831            dialect: the dialect used to parse the input expressions.
2832            copy: if `False`, modify this expression instance in-place.
2833            opts: other options to use to parse the input expressions.
2834
2835        Returns:
2836            The modified Select expression.
2837        """
2838        return _apply_list_builder(
2839            *expressions,
2840            instance=self,
2841            arg="expressions",
2842            append=append,
2843            dialect=dialect,
2844            copy=copy,
2845            **opts,
2846        )

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:
2848    def lateral(
2849        self,
2850        *expressions: t.Optional[ExpOrStr],
2851        append: bool = True,
2852        dialect: DialectType = None,
2853        copy: bool = True,
2854        **opts,
2855    ) -> Select:
2856        """
2857        Append to or set the LATERAL expressions.
2858
2859        Example:
2860            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2861            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2862
2863        Args:
2864            *expressions: the SQL code strings to parse.
2865                If an `Expression` instance is passed, it will be used as-is.
2866            append: if `True`, add to any existing expressions.
2867                Otherwise, this resets the expressions.
2868            dialect: the dialect used to parse the input expressions.
2869            copy: if `False`, modify this expression instance in-place.
2870            opts: other options to use to parse the input expressions.
2871
2872        Returns:
2873            The modified Select expression.
2874        """
2875        return _apply_list_builder(
2876            *expressions,
2877            instance=self,
2878            arg="laterals",
2879            append=append,
2880            into=Lateral,
2881            prefix="LATERAL VIEW",
2882            dialect=dialect,
2883            copy=copy,
2884            **opts,
2885        )

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

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:
2985    def where(
2986        self,
2987        *expressions: t.Optional[ExpOrStr],
2988        append: bool = True,
2989        dialect: DialectType = None,
2990        copy: bool = True,
2991        **opts,
2992    ) -> Select:
2993        """
2994        Append to or set the WHERE expressions.
2995
2996        Example:
2997            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2998            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2999
3000        Args:
3001            *expressions: the SQL code strings to parse.
3002                If an `Expression` instance is passed, it will be used as-is.
3003                Multiple expressions are combined with an AND operator.
3004            append: if `True`, AND the new expressions to any existing expression.
3005                Otherwise, this resets the expression.
3006            dialect: the dialect used to parse the input expressions.
3007            copy: if `False`, modify this expression instance in-place.
3008            opts: other options to use to parse the input expressions.
3009
3010        Returns:
3011            Select: the modified expression.
3012        """
3013        return _apply_conjunction_builder(
3014            *expressions,
3015            instance=self,
3016            arg="where",
3017            append=append,
3018            into=Where,
3019            dialect=dialect,
3020            copy=copy,
3021            **opts,
3022        )

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:
3024    def having(
3025        self,
3026        *expressions: t.Optional[ExpOrStr],
3027        append: bool = True,
3028        dialect: DialectType = None,
3029        copy: bool = True,
3030        **opts,
3031    ) -> Select:
3032        """
3033        Append to or set the HAVING expressions.
3034
3035        Example:
3036            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3037            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3038
3039        Args:
3040            *expressions: the SQL code strings to parse.
3041                If an `Expression` instance is passed, it will be used as-is.
3042                Multiple expressions are combined with an AND operator.
3043            append: if `True`, AND the new expressions to any existing expression.
3044                Otherwise, this resets the expression.
3045            dialect: the dialect used to parse the input expressions.
3046            copy: if `False`, modify this expression instance in-place.
3047            opts: other options to use to parse the input expressions.
3048
3049        Returns:
3050            The modified Select expression.
3051        """
3052        return _apply_conjunction_builder(
3053            *expressions,
3054            instance=self,
3055            arg="having",
3056            append=append,
3057            into=Having,
3058            dialect=dialect,
3059            copy=copy,
3060            **opts,
3061        )

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

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:
3168    def lock(self, update: bool = True, copy: bool = True) -> Select:
3169        """
3170        Set the locking read mode for this expression.
3171
3172        Examples:
3173            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3174            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3175
3176            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3177            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3178
3179        Args:
3180            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3181            copy: if `False`, modify this expression instance in-place.
3182
3183        Returns:
3184            The modified expression.
3185        """
3186        inst = maybe_copy(self, copy)
3187        inst.set("locks", [Lock(update=update)])
3188
3189        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:
3191    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3192        """
3193        Set hints for this expression.
3194
3195        Examples:
3196            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3197            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3198
3199        Args:
3200            hints: The SQL code strings to parse as the hints.
3201                If an `Expression` instance is passed, it will be used as-is.
3202            dialect: The dialect used to parse the hints.
3203            copy: If `False`, modify this expression instance in-place.
3204
3205        Returns:
3206            The modified expression.
3207        """
3208        inst = maybe_copy(self, copy)
3209        inst.set(
3210            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3211        )
3212
3213        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):
3228class Subquery(DerivedTable, Unionable):
3229    arg_types = {
3230        "this": True,
3231        "alias": False,
3232        "with": False,
3233        **QUERY_MODIFIERS,
3234    }
3235
3236    def unnest(self):
3237        """
3238        Returns the first non subquery.
3239        """
3240        expression = self
3241        while isinstance(expression, Subquery):
3242            expression = expression.this
3243        return expression
3244
3245    @property
3246    def is_star(self) -> bool:
3247        return self.this.is_star
3248
3249    @property
3250    def output_name(self) -> str:
3251        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):
3236    def unnest(self):
3237        """
3238        Returns the first non subquery.
3239        """
3240        expression = self
3241        while isinstance(expression, Subquery):
3242            expression = expression.this
3243        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):
3254class TableSample(Expression):
3255    arg_types = {
3256        "this": False,
3257        "method": False,
3258        "bucket_numerator": False,
3259        "bucket_denominator": False,
3260        "bucket_field": False,
3261        "percent": False,
3262        "rows": False,
3263        "size": False,
3264        "seed": False,
3265        "kind": False,
3266    }
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):
3269class Tag(Expression):
3270    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3271
3272    arg_types = {
3273        "this": False,
3274        "prefix": False,
3275        "postfix": False,
3276    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3281class Pivot(Expression):
3282    arg_types = {
3283        "this": False,
3284        "alias": False,
3285        "expressions": True,
3286        "field": False,
3287        "unpivot": False,
3288        "using": False,
3289        "group": False,
3290        "columns": False,
3291    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3294class Window(Expression):
3295    arg_types = {
3296        "this": True,
3297        "partition_by": False,
3298        "order": False,
3299        "spec": False,
3300        "alias": False,
3301        "over": False,
3302        "first": False,
3303    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3306class WindowSpec(Expression):
3307    arg_types = {
3308        "kind": False,
3309        "start": False,
3310        "start_side": False,
3311        "end": False,
3312        "end_side": False,
3313    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3316class Where(Expression):
3317    pass
key = 'where'
class Star(Expression):
3320class Star(Expression):
3321    arg_types = {"except": False, "replace": False}
3322
3323    @property
3324    def name(self) -> str:
3325        return "*"
3326
3327    @property
3328    def output_name(self) -> str:
3329        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):
3332class Parameter(Condition):
3333    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3336class SessionParameter(Condition):
3337    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3340class Placeholder(Condition):
3341    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3344class Null(Condition):
3345    arg_types: t.Dict[str, t.Any] = {}
3346
3347    @property
3348    def name(self) -> str:
3349        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3352class Boolean(Condition):
3353    pass
key = 'boolean'
class DataTypeSize(Expression):
3356class DataTypeSize(Expression):
3357    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3360class DataType(Expression):
3361    arg_types = {
3362        "this": True,
3363        "expressions": False,
3364        "nested": False,
3365        "values": False,
3366        "prefix": False,
3367    }
3368
3369    class Type(AutoName):
3370        ARRAY = auto()
3371        BIGDECIMAL = auto()
3372        BIGINT = auto()
3373        BIGSERIAL = auto()
3374        BINARY = auto()
3375        BIT = auto()
3376        BOOLEAN = auto()
3377        CHAR = auto()
3378        DATE = auto()
3379        DATETIME = auto()
3380        DATETIME64 = auto()
3381        ENUM = auto()
3382        INT4RANGE = auto()
3383        INT4MULTIRANGE = auto()
3384        INT8RANGE = auto()
3385        INT8MULTIRANGE = auto()
3386        NUMRANGE = auto()
3387        NUMMULTIRANGE = auto()
3388        TSRANGE = auto()
3389        TSMULTIRANGE = auto()
3390        TSTZRANGE = auto()
3391        TSTZMULTIRANGE = auto()
3392        DATERANGE = auto()
3393        DATEMULTIRANGE = auto()
3394        DECIMAL = auto()
3395        DOUBLE = auto()
3396        FLOAT = auto()
3397        GEOGRAPHY = auto()
3398        GEOMETRY = auto()
3399        HLLSKETCH = auto()
3400        HSTORE = auto()
3401        IMAGE = auto()
3402        INET = auto()
3403        IPADDRESS = auto()
3404        IPPREFIX = auto()
3405        INT = auto()
3406        INT128 = auto()
3407        INT256 = auto()
3408        INTERVAL = auto()
3409        JSON = auto()
3410        JSONB = auto()
3411        LONGBLOB = auto()
3412        LONGTEXT = auto()
3413        MAP = auto()
3414        MEDIUMBLOB = auto()
3415        MEDIUMTEXT = auto()
3416        MONEY = auto()
3417        NCHAR = auto()
3418        NULL = auto()
3419        NULLABLE = auto()
3420        NVARCHAR = auto()
3421        OBJECT = auto()
3422        ROWVERSION = auto()
3423        SERIAL = auto()
3424        SET = auto()
3425        SMALLINT = auto()
3426        SMALLMONEY = auto()
3427        SMALLSERIAL = auto()
3428        STRUCT = auto()
3429        SUPER = auto()
3430        TEXT = auto()
3431        TIME = auto()
3432        TIMESTAMP = auto()
3433        TIMESTAMPTZ = auto()
3434        TIMESTAMPLTZ = auto()
3435        TINYINT = auto()
3436        UBIGINT = auto()
3437        UINT = auto()
3438        USMALLINT = auto()
3439        UTINYINT = auto()
3440        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3441        UINT128 = auto()
3442        UINT256 = auto()
3443        UNIQUEIDENTIFIER = auto()
3444        USERDEFINED = "USER-DEFINED"
3445        UUID = auto()
3446        VARBINARY = auto()
3447        VARCHAR = auto()
3448        VARIANT = auto()
3449        XML = auto()
3450
3451    TEXT_TYPES = {
3452        Type.CHAR,
3453        Type.NCHAR,
3454        Type.VARCHAR,
3455        Type.NVARCHAR,
3456        Type.TEXT,
3457    }
3458
3459    INTEGER_TYPES = {
3460        Type.INT,
3461        Type.TINYINT,
3462        Type.SMALLINT,
3463        Type.BIGINT,
3464        Type.INT128,
3465        Type.INT256,
3466    }
3467
3468    FLOAT_TYPES = {
3469        Type.FLOAT,
3470        Type.DOUBLE,
3471    }
3472
3473    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3474
3475    TEMPORAL_TYPES = {
3476        Type.TIME,
3477        Type.TIMESTAMP,
3478        Type.TIMESTAMPTZ,
3479        Type.TIMESTAMPLTZ,
3480        Type.DATE,
3481        Type.DATETIME,
3482        Type.DATETIME64,
3483    }
3484
3485    META_TYPES = {"UNKNOWN", "NULL"}
3486
3487    @classmethod
3488    def build(
3489        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3490    ) -> DataType:
3491        from sqlglot import parse_one
3492
3493        if isinstance(dtype, str):
3494            upper = dtype.upper()
3495            if upper in DataType.META_TYPES:
3496                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3497            else:
3498                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3499
3500            if data_type_exp is None:
3501                raise ValueError(f"Unparsable data type value: {dtype}")
3502        elif isinstance(dtype, DataType.Type):
3503            data_type_exp = DataType(this=dtype)
3504        elif isinstance(dtype, DataType):
3505            return dtype
3506        else:
3507            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3508
3509        return DataType(**{**data_type_exp.args, **kwargs})
3510
3511    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3512        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.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>}
INTEGER_TYPES = {<Type.TINYINT: 'TINYINT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.INT256: 'INT256'>, <Type.BIGINT: 'BIGINT'>, <Type.INT: 'INT'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.TINYINT: 'TINYINT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT: 'INT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT256: 'INT256'>, <Type.INT128: 'INT128'>}
TEMPORAL_TYPES = {<Type.DATETIME: 'DATETIME'>, <Type.TIME: 'TIME'>, <Type.DATETIME64: 'DATETIME64'>, <Type.DATE: 'DATE'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>}
META_TYPES = {'UNKNOWN', 'NULL'}
@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:
3487    @classmethod
3488    def build(
3489        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3490    ) -> DataType:
3491        from sqlglot import parse_one
3492
3493        if isinstance(dtype, str):
3494            upper = dtype.upper()
3495            if upper in DataType.META_TYPES:
3496                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3497            else:
3498                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3499
3500            if data_type_exp is None:
3501                raise ValueError(f"Unparsable data type value: {dtype}")
3502        elif isinstance(dtype, DataType.Type):
3503            data_type_exp = DataType(this=dtype)
3504        elif isinstance(dtype, DataType):
3505            return dtype
3506        else:
3507            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3508
3509        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3511    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3512        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3369    class Type(AutoName):
3370        ARRAY = auto()
3371        BIGDECIMAL = auto()
3372        BIGINT = auto()
3373        BIGSERIAL = auto()
3374        BINARY = auto()
3375        BIT = auto()
3376        BOOLEAN = auto()
3377        CHAR = auto()
3378        DATE = auto()
3379        DATETIME = auto()
3380        DATETIME64 = auto()
3381        ENUM = auto()
3382        INT4RANGE = auto()
3383        INT4MULTIRANGE = auto()
3384        INT8RANGE = auto()
3385        INT8MULTIRANGE = auto()
3386        NUMRANGE = auto()
3387        NUMMULTIRANGE = auto()
3388        TSRANGE = auto()
3389        TSMULTIRANGE = auto()
3390        TSTZRANGE = auto()
3391        TSTZMULTIRANGE = auto()
3392        DATERANGE = auto()
3393        DATEMULTIRANGE = auto()
3394        DECIMAL = auto()
3395        DOUBLE = auto()
3396        FLOAT = auto()
3397        GEOGRAPHY = auto()
3398        GEOMETRY = auto()
3399        HLLSKETCH = auto()
3400        HSTORE = auto()
3401        IMAGE = auto()
3402        INET = auto()
3403        IPADDRESS = auto()
3404        IPPREFIX = auto()
3405        INT = auto()
3406        INT128 = auto()
3407        INT256 = auto()
3408        INTERVAL = auto()
3409        JSON = auto()
3410        JSONB = auto()
3411        LONGBLOB = auto()
3412        LONGTEXT = auto()
3413        MAP = auto()
3414        MEDIUMBLOB = auto()
3415        MEDIUMTEXT = auto()
3416        MONEY = auto()
3417        NCHAR = auto()
3418        NULL = auto()
3419        NULLABLE = auto()
3420        NVARCHAR = auto()
3421        OBJECT = auto()
3422        ROWVERSION = auto()
3423        SERIAL = auto()
3424        SET = auto()
3425        SMALLINT = auto()
3426        SMALLMONEY = auto()
3427        SMALLSERIAL = auto()
3428        STRUCT = auto()
3429        SUPER = auto()
3430        TEXT = auto()
3431        TIME = auto()
3432        TIMESTAMP = auto()
3433        TIMESTAMPTZ = auto()
3434        TIMESTAMPLTZ = auto()
3435        TINYINT = auto()
3436        UBIGINT = auto()
3437        UINT = auto()
3438        USMALLINT = auto()
3439        UTINYINT = auto()
3440        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3441        UINT128 = auto()
3442        UINT256 = auto()
3443        UNIQUEIDENTIFIER = auto()
3444        USERDEFINED = "USER-DEFINED"
3445        UUID = auto()
3446        VARBINARY = auto()
3447        VARCHAR = auto()
3448        VARIANT = auto()
3449        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):
3516class PseudoType(Expression):
3517    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3521class SubqueryPredicate(Predicate):
3522    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3525class All(SubqueryPredicate):
3526    pass
key = 'all'
class Any(SubqueryPredicate):
3529class Any(SubqueryPredicate):
3530    pass
key = 'any'
class Exists(SubqueryPredicate):
3533class Exists(SubqueryPredicate):
3534    pass
key = 'exists'
class Command(Expression):
3539class Command(Expression):
3540    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3543class Transaction(Expression):
3544    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3547class Commit(Expression):
3548    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3551class Rollback(Expression):
3552    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3555class AlterTable(Expression):
3556    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3559class AddConstraint(Expression):
3560    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3563class DropPartition(Expression):
3564    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3568class Binary(Condition):
3569    arg_types = {"this": True, "expression": True}
3570
3571    @property
3572    def left(self):
3573        return self.this
3574
3575    @property
3576    def right(self):
3577        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3580class Add(Binary):
3581    pass
key = 'add'
class Connector(Binary):
3584class Connector(Binary):
3585    pass
key = 'connector'
class And(Connector):
3588class And(Connector):
3589    pass
key = 'and'
class Or(Connector):
3592class Or(Connector):
3593    pass
key = 'or'
class BitwiseAnd(Binary):
3596class BitwiseAnd(Binary):
3597    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3600class BitwiseLeftShift(Binary):
3601    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3604class BitwiseOr(Binary):
3605    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3608class BitwiseRightShift(Binary):
3609    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3612class BitwiseXor(Binary):
3613    pass
key = 'bitwisexor'
class Div(Binary):
3616class Div(Binary):
3617    pass
key = 'div'
class Overlaps(Binary):
3620class Overlaps(Binary):
3621    pass
key = 'overlaps'
class Dot(Binary):
3624class Dot(Binary):
3625    @property
3626    def name(self) -> str:
3627        return self.expression.name
3628
3629    @property
3630    def output_name(self) -> str:
3631        return self.name
3632
3633    @classmethod
3634    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3635        """Build a Dot object with a sequence of expressions."""
3636        if len(expressions) < 2:
3637            raise ValueError(f"Dot requires >= 2 expressions.")
3638
3639        a, b, *expressions = expressions
3640        dot = Dot(this=a, expression=b)
3641
3642        for expression in expressions:
3643            dot = Dot(this=dot, expression=expression)
3644
3645        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:
3633    @classmethod
3634    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3635        """Build a Dot object with a sequence of expressions."""
3636        if len(expressions) < 2:
3637            raise ValueError(f"Dot requires >= 2 expressions.")
3638
3639        a, b, *expressions = expressions
3640        dot = Dot(this=a, expression=b)
3641
3642        for expression in expressions:
3643            dot = Dot(this=dot, expression=expression)
3644
3645        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3648class DPipe(Binary):
3649    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3652class SafeDPipe(DPipe):
3653    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3656class EQ(Binary, Predicate):
3657    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3660class NullSafeEQ(Binary, Predicate):
3661    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3664class NullSafeNEQ(Binary, Predicate):
3665    pass
key = 'nullsafeneq'
class Distance(Binary):
3668class Distance(Binary):
3669    pass
key = 'distance'
class Escape(Binary):
3672class Escape(Binary):
3673    pass
key = 'escape'
class Glob(Binary, Predicate):
3676class Glob(Binary, Predicate):
3677    pass
key = 'glob'
class GT(Binary, Predicate):
3680class GT(Binary, Predicate):
3681    pass
key = 'gt'
class GTE(Binary, Predicate):
3684class GTE(Binary, Predicate):
3685    pass
key = 'gte'
class ILike(Binary, Predicate):
3688class ILike(Binary, Predicate):
3689    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3692class ILikeAny(Binary, Predicate):
3693    pass
key = 'ilikeany'
class IntDiv(Binary):
3696class IntDiv(Binary):
3697    pass
key = 'intdiv'
class Is(Binary, Predicate):
3700class Is(Binary, Predicate):
3701    pass
key = 'is'
class Kwarg(Binary):
3704class Kwarg(Binary):
3705    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3708class Like(Binary, Predicate):
3709    pass
key = 'like'
class LikeAny(Binary, Predicate):
3712class LikeAny(Binary, Predicate):
3713    pass
key = 'likeany'
class LT(Binary, Predicate):
3716class LT(Binary, Predicate):
3717    pass
key = 'lt'
class LTE(Binary, Predicate):
3720class LTE(Binary, Predicate):
3721    pass
key = 'lte'
class Mod(Binary):
3724class Mod(Binary):
3725    pass
key = 'mod'
class Mul(Binary):
3728class Mul(Binary):
3729    pass
key = 'mul'
class NEQ(Binary, Predicate):
3732class NEQ(Binary, Predicate):
3733    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3736class SimilarTo(Binary, Predicate):
3737    pass
key = 'similarto'
class Slice(Binary):
3740class Slice(Binary):
3741    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3744class Sub(Binary):
3745    pass
key = 'sub'
class ArrayOverlaps(Binary):
3748class ArrayOverlaps(Binary):
3749    pass
key = 'arrayoverlaps'
class Unary(Condition):
3754class Unary(Condition):
3755    pass
key = 'unary'
class BitwiseNot(Unary):
3758class BitwiseNot(Unary):
3759    pass
key = 'bitwisenot'
class Not(Unary):
3762class Not(Unary):
3763    pass
key = 'not'
class Paren(Unary):
3766class Paren(Unary):
3767    arg_types = {"this": True, "with": False}
3768
3769    @property
3770    def output_name(self) -> str:
3771        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):
3774class Neg(Unary):
3775    pass
key = 'neg'
class Alias(Expression):
3778class Alias(Expression):
3779    arg_types = {"this": True, "alias": False}
3780
3781    @property
3782    def output_name(self) -> str:
3783        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):
3786class Aliases(Expression):
3787    arg_types = {"this": True, "expressions": True}
3788
3789    @property
3790    def aliases(self):
3791        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3794class AtTimeZone(Expression):
3795    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3798class Between(Predicate):
3799    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3802class Bracket(Condition):
3803    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3806class SafeBracket(Bracket):
3807    """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):
3810class Distinct(Expression):
3811    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3814class In(Predicate):
3815    arg_types = {
3816        "this": True,
3817        "expressions": False,
3818        "query": False,
3819        "unnest": False,
3820        "field": False,
3821        "is_global": False,
3822    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3825class TimeUnit(Expression):
3826    """Automatically converts unit arg into a var."""
3827
3828    arg_types = {"unit": False}
3829
3830    def __init__(self, **args):
3831        unit = args.get("unit")
3832        if isinstance(unit, (Column, Literal)):
3833            args["unit"] = Var(this=unit.name)
3834        elif isinstance(unit, Week):
3835            unit.set("this", Var(this=unit.this.name))
3836
3837        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3830    def __init__(self, **args):
3831        unit = args.get("unit")
3832        if isinstance(unit, (Column, Literal)):
3833            args["unit"] = Var(this=unit.name)
3834        elif isinstance(unit, Week):
3835            unit.set("this", Var(this=unit.this.name))
3836
3837        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3840class Interval(TimeUnit):
3841    arg_types = {"this": False, "unit": False}
3842
3843    @property
3844    def unit(self) -> t.Optional[Var]:
3845        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3848class IgnoreNulls(Expression):
3849    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3852class RespectNulls(Expression):
3853    pass
key = 'respectnulls'
class Func(Condition):
3857class Func(Condition):
3858    """
3859    The base class for all function expressions.
3860
3861    Attributes:
3862        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3863            treated as a variable length argument and the argument's value will be stored as a list.
3864        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3865            for this function expression. These values are used to map this node to a name during parsing
3866            as well as to provide the function's name during SQL string generation. By default the SQL
3867            name is set to the expression's class name transformed to snake case.
3868    """
3869
3870    is_var_len_args = False
3871
3872    @classmethod
3873    def from_arg_list(cls, args):
3874        if cls.is_var_len_args:
3875            all_arg_keys = list(cls.arg_types)
3876            # If this function supports variable length argument treat the last argument as such.
3877            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3878            num_non_var = len(non_var_len_arg_keys)
3879
3880            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3881            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3882        else:
3883            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3884
3885        return cls(**args_dict)
3886
3887    @classmethod
3888    def sql_names(cls):
3889        if cls is Func:
3890            raise NotImplementedError(
3891                "SQL name is only supported by concrete function implementations"
3892            )
3893        if "_sql_names" not in cls.__dict__:
3894            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3895        return cls._sql_names
3896
3897    @classmethod
3898    def sql_name(cls):
3899        return cls.sql_names()[0]
3900
3901    @classmethod
3902    def default_parser_mappings(cls):
3903        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):
3872    @classmethod
3873    def from_arg_list(cls, args):
3874        if cls.is_var_len_args:
3875            all_arg_keys = list(cls.arg_types)
3876            # If this function supports variable length argument treat the last argument as such.
3877            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3878            num_non_var = len(non_var_len_arg_keys)
3879
3880            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3881            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3882        else:
3883            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3884
3885        return cls(**args_dict)
@classmethod
def sql_names(cls):
3887    @classmethod
3888    def sql_names(cls):
3889        if cls is Func:
3890            raise NotImplementedError(
3891                "SQL name is only supported by concrete function implementations"
3892            )
3893        if "_sql_names" not in cls.__dict__:
3894            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3895        return cls._sql_names
@classmethod
def sql_name(cls):
3897    @classmethod
3898    def sql_name(cls):
3899        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3901    @classmethod
3902    def default_parser_mappings(cls):
3903        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3906class AggFunc(Func):
3907    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3910class ParameterizedAgg(AggFunc):
3911    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3914class Abs(Func):
3915    pass
key = 'abs'
class Transform(Func):
3919class Transform(Func):
3920    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
3923class Anonymous(Func):
3924    arg_types = {"this": True, "expressions": False}
3925    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3930class Hll(AggFunc):
3931    arg_types = {"this": True, "expressions": False}
3932    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3935class ApproxDistinct(AggFunc):
3936    arg_types = {"this": True, "accuracy": False}
3937    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3940class Array(Func):
3941    arg_types = {"expressions": False}
3942    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3946class ToChar(Func):
3947    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3950class GenerateSeries(Func):
3951    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3954class ArrayAgg(AggFunc):
3955    pass
key = 'arrayagg'
class ArrayAll(Func):
3958class ArrayAll(Func):
3959    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3962class ArrayAny(Func):
3963    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3966class ArrayConcat(Func):
3967    arg_types = {"this": True, "expressions": False}
3968    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3971class ArrayContains(Binary, Func):
3972    pass
key = 'arraycontains'
class ArrayContained(Binary):
3975class ArrayContained(Binary):
3976    pass
key = 'arraycontained'
class ArrayFilter(Func):
3979class ArrayFilter(Func):
3980    arg_types = {"this": True, "expression": True}
3981    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3984class ArrayJoin(Func):
3985    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3988class ArraySize(Func):
3989    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3992class ArraySort(Func):
3993    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3996class ArraySum(Func):
3997    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4000class ArrayUnionAgg(AggFunc):
4001    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4004class Avg(AggFunc):
4005    pass
key = 'avg'
class AnyValue(AggFunc):
4008class AnyValue(AggFunc):
4009    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
4012class Case(Func):
4013    arg_types = {"this": False, "ifs": True, "default": False}
4014
4015    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4016        instance = maybe_copy(self, copy)
4017        instance.append(
4018            "ifs",
4019            If(
4020                this=maybe_parse(condition, copy=copy, **opts),
4021                true=maybe_parse(then, copy=copy, **opts),
4022            ),
4023        )
4024        return instance
4025
4026    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4027        instance = maybe_copy(self, copy)
4028        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4029        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:
4015    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4016        instance = maybe_copy(self, copy)
4017        instance.append(
4018            "ifs",
4019            If(
4020                this=maybe_parse(condition, copy=copy, **opts),
4021                true=maybe_parse(then, copy=copy, **opts),
4022            ),
4023        )
4024        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4026    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4027        instance = maybe_copy(self, copy)
4028        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4029        return instance
key = 'case'
class Cast(Func):
4032class Cast(Func):
4033    arg_types = {"this": True, "to": True, "format": False}
4034
4035    @property
4036    def name(self) -> str:
4037        return self.this.name
4038
4039    @property
4040    def to(self) -> DataType:
4041        return self.args["to"]
4042
4043    @property
4044    def output_name(self) -> str:
4045        return self.name
4046
4047    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4048        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:
4047    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4048        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
4051class CastToStrType(Func):
4052    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
4055class Collate(Binary):
4056    pass
key = 'collate'
class TryCast(Cast):
4059class TryCast(Cast):
4060    pass
key = 'trycast'
class Ceil(Func):
4063class Ceil(Func):
4064    arg_types = {"this": True, "decimals": False}
4065    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4068class Coalesce(Func):
4069    arg_types = {"this": True, "expressions": False}
4070    is_var_len_args = True
4071    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4074class Concat(Func):
4075    arg_types = {"expressions": True}
4076    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4079class SafeConcat(Concat):
4080    pass
key = 'safeconcat'
class ConcatWs(Concat):
4083class ConcatWs(Concat):
4084    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4087class Count(AggFunc):
4088    arg_types = {"this": False, "expressions": False}
4089    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4092class CountIf(AggFunc):
4093    pass
key = 'countif'
class CurrentDate(Func):
4096class CurrentDate(Func):
4097    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4100class CurrentDatetime(Func):
4101    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4104class CurrentTime(Func):
4105    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4108class CurrentTimestamp(Func):
4109    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4112class CurrentUser(Func):
4113    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4116class DateAdd(Func, TimeUnit):
4117    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4120class DateSub(Func, TimeUnit):
4121    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4124class DateDiff(Func, TimeUnit):
4125    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4126    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4129class DateTrunc(Func):
4130    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4133class DatetimeAdd(Func, TimeUnit):
4134    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4137class DatetimeSub(Func, TimeUnit):
4138    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4141class DatetimeDiff(Func, TimeUnit):
4142    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4145class DatetimeTrunc(Func, TimeUnit):
4146    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4149class DayOfWeek(Func):
4150    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4153class DayOfMonth(Func):
4154    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4157class DayOfYear(Func):
4158    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4161class WeekOfYear(Func):
4162    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4165class MonthsBetween(Func):
4166    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4169class LastDateOfMonth(Func):
4170    pass
key = 'lastdateofmonth'
class Extract(Func):
4173class Extract(Func):
4174    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4177class TimestampAdd(Func, TimeUnit):
4178    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4181class TimestampSub(Func, TimeUnit):
4182    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4185class TimestampDiff(Func, TimeUnit):
4186    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4189class TimestampTrunc(Func, TimeUnit):
4190    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4193class TimeAdd(Func, TimeUnit):
4194    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4197class TimeSub(Func, TimeUnit):
4198    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4201class TimeDiff(Func, TimeUnit):
4202    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4205class TimeTrunc(Func, TimeUnit):
4206    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4209class DateFromParts(Func):
4210    _sql_names = ["DATEFROMPARTS"]
4211    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4214class DateStrToDate(Func):
4215    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4218class DateToDateStr(Func):
4219    pass
key = 'datetodatestr'
class DateToDi(Func):
4222class DateToDi(Func):
4223    pass
key = 'datetodi'
class Date(Func):
4227class Date(Func):
4228    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4231class Day(Func):
4232    pass
key = 'day'
class Decode(Func):
4235class Decode(Func):
4236    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4239class DiToDate(Func):
4240    pass
key = 'ditodate'
class Encode(Func):
4243class Encode(Func):
4244    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4247class Exp(Func):
4248    pass
key = 'exp'
class Explode(Func):
4251class Explode(Func):
4252    pass
key = 'explode'
class Floor(Func):
4255class Floor(Func):
4256    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4259class FromBase64(Func):
4260    pass
key = 'frombase64'
class ToBase64(Func):
4263class ToBase64(Func):
4264    pass
key = 'tobase64'
class Greatest(Func):
4267class Greatest(Func):
4268    arg_types = {"this": True, "expressions": False}
4269    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4272class GroupConcat(Func):
4273    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4276class Hex(Func):
4277    pass
key = 'hex'
class Xor(Connector, Func):
4280class Xor(Connector, Func):
4281    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4284class If(Func):
4285    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4288class Initcap(Func):
4289    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4292class IsNan(Func):
4293    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class JSONKeyValue(Expression):
4296class JSONKeyValue(Expression):
4297    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4300class JSONObject(Func):
4301    arg_types = {
4302        "expressions": False,
4303        "null_handling": False,
4304        "unique_keys": False,
4305        "return_type": False,
4306        "format_json": False,
4307        "encoding": False,
4308    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4311class OpenJSONColumnDef(Expression):
4312    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):
4315class OpenJSON(Func):
4316    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4319class JSONBContains(Binary):
4320    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4323class JSONExtract(Binary, Func):
4324    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4327class JSONExtractScalar(JSONExtract):
4328    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4331class JSONBExtract(JSONExtract):
4332    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4335class JSONBExtractScalar(JSONExtract):
4336    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4339class JSONFormat(Func):
4340    arg_types = {"this": False, "options": False}
4341    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4345class JSONArrayContains(Binary, Predicate, Func):
4346    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4349class Least(Func):
4350    arg_types = {"this": True, "expressions": False}
4351    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4354class Left(Func):
4355    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4362class Length(Func):
4363    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4366class Levenshtein(Func):
4367    arg_types = {
4368        "this": True,
4369        "expression": False,
4370        "ins_cost": False,
4371        "del_cost": False,
4372        "sub_cost": False,
4373    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4376class Ln(Func):
4377    pass
key = 'ln'
class Log(Func):
4380class Log(Func):
4381    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4384class Log2(Func):
4385    pass
key = 'log2'
class Log10(Func):
4388class Log10(Func):
4389    pass
key = 'log10'
class LogicalOr(AggFunc):
4392class LogicalOr(AggFunc):
4393    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4396class LogicalAnd(AggFunc):
4397    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4400class Lower(Func):
4401    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4404class Map(Func):
4405    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4408class MapFromEntries(Func):
4409    pass
key = 'mapfromentries'
class StarMap(Func):
4412class StarMap(Func):
4413    pass
key = 'starmap'
class VarMap(Func):
4416class VarMap(Func):
4417    arg_types = {"keys": True, "values": True}
4418    is_var_len_args = True
4419
4420    @property
4421    def keys(self) -> t.List[Expression]:
4422        return self.args["keys"].expressions
4423
4424    @property
4425    def values(self) -> t.List[Expression]:
4426        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4430class MatchAgainst(Func):
4431    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4434class Max(AggFunc):
4435    arg_types = {"this": True, "expressions": False}
4436    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4439class MD5(Func):
4440    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4444class MD5Digest(Func):
4445    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4448class Min(AggFunc):
4449    arg_types = {"this": True, "expressions": False}
4450    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4453class Month(Func):
4454    pass
key = 'month'
class Nvl2(Func):
4457class Nvl2(Func):
4458    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4461class Posexplode(Func):
4462    pass
key = 'posexplode'
class Pow(Binary, Func):
4465class Pow(Binary, Func):
4466    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4469class PercentileCont(AggFunc):
4470    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4473class PercentileDisc(AggFunc):
4474    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4477class Quantile(AggFunc):
4478    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4481class ApproxQuantile(Quantile):
4482    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):
4485class RangeN(Func):
4486    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4489class ReadCSV(Func):
4490    _sql_names = ["READ_CSV"]
4491    is_var_len_args = True
4492    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4495class Reduce(Func):
4496    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):
4499class RegexpExtract(Func):
4500    arg_types = {
4501        "this": True,
4502        "expression": True,
4503        "position": False,
4504        "occurrence": False,
4505        "parameters": False,
4506        "group": False,
4507    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4510class RegexpReplace(Func):
4511    arg_types = {
4512        "this": True,
4513        "expression": True,
4514        "replacement": True,
4515        "position": False,
4516        "occurrence": False,
4517        "parameters": False,
4518    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4521class RegexpLike(Binary, Func):
4522    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4525class RegexpILike(Func):
4526    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4531class RegexpSplit(Func):
4532    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4535class Repeat(Func):
4536    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4539class Round(Func):
4540    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4543class RowNumber(Func):
4544    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4547class SafeDivide(Func):
4548    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4551class SetAgg(AggFunc):
4552    pass
key = 'setagg'
class SHA(Func):
4555class SHA(Func):
4556    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4559class SHA2(Func):
4560    _sql_names = ["SHA2"]
4561    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4564class SortArray(Func):
4565    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4568class Split(Func):
4569    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4574class Substring(Func):
4575    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4578class StandardHash(Func):
4579    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4582class StartsWith(Func):
4583    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4584    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4587class StrPosition(Func):
4588    arg_types = {
4589        "this": True,
4590        "substr": True,
4591        "position": False,
4592        "instance": False,
4593    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4596class StrToDate(Func):
4597    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4600class StrToTime(Func):
4601    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4606class StrToUnix(Func):
4607    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4610class NumberToStr(Func):
4611    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4614class FromBase(Func):
4615    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4618class Struct(Func):
4619    arg_types = {"expressions": True}
4620    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4623class StructExtract(Func):
4624    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4627class Sum(AggFunc):
4628    pass
key = 'sum'
class Sqrt(Func):
4631class Sqrt(Func):
4632    pass
key = 'sqrt'
class Stddev(AggFunc):
4635class Stddev(AggFunc):
4636    pass
key = 'stddev'
class StddevPop(AggFunc):
4639class StddevPop(AggFunc):
4640    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4643class StddevSamp(AggFunc):
4644    pass
key = 'stddevsamp'
class TimeToStr(Func):
4647class TimeToStr(Func):
4648    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4651class TimeToTimeStr(Func):
4652    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4655class TimeToUnix(Func):
4656    pass
key = 'timetounix'
class TimeStrToDate(Func):
4659class TimeStrToDate(Func):
4660    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4663class TimeStrToTime(Func):
4664    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4667class TimeStrToUnix(Func):
4668    pass
key = 'timestrtounix'
class Trim(Func):
4671class Trim(Func):
4672    arg_types = {
4673        "this": True,
4674        "expression": False,
4675        "position": False,
4676        "collation": False,
4677    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4680class TsOrDsAdd(Func, TimeUnit):
4681    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4684class TsOrDsToDateStr(Func):
4685    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4688class TsOrDsToDate(Func):
4689    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4692class TsOrDiToDi(Func):
4693    pass
key = 'tsorditodi'
class Unhex(Func):
4696class Unhex(Func):
4697    pass
key = 'unhex'
class UnixToStr(Func):
4700class UnixToStr(Func):
4701    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4706class UnixToTime(Func):
4707    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4708
4709    SECONDS = Literal.string("seconds")
4710    MILLIS = Literal.string("millis")
4711    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):
4714class UnixToTimeStr(Func):
4715    pass
key = 'unixtotimestr'
class Upper(Func):
4718class Upper(Func):
4719    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4722class Variance(AggFunc):
4723    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4726class VariancePop(AggFunc):
4727    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4730class Week(Func):
4731    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4734class XMLTable(Func):
4735    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):
4738class Year(Func):
4739    pass
key = 'year'
class Use(Expression):
4742class Use(Expression):
4743    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4746class Merge(Expression):
4747    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):
4750class When(Func):
4751    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):
4756class NextValueFor(Func):
4757    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:
4794def maybe_parse(
4795    sql_or_expression: ExpOrStr,
4796    *,
4797    into: t.Optional[IntoType] = None,
4798    dialect: DialectType = None,
4799    prefix: t.Optional[str] = None,
4800    copy: bool = False,
4801    **opts,
4802) -> Expression:
4803    """Gracefully handle a possible string or expression.
4804
4805    Example:
4806        >>> maybe_parse("1")
4807        (LITERAL this: 1, is_string: False)
4808        >>> maybe_parse(to_identifier("x"))
4809        (IDENTIFIER this: x, quoted: False)
4810
4811    Args:
4812        sql_or_expression: the SQL code string or an expression
4813        into: the SQLGlot Expression to parse into
4814        dialect: the dialect used to parse the input expressions (in the case that an
4815            input expression is a SQL string).
4816        prefix: a string to prefix the sql with before it gets parsed
4817            (automatically includes a space)
4818        copy: whether or not to copy the expression.
4819        **opts: other options to use to parse the input expressions (again, in the case
4820            that an input expression is a SQL string).
4821
4822    Returns:
4823        Expression: the parsed or given expression.
4824    """
4825    if isinstance(sql_or_expression, Expression):
4826        if copy:
4827            return sql_or_expression.copy()
4828        return sql_or_expression
4829
4830    if sql_or_expression is None:
4831        raise ParseError(f"SQL cannot be None")
4832
4833    import sqlglot
4834
4835    sql = str(sql_or_expression)
4836    if prefix:
4837        sql = f"{prefix} {sql}"
4838
4839    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:
4842def maybe_copy(instance: E, copy: bool = True) -> E:
4843    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:
5023def union(
5024    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5025) -> Union:
5026    """
5027    Initializes a syntax tree from one UNION expression.
5028
5029    Example:
5030        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5031        'SELECT * FROM foo UNION SELECT * FROM bla'
5032
5033    Args:
5034        left: the SQL code string corresponding to the left-hand side.
5035            If an `Expression` instance is passed, it will be used as-is.
5036        right: the SQL code string corresponding to the right-hand side.
5037            If an `Expression` instance is passed, it will be used as-is.
5038        distinct: set the DISTINCT flag if and only if this is true.
5039        dialect: the dialect used to parse the input expression.
5040        opts: other options to use to parse the input expressions.
5041
5042    Returns:
5043        The new Union instance.
5044    """
5045    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5046    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5047
5048    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:
5051def intersect(
5052    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5053) -> Intersect:
5054    """
5055    Initializes a syntax tree from one INTERSECT expression.
5056
5057    Example:
5058        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5059        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5060
5061    Args:
5062        left: the SQL code string corresponding to the left-hand side.
5063            If an `Expression` instance is passed, it will be used as-is.
5064        right: the SQL code string corresponding to the right-hand side.
5065            If an `Expression` instance is passed, it will be used as-is.
5066        distinct: set the DISTINCT flag if and only if this is true.
5067        dialect: the dialect used to parse the input expression.
5068        opts: other options to use to parse the input expressions.
5069
5070    Returns:
5071        The new Intersect instance.
5072    """
5073    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5074    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5075
5076    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:
5079def except_(
5080    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5081) -> Except:
5082    """
5083    Initializes a syntax tree from one EXCEPT expression.
5084
5085    Example:
5086        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5087        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5088
5089    Args:
5090        left: the SQL code string corresponding to the left-hand side.
5091            If an `Expression` instance is passed, it will be used as-is.
5092        right: the SQL code string corresponding to the right-hand side.
5093            If an `Expression` instance is passed, it will be used as-is.
5094        distinct: set the DISTINCT flag if and only if this is true.
5095        dialect: the dialect used to parse the input expression.
5096        opts: other options to use to parse the input expressions.
5097
5098    Returns:
5099        The new Except instance.
5100    """
5101    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5102    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5103
5104    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:
5107def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5108    """
5109    Initializes a syntax tree from one or multiple SELECT expressions.
5110
5111    Example:
5112        >>> select("col1", "col2").from_("tbl").sql()
5113        'SELECT col1, col2 FROM tbl'
5114
5115    Args:
5116        *expressions: the SQL code string to parse as the expressions of a
5117            SELECT statement. If an Expression instance is passed, this is used as-is.
5118        dialect: the dialect used to parse the input expressions (in the case that an
5119            input expression is a SQL string).
5120        **opts: other options to use to parse the input expressions (again, in the case
5121            that an input expression is a SQL string).
5122
5123    Returns:
5124        Select: the syntax tree for the SELECT statement.
5125    """
5126    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:
5129def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5130    """
5131    Initializes a syntax tree from a FROM expression.
5132
5133    Example:
5134        >>> from_("tbl").select("col1", "col2").sql()
5135        'SELECT col1, col2 FROM tbl'
5136
5137    Args:
5138        *expression: the SQL code string to parse as the FROM expressions of a
5139            SELECT statement. If an Expression instance is passed, this is used as-is.
5140        dialect: the dialect used to parse the input expression (in the case that the
5141            input expression is a SQL string).
5142        **opts: other options to use to parse the input expressions (again, in the case
5143            that the input expression is a SQL string).
5144
5145    Returns:
5146        Select: the syntax tree for the SELECT statement.
5147    """
5148    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:
5151def update(
5152    table: str | Table,
5153    properties: dict,
5154    where: t.Optional[ExpOrStr] = None,
5155    from_: t.Optional[ExpOrStr] = None,
5156    dialect: DialectType = None,
5157    **opts,
5158) -> Update:
5159    """
5160    Creates an update statement.
5161
5162    Example:
5163        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5164        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5165
5166    Args:
5167        *properties: dictionary of properties to set which are
5168            auto converted to sql objects eg None -> NULL
5169        where: sql conditional parsed into a WHERE statement
5170        from_: sql statement parsed into a FROM statement
5171        dialect: the dialect used to parse the input expressions.
5172        **opts: other options to use to parse the input expressions.
5173
5174    Returns:
5175        Update: the syntax tree for the UPDATE statement.
5176    """
5177    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5178    update_expr.set(
5179        "expressions",
5180        [
5181            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5182            for k, v in properties.items()
5183        ],
5184    )
5185    if from_:
5186        update_expr.set(
5187            "from",
5188            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5189        )
5190    if isinstance(where, Condition):
5191        where = Where(this=where)
5192    if where:
5193        update_expr.set(
5194            "where",
5195            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5196        )
5197    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:
5200def delete(
5201    table: ExpOrStr,
5202    where: t.Optional[ExpOrStr] = None,
5203    returning: t.Optional[ExpOrStr] = None,
5204    dialect: DialectType = None,
5205    **opts,
5206) -> Delete:
5207    """
5208    Builds a delete statement.
5209
5210    Example:
5211        >>> delete("my_table", where="id > 1").sql()
5212        'DELETE FROM my_table WHERE id > 1'
5213
5214    Args:
5215        where: sql conditional parsed into a WHERE statement
5216        returning: sql conditional parsed into a RETURNING statement
5217        dialect: the dialect used to parse the input expressions.
5218        **opts: other options to use to parse the input expressions.
5219
5220    Returns:
5221        Delete: the syntax tree for the DELETE statement.
5222    """
5223    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5224    if where:
5225        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5226    if returning:
5227        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5228    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:
5231def insert(
5232    expression: ExpOrStr,
5233    into: ExpOrStr,
5234    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5235    overwrite: t.Optional[bool] = None,
5236    dialect: DialectType = None,
5237    copy: bool = True,
5238    **opts,
5239) -> Insert:
5240    """
5241    Builds an INSERT statement.
5242
5243    Example:
5244        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5245        'INSERT INTO tbl VALUES (1, 2, 3)'
5246
5247    Args:
5248        expression: the sql string or expression of the INSERT statement
5249        into: the tbl to insert data to.
5250        columns: optionally the table's column names.
5251        overwrite: whether to INSERT OVERWRITE or not.
5252        dialect: the dialect used to parse the input expressions.
5253        copy: whether or not to copy the expression.
5254        **opts: other options to use to parse the input expressions.
5255
5256    Returns:
5257        Insert: the syntax tree for the INSERT statement.
5258    """
5259    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5260    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5261
5262    if columns:
5263        this = _apply_list_builder(
5264            *columns,
5265            instance=Schema(this=this),
5266            arg="expressions",
5267            into=Identifier,
5268            copy=False,
5269            dialect=dialect,
5270            **opts,
5271        )
5272
5273    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:
5276def condition(
5277    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5278) -> Condition:
5279    """
5280    Initialize a logical condition expression.
5281
5282    Example:
5283        >>> condition("x=1").sql()
5284        'x = 1'
5285
5286        This is helpful for composing larger logical syntax trees:
5287        >>> where = condition("x=1")
5288        >>> where = where.and_("y=1")
5289        >>> Select().from_("tbl").select("*").where(where).sql()
5290        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5291
5292    Args:
5293        *expression: the SQL code string to parse.
5294            If an Expression instance is passed, this is used as-is.
5295        dialect: the dialect used to parse the input expression (in the case that the
5296            input expression is a SQL string).
5297        copy: Whether or not to copy `expression` (only applies to expressions).
5298        **opts: other options to use to parse the input expressions (again, in the case
5299            that the input expression is a SQL string).
5300
5301    Returns:
5302        The new Condition instance
5303    """
5304    return maybe_parse(
5305        expression,
5306        into=Condition,
5307        dialect=dialect,
5308        copy=copy,
5309        **opts,
5310    )

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:
5313def and_(
5314    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5315) -> Condition:
5316    """
5317    Combine multiple conditions with an AND logical operator.
5318
5319    Example:
5320        >>> and_("x=1", and_("y=1", "z=1")).sql()
5321        'x = 1 AND (y = 1 AND z = 1)'
5322
5323    Args:
5324        *expressions: the SQL code strings to parse.
5325            If an Expression instance is passed, this is used as-is.
5326        dialect: the dialect used to parse the input expression.
5327        copy: whether or not to copy `expressions` (only applies to Expressions).
5328        **opts: other options to use to parse the input expressions.
5329
5330    Returns:
5331        And: the new condition
5332    """
5333    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:
5336def or_(
5337    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5338) -> Condition:
5339    """
5340    Combine multiple conditions with an OR logical operator.
5341
5342    Example:
5343        >>> or_("x=1", or_("y=1", "z=1")).sql()
5344        'x = 1 OR (y = 1 OR z = 1)'
5345
5346    Args:
5347        *expressions: the SQL code strings to parse.
5348            If an Expression instance is passed, this is used as-is.
5349        dialect: the dialect used to parse the input expression.
5350        copy: whether or not to copy `expressions` (only applies to Expressions).
5351        **opts: other options to use to parse the input expressions.
5352
5353    Returns:
5354        Or: the new condition
5355    """
5356    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:
5359def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5360    """
5361    Wrap a condition with a NOT operator.
5362
5363    Example:
5364        >>> not_("this_suit='black'").sql()
5365        "NOT this_suit = 'black'"
5366
5367    Args:
5368        expression: the SQL code string 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 to copy the expression or not.
5372        **opts: other options to use to parse the input expressions.
5373
5374    Returns:
5375        The new condition.
5376    """
5377    this = condition(
5378        expression,
5379        dialect=dialect,
5380        copy=copy,
5381        **opts,
5382    )
5383    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:
5386def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5387    """
5388    Wrap an expression in parentheses.
5389
5390    Example:
5391        >>> paren("5 + 3").sql()
5392        '(5 + 3)'
5393
5394    Args:
5395        expression: the SQL code string to parse.
5396            If an Expression instance is passed, this is used as-is.
5397        copy: whether to copy the expression or not.
5398
5399    Returns:
5400        The wrapped expression.
5401    """
5402    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):
5420def to_identifier(name, quoted=None, copy=True):
5421    """Builds an identifier.
5422
5423    Args:
5424        name: The name to turn into an identifier.
5425        quoted: Whether or not force quote the identifier.
5426        copy: Whether or not to copy a passed in Identefier node.
5427
5428    Returns:
5429        The identifier ast node.
5430    """
5431
5432    if name is None:
5433        return None
5434
5435    if isinstance(name, Identifier):
5436        identifier = maybe_copy(name, copy)
5437    elif isinstance(name, str):
5438        identifier = Identifier(
5439            this=name,
5440            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5441        )
5442    else:
5443        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5444    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:
5450def to_interval(interval: str | Literal) -> Interval:
5451    """Builds an interval expression from a string like '1 day' or '5 months'."""
5452    if isinstance(interval, Literal):
5453        if not interval.is_string:
5454            raise ValueError("Invalid interval string.")
5455
5456        interval = interval.this
5457
5458    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5459
5460    if not interval_parts:
5461        raise ValueError("Invalid interval string.")
5462
5463    return Interval(
5464        this=Literal.string(interval_parts.group(1)),
5465        unit=Var(this=interval_parts.group(2)),
5466    )

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

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:
5638def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5639    """Cast an expression to a data type.
5640
5641    Example:
5642        >>> cast('x + 1', 'int').sql()
5643        'CAST(x + 1 AS INT)'
5644
5645    Args:
5646        expression: The expression to cast.
5647        to: The datatype to cast to.
5648
5649    Returns:
5650        The new Cast instance.
5651    """
5652    expression = maybe_parse(expression, **opts)
5653    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:
5656def table_(
5657    table: Identifier | str,
5658    db: t.Optional[Identifier | str] = None,
5659    catalog: t.Optional[Identifier | str] = None,
5660    quoted: t.Optional[bool] = None,
5661    alias: t.Optional[Identifier | str] = None,
5662) -> Table:
5663    """Build a Table.
5664
5665    Args:
5666        table: Table name.
5667        db: Database name.
5668        catalog: Catalog name.
5669        quote: Whether to force quotes on the table's identifiers.
5670        alias: Table's alias.
5671
5672    Returns:
5673        The new Table instance.
5674    """
5675    return Table(
5676        this=to_identifier(table, quoted=quoted),
5677        db=to_identifier(db, quoted=quoted),
5678        catalog=to_identifier(catalog, quoted=quoted),
5679        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5680    )

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:
5683def values(
5684    values: t.Iterable[t.Tuple[t.Any, ...]],
5685    alias: t.Optional[str] = None,
5686    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5687) -> Values:
5688    """Build VALUES statement.
5689
5690    Example:
5691        >>> values([(1, '2')]).sql()
5692        "VALUES (1, '2')"
5693
5694    Args:
5695        values: values statements that will be converted to SQL
5696        alias: optional alias
5697        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5698         If either are provided then an alias is also required.
5699
5700    Returns:
5701        Values: the Values expression object
5702    """
5703    if columns and not alias:
5704        raise ValueError("Alias is required when providing columns")
5705
5706    return Values(
5707        expressions=[convert(tup) for tup in values],
5708        alias=(
5709            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5710            if columns
5711            else (TableAlias(this=to_identifier(alias)) if alias else None)
5712        ),
5713    )

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:
5716def var(name: t.Optional[ExpOrStr]) -> Var:
5717    """Build a SQL variable.
5718
5719    Example:
5720        >>> repr(var('x'))
5721        '(VAR this: x)'
5722
5723        >>> repr(var(column('x', table='y')))
5724        '(VAR this: x)'
5725
5726    Args:
5727        name: The name of the var or an expression who's name will become the var.
5728
5729    Returns:
5730        The new variable node.
5731    """
5732    if not name:
5733        raise ValueError("Cannot convert empty name into var.")
5734
5735    if isinstance(name, Expression):
5736        name = name.name
5737    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:
5740def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5741    """Build ALTER TABLE... RENAME... expression
5742
5743    Args:
5744        old_name: The old name of the table
5745        new_name: The new name of the table
5746
5747    Returns:
5748        Alter table expression
5749    """
5750    old_table = to_table(old_name)
5751    new_table = to_table(new_name)
5752    return AlterTable(
5753        this=old_table,
5754        actions=[
5755            RenameTable(this=new_table),
5756        ],
5757    )

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

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:
5847def table_name(table: Table | str, dialect: DialectType = None) -> str:
5848    """Get the full name of a table as a string.
5849
5850    Args:
5851        table: Table expression node or string.
5852        dialect: The dialect to generate the table name for.
5853
5854    Examples:
5855        >>> from sqlglot import exp, parse_one
5856        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5857        'a.b.c'
5858
5859    Returns:
5860        The table name.
5861    """
5862
5863    table = maybe_parse(table, into=Table)
5864
5865    if not table:
5866        raise ValueError(f"Cannot parse {table}")
5867
5868    return ".".join(
5869        part.sql(dialect=dialect, identify=True)
5870        if not SAFE_IDENTIFIER_RE.match(part.name)
5871        else part.name
5872        for part in table.parts
5873    )

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

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
6031def false() -> Boolean:
6032    """
6033    Returns a false Boolean expression.
6034    """
6035    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6038def null() -> Null:
6039    """
6040    Returns a Null expression.
6041    """
6042    return Null()

Returns a Null expression.

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