Edit on GitHub

Expressions

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

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


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

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

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

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

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

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

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

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

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

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

name: str
alias_or_name: str
output_name: str

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

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

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

Returns a deep copy of the expression.

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

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

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

Sets arg_key to value.

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

Returns the depth of this tree.

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

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

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

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

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

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

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

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

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

The generator object.

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

Returns a nearest parent matching expression_types.

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

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

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

Returns the root expression of this tree.

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

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

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

the generator object.

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

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

Returns:

The generator object.

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

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

Returns:

The generator object.

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

Returns the first non parenthesis child or self.

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

Returns the inner expression if this is an Alias.

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

Returns unnested operands as a tuple.

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

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

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

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

Returns SQL string representation of this tree.

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

The SQL string.

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

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

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

The transformed tree.

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

Swap out this expression with a new expression.

For example::

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

The new expression or expressions.

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

Remove this expression from its AST.

Returns:

The popped expression.

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

Assert that this Expression is an instance of type_.

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

Examples:

This is useful for type security in chained expressions:

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

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

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

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

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

Dump this Expression to a JSON-serializable dict.

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

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

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

AND this condition with one or multiple expressions.

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

The new And condition.

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

OR this condition with one or multiple expressions.

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

The new Or condition.

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

Wrap this condition with NOT.

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

The new Not instance.

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

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

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

Builds a UNION expression.

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

The new Union expression.

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

Builds an INTERSECT expression.

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

The new Intersect expression.

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

Builds an EXCEPT expression.

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

The new Except expression.

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

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

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

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

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

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

Converts the column into a dot expression.

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

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

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

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

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

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

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

Append to or set the common table expressions.

Example:
>>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'insert'
class OnConflict(Expression):
1581class OnConflict(Expression):
1582    arg_types = {
1583        "duplicate": False,
1584        "expressions": False,
1585        "nothing": False,
1586        "key": False,
1587        "constraint": False,
1588    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1591class Returning(Expression):
1592    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1596class Introducer(Expression):
1597    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1601class National(Expression):
1602    pass
key = 'national'
class LoadData(Expression):
1605class LoadData(Expression):
1606    arg_types = {
1607        "this": True,
1608        "local": False,
1609        "overwrite": False,
1610        "inpath": True,
1611        "partition": False,
1612        "input_format": False,
1613        "serde": False,
1614    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1617class Partition(Expression):
1618    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1621class Fetch(Expression):
1622    arg_types = {
1623        "direction": False,
1624        "count": False,
1625        "percent": False,
1626        "with_ties": False,
1627    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1630class Group(Expression):
1631    arg_types = {
1632        "expressions": False,
1633        "grouping_sets": False,
1634        "cube": False,
1635        "rollup": False,
1636        "totals": False,
1637        "all": False,
1638    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1641class Lambda(Expression):
1642    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1645class Limit(Expression):
1646    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1649class Literal(Condition):
1650    arg_types = {"this": True, "is_string": True}
1651
1652    @property
1653    def hashable_args(self) -> t.Any:
1654        return (self.this, self.args.get("is_string"))
1655
1656    @classmethod
1657    def number(cls, number) -> Literal:
1658        return cls(this=str(number), is_string=False)
1659
1660    @classmethod
1661    def string(cls, string) -> Literal:
1662        return cls(this=str(string), is_string=True)
1663
1664    @property
1665    def output_name(self) -> str:
1666        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1656    @classmethod
1657    def number(cls, number) -> Literal:
1658        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1660    @classmethod
1661    def string(cls, string) -> Literal:
1662        return cls(this=str(string), is_string=True)
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'literal'
class Join(Expression):
1669class Join(Expression):
1670    arg_types = {
1671        "this": True,
1672        "on": False,
1673        "side": False,
1674        "kind": False,
1675        "using": False,
1676        "method": False,
1677        "global": False,
1678        "hint": False,
1679    }
1680
1681    @property
1682    def method(self) -> str:
1683        return self.text("method").upper()
1684
1685    @property
1686    def kind(self) -> str:
1687        return self.text("kind").upper()
1688
1689    @property
1690    def side(self) -> str:
1691        return self.text("side").upper()
1692
1693    @property
1694    def hint(self) -> str:
1695        return self.text("hint").upper()
1696
1697    @property
1698    def alias_or_name(self) -> str:
1699        return self.this.alias_or_name
1700
1701    def on(
1702        self,
1703        *expressions: t.Optional[ExpOrStr],
1704        append: bool = True,
1705        dialect: DialectType = None,
1706        copy: bool = True,
1707        **opts,
1708    ) -> Join:
1709        """
1710        Append to or set the ON expressions.
1711
1712        Example:
1713            >>> import sqlglot
1714            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1715            'JOIN x ON y = 1'
1716
1717        Args:
1718            *expressions: the SQL code strings to parse.
1719                If an `Expression` instance is passed, it will be used as-is.
1720                Multiple expressions are combined with an AND operator.
1721            append: if `True`, AND the new expressions to any existing expression.
1722                Otherwise, this resets the expression.
1723            dialect: the dialect used to parse the input expressions.
1724            copy: if `False`, modify this expression instance in-place.
1725            opts: other options to use to parse the input expressions.
1726
1727        Returns:
1728            The modified Join expression.
1729        """
1730        join = _apply_conjunction_builder(
1731            *expressions,
1732            instance=self,
1733            arg="on",
1734            append=append,
1735            dialect=dialect,
1736            copy=copy,
1737            **opts,
1738        )
1739
1740        if join.kind == "CROSS":
1741            join.set("kind", None)
1742
1743        return join
1744
1745    def using(
1746        self,
1747        *expressions: t.Optional[ExpOrStr],
1748        append: bool = True,
1749        dialect: DialectType = None,
1750        copy: bool = True,
1751        **opts,
1752    ) -> Join:
1753        """
1754        Append to or set the USING expressions.
1755
1756        Example:
1757            >>> import sqlglot
1758            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1759            'JOIN x USING (foo, bla)'
1760
1761        Args:
1762            *expressions: the SQL code strings to parse.
1763                If an `Expression` instance is passed, it will be used as-is.
1764            append: if `True`, concatenate the new expressions to the existing "using" list.
1765                Otherwise, this resets the expression.
1766            dialect: the dialect used to parse the input expressions.
1767            copy: if `False`, modify this expression instance in-place.
1768            opts: other options to use to parse the input expressions.
1769
1770        Returns:
1771            The modified Join expression.
1772        """
1773        join = _apply_list_builder(
1774            *expressions,
1775            instance=self,
1776            arg="using",
1777            append=append,
1778            dialect=dialect,
1779            copy=copy,
1780            **opts,
1781        )
1782
1783        if join.kind == "CROSS":
1784            join.set("kind", None)
1785
1786        return join
arg_types = {'this': True, 'on': False, 'side': False, 'kind': False, 'using': False, 'method': False, 'global': False, 'hint': False}
method: str
kind: str
side: str
hint: str
alias_or_name: str
def on( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1701    def on(
1702        self,
1703        *expressions: t.Optional[ExpOrStr],
1704        append: bool = True,
1705        dialect: DialectType = None,
1706        copy: bool = True,
1707        **opts,
1708    ) -> Join:
1709        """
1710        Append to or set the ON expressions.
1711
1712        Example:
1713            >>> import sqlglot
1714            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1715            'JOIN x ON y = 1'
1716
1717        Args:
1718            *expressions: the SQL code strings to parse.
1719                If an `Expression` instance is passed, it will be used as-is.
1720                Multiple expressions are combined with an AND operator.
1721            append: if `True`, AND the new expressions to any existing expression.
1722                Otherwise, this resets the expression.
1723            dialect: the dialect used to parse the input expressions.
1724            copy: if `False`, modify this expression instance in-place.
1725            opts: other options to use to parse the input expressions.
1726
1727        Returns:
1728            The modified Join expression.
1729        """
1730        join = _apply_conjunction_builder(
1731            *expressions,
1732            instance=self,
1733            arg="on",
1734            append=append,
1735            dialect=dialect,
1736            copy=copy,
1737            **opts,
1738        )
1739
1740        if join.kind == "CROSS":
1741            join.set("kind", None)
1742
1743        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

def using( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1745    def using(
1746        self,
1747        *expressions: t.Optional[ExpOrStr],
1748        append: bool = True,
1749        dialect: DialectType = None,
1750        copy: bool = True,
1751        **opts,
1752    ) -> Join:
1753        """
1754        Append to or set the USING expressions.
1755
1756        Example:
1757            >>> import sqlglot
1758            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1759            'JOIN x USING (foo, bla)'
1760
1761        Args:
1762            *expressions: the SQL code strings to parse.
1763                If an `Expression` instance is passed, it will be used as-is.
1764            append: if `True`, concatenate the new expressions to the existing "using" list.
1765                Otherwise, this resets the expression.
1766            dialect: the dialect used to parse the input expressions.
1767            copy: if `False`, modify this expression instance in-place.
1768            opts: other options to use to parse the input expressions.
1769
1770        Returns:
1771            The modified Join expression.
1772        """
1773        join = _apply_list_builder(
1774            *expressions,
1775            instance=self,
1776            arg="using",
1777            append=append,
1778            dialect=dialect,
1779            copy=copy,
1780            **opts,
1781        )
1782
1783        if join.kind == "CROSS":
1784            join.set("kind", None)
1785
1786        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

key = 'join'
class Lateral(UDTF):
1789class Lateral(UDTF):
1790    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
arg_types = {'this': True, 'view': False, 'outer': False, 'alias': False}
key = 'lateral'
class MatchRecognize(Expression):
1793class MatchRecognize(Expression):
1794    arg_types = {
1795        "partition_by": False,
1796        "order": False,
1797        "measures": False,
1798        "rows": False,
1799        "after": False,
1800        "pattern": False,
1801        "define": False,
1802        "alias": False,
1803    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1808class Final(Expression):
1809    pass
key = 'final'
class Offset(Expression):
1812class Offset(Expression):
1813    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1816class Order(Expression):
1817    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1822class Cluster(Order):
1823    pass
key = 'cluster'
class Distribute(Order):
1826class Distribute(Order):
1827    pass
key = 'distribute'
class Sort(Order):
1830class Sort(Order):
1831    pass
key = 'sort'
class Ordered(Expression):
1834class Ordered(Expression):
1835    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1838class Property(Expression):
1839    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1842class AlgorithmProperty(Property):
1843    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1846class AutoIncrementProperty(Property):
1847    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1850class BlockCompressionProperty(Property):
1851    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
arg_types = {'autotemp': False, 'always': False, 'default': True, 'manual': True, 'never': True}
key = 'blockcompressionproperty'
class CharacterSetProperty(Property):
1854class CharacterSetProperty(Property):
1855    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1858class ChecksumProperty(Property):
1859    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1862class CollateProperty(Property):
1863    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1866class CopyGrantsProperty(Property):
1867    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1870class DataBlocksizeProperty(Property):
1871    arg_types = {
1872        "size": False,
1873        "units": False,
1874        "minimum": False,
1875        "maximum": False,
1876        "default": False,
1877    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1880class DefinerProperty(Property):
1881    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1884class DistKeyProperty(Property):
1885    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1888class DistStyleProperty(Property):
1889    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1892class EngineProperty(Property):
1893    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1896class ToTableProperty(Property):
1897    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1900class ExecuteAsProperty(Property):
1901    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1904class ExternalProperty(Property):
1905    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1908class FallbackProperty(Property):
1909    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1912class FileFormatProperty(Property):
1913    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1916class FreespaceProperty(Property):
1917    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1920class InputOutputFormat(Expression):
1921    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1924class IsolatedLoadingProperty(Property):
1925    arg_types = {
1926        "no": True,
1927        "concurrent": True,
1928        "for_all": True,
1929        "for_insert": True,
1930        "for_none": True,
1931    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1934class JournalProperty(Property):
1935    arg_types = {
1936        "no": False,
1937        "dual": False,
1938        "before": False,
1939        "local": False,
1940        "after": False,
1941    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1944class LanguageProperty(Property):
1945    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1949class ClusteredByProperty(Property):
1950    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1953class DictProperty(Property):
1954    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1957class DictSubProperty(Property):
1958    pass
key = 'dictsubproperty'
class DictRange(Property):
1961class DictRange(Property):
1962    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1967class OnCluster(Property):
1968    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1971class LikeProperty(Property):
1972    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1975class LocationProperty(Property):
1976    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
1979class LockingProperty(Property):
1980    arg_types = {
1981        "this": False,
1982        "kind": True,
1983        "for_or_in": True,
1984        "lock_type": True,
1985        "override": False,
1986    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
1989class LogProperty(Property):
1990    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
1993class MaterializedProperty(Property):
1994    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
1997class MergeBlockRatioProperty(Property):
1998    arg_types = {"this": False, "no": False, "default": False, "percent": False}
arg_types = {'this': False, 'no': False, 'default': False, 'percent': False}
key = 'mergeblockratioproperty'
class NoPrimaryIndexProperty(Property):
2001class NoPrimaryIndexProperty(Property):
2002    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
2005class OnCommitProperty(Property):
2006    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2009class PartitionedByProperty(Property):
2010    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2013class ReturnsProperty(Property):
2014    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2017class RowFormatProperty(Property):
2018    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2021class RowFormatDelimitedProperty(Property):
2022    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2023    arg_types = {
2024        "fields": False,
2025        "escaped": False,
2026        "collection_items": False,
2027        "map_keys": False,
2028        "lines": False,
2029        "null": False,
2030        "serde": False,
2031    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2034class RowFormatSerdeProperty(Property):
2035    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2039class QueryTransform(Expression):
2040    arg_types = {
2041        "expressions": True,
2042        "command_script": True,
2043        "schema": False,
2044        "row_format_before": False,
2045        "record_writer": False,
2046        "row_format_after": False,
2047        "record_reader": False,
2048    }
arg_types = {'expressions': True, 'command_script': True, 'schema': False, 'row_format_before': False, 'record_writer': False, 'row_format_after': False, 'record_reader': False}
key = 'querytransform'
class SchemaCommentProperty(Property):
2051class SchemaCommentProperty(Property):
2052    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2055class SerdeProperties(Property):
2056    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2059class SetProperty(Property):
2060    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2063class SettingsProperty(Property):
2064    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2067class SortKeyProperty(Property):
2068    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2071class SqlSecurityProperty(Property):
2072    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2075class StabilityProperty(Property):
2076    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2079class TemporaryProperty(Property):
2080    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2083class TransientProperty(Property):
2084    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2087class VolatileProperty(Property):
2088    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2091class WithDataProperty(Property):
2092    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2095class WithJournalTableProperty(Property):
2096    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2099class Properties(Expression):
2100    arg_types = {"expressions": True}
2101
2102    NAME_TO_PROPERTY = {
2103        "ALGORITHM": AlgorithmProperty,
2104        "AUTO_INCREMENT": AutoIncrementProperty,
2105        "CHARACTER SET": CharacterSetProperty,
2106        "CLUSTERED_BY": ClusteredByProperty,
2107        "COLLATE": CollateProperty,
2108        "COMMENT": SchemaCommentProperty,
2109        "DEFINER": DefinerProperty,
2110        "DISTKEY": DistKeyProperty,
2111        "DISTSTYLE": DistStyleProperty,
2112        "ENGINE": EngineProperty,
2113        "EXECUTE AS": ExecuteAsProperty,
2114        "FORMAT": FileFormatProperty,
2115        "LANGUAGE": LanguageProperty,
2116        "LOCATION": LocationProperty,
2117        "PARTITIONED_BY": PartitionedByProperty,
2118        "RETURNS": ReturnsProperty,
2119        "ROW_FORMAT": RowFormatProperty,
2120        "SORTKEY": SortKeyProperty,
2121    }
2122
2123    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2124
2125    # CREATE property locations
2126    # Form: schema specified
2127    #   create [POST_CREATE]
2128    #     table a [POST_NAME]
2129    #     (b int) [POST_SCHEMA]
2130    #     with ([POST_WITH])
2131    #     index (b) [POST_INDEX]
2132    #
2133    # Form: alias selection
2134    #   create [POST_CREATE]
2135    #     table a [POST_NAME]
2136    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2137    #     index (c) [POST_INDEX]
2138    class Location(AutoName):
2139        POST_CREATE = auto()
2140        POST_NAME = auto()
2141        POST_SCHEMA = auto()
2142        POST_WITH = auto()
2143        POST_ALIAS = auto()
2144        POST_EXPRESSION = auto()
2145        POST_INDEX = auto()
2146        UNSUPPORTED = auto()
2147
2148    @classmethod
2149    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2150        expressions = []
2151        for key, value in properties_dict.items():
2152            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2153            if property_cls:
2154                expressions.append(property_cls(this=convert(value)))
2155            else:
2156                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2157
2158        return cls(expressions=expressions)
arg_types = {'expressions': True}
NAME_TO_PROPERTY = {'ALGORITHM': <class 'sqlglot.expressions.AlgorithmProperty'>, 'AUTO_INCREMENT': <class 'sqlglot.expressions.AutoIncrementProperty'>, 'CHARACTER SET': <class 'sqlglot.expressions.CharacterSetProperty'>, 'CLUSTERED_BY': <class 'sqlglot.expressions.ClusteredByProperty'>, 'COLLATE': <class 'sqlglot.expressions.CollateProperty'>, 'COMMENT': <class 'sqlglot.expressions.SchemaCommentProperty'>, 'DEFINER': <class 'sqlglot.expressions.DefinerProperty'>, 'DISTKEY': <class 'sqlglot.expressions.DistKeyProperty'>, 'DISTSTYLE': <class 'sqlglot.expressions.DistStyleProperty'>, 'ENGINE': <class 'sqlglot.expressions.EngineProperty'>, 'EXECUTE AS': <class 'sqlglot.expressions.ExecuteAsProperty'>, 'FORMAT': <class 'sqlglot.expressions.FileFormatProperty'>, 'LANGUAGE': <class 'sqlglot.expressions.LanguageProperty'>, 'LOCATION': <class 'sqlglot.expressions.LocationProperty'>, 'PARTITIONED_BY': <class 'sqlglot.expressions.PartitionedByProperty'>, 'RETURNS': <class 'sqlglot.expressions.ReturnsProperty'>, 'ROW_FORMAT': <class 'sqlglot.expressions.RowFormatProperty'>, 'SORTKEY': <class 'sqlglot.expressions.SortKeyProperty'>}
PROPERTY_TO_NAME = {<class 'sqlglot.expressions.AlgorithmProperty'>: 'ALGORITHM', <class 'sqlglot.expressions.AutoIncrementProperty'>: 'AUTO_INCREMENT', <class 'sqlglot.expressions.CharacterSetProperty'>: 'CHARACTER SET', <class 'sqlglot.expressions.ClusteredByProperty'>: 'CLUSTERED_BY', <class 'sqlglot.expressions.CollateProperty'>: 'COLLATE', <class 'sqlglot.expressions.SchemaCommentProperty'>: 'COMMENT', <class 'sqlglot.expressions.DefinerProperty'>: 'DEFINER', <class 'sqlglot.expressions.DistKeyProperty'>: 'DISTKEY', <class 'sqlglot.expressions.DistStyleProperty'>: 'DISTSTYLE', <class 'sqlglot.expressions.EngineProperty'>: 'ENGINE', <class 'sqlglot.expressions.ExecuteAsProperty'>: 'EXECUTE AS', <class 'sqlglot.expressions.FileFormatProperty'>: 'FORMAT', <class 'sqlglot.expressions.LanguageProperty'>: 'LANGUAGE', <class 'sqlglot.expressions.LocationProperty'>: 'LOCATION', <class 'sqlglot.expressions.PartitionedByProperty'>: 'PARTITIONED_BY', <class 'sqlglot.expressions.ReturnsProperty'>: 'RETURNS', <class 'sqlglot.expressions.RowFormatProperty'>: 'ROW_FORMAT', <class 'sqlglot.expressions.SortKeyProperty'>: 'SORTKEY'}
@classmethod
def from_dict(cls, properties_dict: Dict) -> sqlglot.expressions.Properties:
2148    @classmethod
2149    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2150        expressions = []
2151        for key, value in properties_dict.items():
2152            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2153            if property_cls:
2154                expressions.append(property_cls(this=convert(value)))
2155            else:
2156                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2157
2158        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2138    class Location(AutoName):
2139        POST_CREATE = auto()
2140        POST_NAME = auto()
2141        POST_SCHEMA = auto()
2142        POST_WITH = auto()
2143        POST_ALIAS = auto()
2144        POST_EXPRESSION = auto()
2145        POST_INDEX = auto()
2146        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
2161class Qualify(Expression):
2162    pass
key = 'qualify'
class Return(Expression):
2166class Return(Expression):
2167    pass
key = 'return'
class Reference(Expression):
2170class Reference(Expression):
2171    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2174class Tuple(Expression):
2175    arg_types = {"expressions": False}
2176
2177    def isin(
2178        self,
2179        *expressions: t.Any,
2180        query: t.Optional[ExpOrStr] = None,
2181        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2182        copy: bool = True,
2183        **opts,
2184    ) -> In:
2185        return In(
2186            this=_maybe_copy(self, copy),
2187            expressions=[convert(e, copy=copy) for e in expressions],
2188            query=maybe_parse(query, copy=copy, **opts) if query else None,
2189            unnest=Unnest(
2190                expressions=[
2191                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2192                ]
2193            )
2194            if unnest
2195            else None,
2196        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, unnest: Union[str, sqlglot.expressions.Expression, NoneType, Collection[Union[str, sqlglot.expressions.Expression]]] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2177    def isin(
2178        self,
2179        *expressions: t.Any,
2180        query: t.Optional[ExpOrStr] = None,
2181        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2182        copy: bool = True,
2183        **opts,
2184    ) -> In:
2185        return In(
2186            this=_maybe_copy(self, copy),
2187            expressions=[convert(e, copy=copy) for e in expressions],
2188            query=maybe_parse(query, copy=copy, **opts) if query else None,
2189            unnest=Unnest(
2190                expressions=[
2191                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2192                ]
2193            )
2194            if unnest
2195            else None,
2196        )
key = 'tuple'
class Subqueryable(Unionable):
2199class Subqueryable(Unionable):
2200    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2201        """
2202        Convert this expression to an aliased expression that can be used as a Subquery.
2203
2204        Example:
2205            >>> subquery = Select().select("x").from_("tbl").subquery()
2206            >>> Select().select("x").from_(subquery).sql()
2207            'SELECT x FROM (SELECT x FROM tbl)'
2208
2209        Args:
2210            alias (str | Identifier): an optional alias for the subquery
2211            copy (bool): if `False`, modify this expression instance in-place.
2212
2213        Returns:
2214            Alias: the subquery
2215        """
2216        instance = _maybe_copy(self, copy)
2217        if not isinstance(alias, Expression):
2218            alias = TableAlias(this=to_identifier(alias)) if alias else None
2219
2220        return Subquery(this=instance, alias=alias)
2221
2222    def limit(
2223        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2224    ) -> Select:
2225        raise NotImplementedError
2226
2227    @property
2228    def ctes(self):
2229        with_ = self.args.get("with")
2230        if not with_:
2231            return []
2232        return with_.expressions
2233
2234    @property
2235    def selects(self) -> t.List[Expression]:
2236        raise NotImplementedError("Subqueryable objects must implement `selects`")
2237
2238    @property
2239    def named_selects(self) -> t.List[str]:
2240        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2241
2242    def with_(
2243        self,
2244        alias: ExpOrStr,
2245        as_: ExpOrStr,
2246        recursive: t.Optional[bool] = None,
2247        append: bool = True,
2248        dialect: DialectType = None,
2249        copy: bool = True,
2250        **opts,
2251    ) -> Subqueryable:
2252        """
2253        Append to or set the common table expressions.
2254
2255        Example:
2256            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2257            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2258
2259        Args:
2260            alias: the SQL code string to parse as the table name.
2261                If an `Expression` instance is passed, this is used as-is.
2262            as_: the SQL code string to parse as the table expression.
2263                If an `Expression` instance is passed, it will be used as-is.
2264            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2265            append: if `True`, add to any existing expressions.
2266                Otherwise, this resets the expressions.
2267            dialect: the dialect used to parse the input expression.
2268            copy: if `False`, modify this expression instance in-place.
2269            opts: other options to use to parse the input expressions.
2270
2271        Returns:
2272            The modified expression.
2273        """
2274        return _apply_cte_builder(
2275            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2276        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2200    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2201        """
2202        Convert this expression to an aliased expression that can be used as a Subquery.
2203
2204        Example:
2205            >>> subquery = Select().select("x").from_("tbl").subquery()
2206            >>> Select().select("x").from_(subquery).sql()
2207            'SELECT x FROM (SELECT x FROM tbl)'
2208
2209        Args:
2210            alias (str | Identifier): an optional alias for the subquery
2211            copy (bool): if `False`, modify this expression instance in-place.
2212
2213        Returns:
2214            Alias: the subquery
2215        """
2216        instance = _maybe_copy(self, copy)
2217        if not isinstance(alias, Expression):
2218            alias = TableAlias(this=to_identifier(alias)) if alias else None
2219
2220        return Subquery(this=instance, alias=alias)

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2222    def limit(
2223        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2224    ) -> Select:
2225        raise NotImplementedError
ctes
named_selects: List[str]
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Subqueryable:
2242    def with_(
2243        self,
2244        alias: ExpOrStr,
2245        as_: ExpOrStr,
2246        recursive: t.Optional[bool] = None,
2247        append: bool = True,
2248        dialect: DialectType = None,
2249        copy: bool = True,
2250        **opts,
2251    ) -> Subqueryable:
2252        """
2253        Append to or set the common table expressions.
2254
2255        Example:
2256            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2257            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2258
2259        Args:
2260            alias: the SQL code string to parse as the table name.
2261                If an `Expression` instance is passed, this is used as-is.
2262            as_: the SQL code string to parse as the table expression.
2263                If an `Expression` instance is passed, it will be used as-is.
2264            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2265            append: if `True`, add to any existing expressions.
2266                Otherwise, this resets the expressions.
2267            dialect: the dialect used to parse the input expression.
2268            copy: if `False`, modify this expression instance in-place.
2269            opts: other options to use to parse the input expressions.
2270
2271        Returns:
2272            The modified expression.
2273        """
2274        return _apply_cte_builder(
2275            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2276        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

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

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

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

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The limited subqueryable.

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

Append to or set the SELECT of the union recursively.

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

Union: the modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

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

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • expression : the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

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

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

Append to or set the SELECT expressions.

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

The modified Select expression.

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

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

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

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

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

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:
3146    def lock(self, update: bool = True, copy: bool = True) -> Select:
3147        """
3148        Set the locking read mode for this expression.
3149
3150        Examples:
3151            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3152            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3153
3154            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3155            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3156
3157        Args:
3158            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3159            copy: if `False`, modify this expression instance in-place.
3160
3161        Returns:
3162            The modified expression.
3163        """
3164        inst = _maybe_copy(self, copy)
3165        inst.set("locks", [Lock(update=update)])
3166
3167        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:
3169    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3170        """
3171        Set hints for this expression.
3172
3173        Examples:
3174            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3175            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3176
3177        Args:
3178            hints: The SQL code strings to parse as the hints.
3179                If an `Expression` instance is passed, it will be used as-is.
3180            dialect: The dialect used to parse the hints.
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(
3188            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3189        )
3190
3191        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):
3206class Subquery(DerivedTable, Unionable):
3207    arg_types = {
3208        "this": True,
3209        "alias": False,
3210        "with": False,
3211        **QUERY_MODIFIERS,
3212    }
3213
3214    def unnest(self):
3215        """
3216        Returns the first non subquery.
3217        """
3218        expression = self
3219        while isinstance(expression, Subquery):
3220            expression = expression.this
3221        return expression
3222
3223    @property
3224    def is_star(self) -> bool:
3225        return self.this.is_star
3226
3227    @property
3228    def output_name(self) -> str:
3229        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):
3214    def unnest(self):
3215        """
3216        Returns the first non subquery.
3217        """
3218        expression = self
3219        while isinstance(expression, Subquery):
3220            expression = expression.this
3221        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):
3232class TableSample(Expression):
3233    arg_types = {
3234        "this": False,
3235        "method": False,
3236        "bucket_numerator": False,
3237        "bucket_denominator": False,
3238        "bucket_field": False,
3239        "percent": False,
3240        "rows": False,
3241        "size": False,
3242        "seed": False,
3243        "kind": False,
3244    }
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):
3247class Tag(Expression):
3248    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3249
3250    arg_types = {
3251        "this": False,
3252        "prefix": False,
3253        "postfix": False,
3254    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3259class Pivot(Expression):
3260    arg_types = {
3261        "this": False,
3262        "alias": False,
3263        "expressions": True,
3264        "field": False,
3265        "unpivot": False,
3266        "using": False,
3267        "group": False,
3268        "columns": False,
3269    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3272class Window(Expression):
3273    arg_types = {
3274        "this": True,
3275        "partition_by": False,
3276        "order": False,
3277        "spec": False,
3278        "alias": False,
3279        "over": False,
3280        "first": False,
3281    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3284class WindowSpec(Expression):
3285    arg_types = {
3286        "kind": False,
3287        "start": False,
3288        "start_side": False,
3289        "end": False,
3290        "end_side": False,
3291    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3294class Where(Expression):
3295    pass
key = 'where'
class Star(Expression):
3298class Star(Expression):
3299    arg_types = {"except": False, "replace": False}
3300
3301    @property
3302    def name(self) -> str:
3303        return "*"
3304
3305    @property
3306    def output_name(self) -> str:
3307        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):
3310class Parameter(Condition):
3311    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3314class SessionParameter(Condition):
3315    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3318class Placeholder(Condition):
3319    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3322class Null(Condition):
3323    arg_types: t.Dict[str, t.Any] = {}
3324
3325    @property
3326    def name(self) -> str:
3327        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3330class Boolean(Condition):
3331    pass
key = 'boolean'
class DataTypeSize(Expression):
3334class DataTypeSize(Expression):
3335    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3338class DataType(Expression):
3339    arg_types = {
3340        "this": True,
3341        "expressions": False,
3342        "nested": False,
3343        "values": False,
3344        "prefix": False,
3345    }
3346
3347    class Type(AutoName):
3348        ARRAY = auto()
3349        BIGDECIMAL = auto()
3350        BIGINT = auto()
3351        BIGSERIAL = auto()
3352        BINARY = auto()
3353        BIT = auto()
3354        BOOLEAN = auto()
3355        CHAR = auto()
3356        DATE = auto()
3357        DATETIME = auto()
3358        DATETIME64 = auto()
3359        ENUM = auto()
3360        INT4RANGE = auto()
3361        INT4MULTIRANGE = auto()
3362        INT8RANGE = auto()
3363        INT8MULTIRANGE = auto()
3364        NUMRANGE = auto()
3365        NUMMULTIRANGE = auto()
3366        TSRANGE = auto()
3367        TSMULTIRANGE = auto()
3368        TSTZRANGE = auto()
3369        TSTZMULTIRANGE = auto()
3370        DATERANGE = auto()
3371        DATEMULTIRANGE = auto()
3372        DECIMAL = auto()
3373        DOUBLE = auto()
3374        FLOAT = auto()
3375        GEOGRAPHY = auto()
3376        GEOMETRY = auto()
3377        HLLSKETCH = auto()
3378        HSTORE = auto()
3379        IMAGE = auto()
3380        INET = auto()
3381        INT = auto()
3382        INT128 = auto()
3383        INT256 = auto()
3384        INTERVAL = auto()
3385        JSON = auto()
3386        JSONB = auto()
3387        LONGBLOB = auto()
3388        LONGTEXT = auto()
3389        MAP = auto()
3390        MEDIUMBLOB = auto()
3391        MEDIUMTEXT = auto()
3392        MONEY = auto()
3393        NCHAR = auto()
3394        NULL = auto()
3395        NULLABLE = auto()
3396        NVARCHAR = auto()
3397        OBJECT = auto()
3398        ROWVERSION = auto()
3399        SERIAL = auto()
3400        SET = auto()
3401        SMALLINT = auto()
3402        SMALLMONEY = auto()
3403        SMALLSERIAL = auto()
3404        STRUCT = auto()
3405        SUPER = auto()
3406        TEXT = auto()
3407        TIME = auto()
3408        TIMESTAMP = auto()
3409        TIMESTAMPTZ = auto()
3410        TIMESTAMPLTZ = auto()
3411        TINYINT = auto()
3412        UBIGINT = auto()
3413        UINT = auto()
3414        USMALLINT = auto()
3415        UTINYINT = auto()
3416        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3417        UINT128 = auto()
3418        UINT256 = auto()
3419        UNIQUEIDENTIFIER = auto()
3420        USERDEFINED = "USER-DEFINED"
3421        UUID = auto()
3422        VARBINARY = auto()
3423        VARCHAR = auto()
3424        VARIANT = auto()
3425        XML = auto()
3426
3427    TEXT_TYPES = {
3428        Type.CHAR,
3429        Type.NCHAR,
3430        Type.VARCHAR,
3431        Type.NVARCHAR,
3432        Type.TEXT,
3433    }
3434
3435    INTEGER_TYPES = {
3436        Type.INT,
3437        Type.TINYINT,
3438        Type.SMALLINT,
3439        Type.BIGINT,
3440        Type.INT128,
3441        Type.INT256,
3442    }
3443
3444    FLOAT_TYPES = {
3445        Type.FLOAT,
3446        Type.DOUBLE,
3447    }
3448
3449    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3450
3451    TEMPORAL_TYPES = {
3452        Type.TIME,
3453        Type.TIMESTAMP,
3454        Type.TIMESTAMPTZ,
3455        Type.TIMESTAMPLTZ,
3456        Type.DATE,
3457        Type.DATETIME,
3458        Type.DATETIME64,
3459    }
3460
3461    META_TYPES = {"UNKNOWN", "NULL"}
3462
3463    @classmethod
3464    def build(
3465        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3466    ) -> DataType:
3467        from sqlglot import parse_one
3468
3469        if isinstance(dtype, str):
3470            upper = dtype.upper()
3471            if upper in DataType.META_TYPES:
3472                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3473            else:
3474                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3475
3476            if data_type_exp is None:
3477                raise ValueError(f"Unparsable data type value: {dtype}")
3478        elif isinstance(dtype, DataType.Type):
3479            data_type_exp = DataType(this=dtype)
3480        elif isinstance(dtype, DataType):
3481            return dtype
3482        else:
3483            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3484
3485        return DataType(**{**data_type_exp.args, **kwargs})
3486
3487    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3488        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.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>}
INTEGER_TYPES = {<Type.BIGINT: 'BIGINT'>, <Type.INT256: 'INT256'>, <Type.INT128: 'INT128'>, <Type.SMALLINT: 'SMALLINT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.INT128: 'INT128'>, <Type.SMALLINT: 'SMALLINT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>, <Type.BIGINT: 'BIGINT'>, <Type.FLOAT: 'FLOAT'>, <Type.INT256: 'INT256'>}
TEMPORAL_TYPES = {<Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.DATETIME: 'DATETIME'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATETIME64: 'DATETIME64'>, <Type.DATE: 'DATE'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIME: 'TIME'>}
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:
3463    @classmethod
3464    def build(
3465        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3466    ) -> DataType:
3467        from sqlglot import parse_one
3468
3469        if isinstance(dtype, str):
3470            upper = dtype.upper()
3471            if upper in DataType.META_TYPES:
3472                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3473            else:
3474                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3475
3476            if data_type_exp is None:
3477                raise ValueError(f"Unparsable data type value: {dtype}")
3478        elif isinstance(dtype, DataType.Type):
3479            data_type_exp = DataType(this=dtype)
3480        elif isinstance(dtype, DataType):
3481            return dtype
3482        else:
3483            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3484
3485        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3487    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3488        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3347    class Type(AutoName):
3348        ARRAY = auto()
3349        BIGDECIMAL = auto()
3350        BIGINT = auto()
3351        BIGSERIAL = auto()
3352        BINARY = auto()
3353        BIT = auto()
3354        BOOLEAN = auto()
3355        CHAR = auto()
3356        DATE = auto()
3357        DATETIME = auto()
3358        DATETIME64 = auto()
3359        ENUM = auto()
3360        INT4RANGE = auto()
3361        INT4MULTIRANGE = auto()
3362        INT8RANGE = auto()
3363        INT8MULTIRANGE = auto()
3364        NUMRANGE = auto()
3365        NUMMULTIRANGE = auto()
3366        TSRANGE = auto()
3367        TSMULTIRANGE = auto()
3368        TSTZRANGE = auto()
3369        TSTZMULTIRANGE = auto()
3370        DATERANGE = auto()
3371        DATEMULTIRANGE = auto()
3372        DECIMAL = auto()
3373        DOUBLE = auto()
3374        FLOAT = auto()
3375        GEOGRAPHY = auto()
3376        GEOMETRY = auto()
3377        HLLSKETCH = auto()
3378        HSTORE = auto()
3379        IMAGE = auto()
3380        INET = auto()
3381        INT = auto()
3382        INT128 = auto()
3383        INT256 = auto()
3384        INTERVAL = auto()
3385        JSON = auto()
3386        JSONB = auto()
3387        LONGBLOB = auto()
3388        LONGTEXT = auto()
3389        MAP = auto()
3390        MEDIUMBLOB = auto()
3391        MEDIUMTEXT = auto()
3392        MONEY = auto()
3393        NCHAR = auto()
3394        NULL = auto()
3395        NULLABLE = auto()
3396        NVARCHAR = auto()
3397        OBJECT = auto()
3398        ROWVERSION = auto()
3399        SERIAL = auto()
3400        SET = auto()
3401        SMALLINT = auto()
3402        SMALLMONEY = auto()
3403        SMALLSERIAL = auto()
3404        STRUCT = auto()
3405        SUPER = auto()
3406        TEXT = auto()
3407        TIME = auto()
3408        TIMESTAMP = auto()
3409        TIMESTAMPTZ = auto()
3410        TIMESTAMPLTZ = auto()
3411        TINYINT = auto()
3412        UBIGINT = auto()
3413        UINT = auto()
3414        USMALLINT = auto()
3415        UTINYINT = auto()
3416        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3417        UINT128 = auto()
3418        UINT256 = auto()
3419        UNIQUEIDENTIFIER = auto()
3420        USERDEFINED = "USER-DEFINED"
3421        UUID = auto()
3422        VARBINARY = auto()
3423        VARCHAR = auto()
3424        VARIANT = auto()
3425        XML = auto()

An enumeration.

ARRAY = <Type.ARRAY: 'ARRAY'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <Type.BIGINT: 'BIGINT'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
BINARY = <Type.BINARY: 'BINARY'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
CHAR = <Type.CHAR: 'CHAR'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
ENUM = <Type.ENUM: 'ENUM'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3492class PseudoType(Expression):
3493    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3497class SubqueryPredicate(Predicate):
3498    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3501class All(SubqueryPredicate):
3502    pass
key = 'all'
class Any(SubqueryPredicate):
3505class Any(SubqueryPredicate):
3506    pass
key = 'any'
class Exists(SubqueryPredicate):
3509class Exists(SubqueryPredicate):
3510    pass
key = 'exists'
class Command(Expression):
3515class Command(Expression):
3516    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3519class Transaction(Expression):
3520    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3523class Commit(Expression):
3524    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3527class Rollback(Expression):
3528    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3531class AlterTable(Expression):
3532    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3535class AddConstraint(Expression):
3536    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3539class DropPartition(Expression):
3540    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3544class Binary(Condition):
3545    arg_types = {"this": True, "expression": True}
3546
3547    @property
3548    def left(self):
3549        return self.this
3550
3551    @property
3552    def right(self):
3553        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3556class Add(Binary):
3557    pass
key = 'add'
class Connector(Binary):
3560class Connector(Binary):
3561    pass
key = 'connector'
class And(Connector):
3564class And(Connector):
3565    pass
key = 'and'
class Or(Connector):
3568class Or(Connector):
3569    pass
key = 'or'
class BitwiseAnd(Binary):
3572class BitwiseAnd(Binary):
3573    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3576class BitwiseLeftShift(Binary):
3577    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3580class BitwiseOr(Binary):
3581    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3584class BitwiseRightShift(Binary):
3585    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3588class BitwiseXor(Binary):
3589    pass
key = 'bitwisexor'
class Div(Binary):
3592class Div(Binary):
3593    pass
key = 'div'
class Overlaps(Binary):
3596class Overlaps(Binary):
3597    pass
key = 'overlaps'
class Dot(Binary):
3600class Dot(Binary):
3601    @property
3602    def name(self) -> str:
3603        return self.expression.name
3604
3605    @property
3606    def output_name(self) -> str:
3607        return self.name
3608
3609    @classmethod
3610    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3611        """Build a Dot object with a sequence of expressions."""
3612        if len(expressions) < 2:
3613            raise ValueError(f"Dot requires >= 2 expressions.")
3614
3615        a, b, *expressions = expressions
3616        dot = Dot(this=a, expression=b)
3617
3618        for expression in expressions:
3619            dot = Dot(this=dot, expression=expression)
3620
3621        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:
3609    @classmethod
3610    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3611        """Build a Dot object with a sequence of expressions."""
3612        if len(expressions) < 2:
3613            raise ValueError(f"Dot requires >= 2 expressions.")
3614
3615        a, b, *expressions = expressions
3616        dot = Dot(this=a, expression=b)
3617
3618        for expression in expressions:
3619            dot = Dot(this=dot, expression=expression)
3620
3621        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3624class DPipe(Binary):
3625    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3628class SafeDPipe(DPipe):
3629    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3632class EQ(Binary, Predicate):
3633    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3636class NullSafeEQ(Binary, Predicate):
3637    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3640class NullSafeNEQ(Binary, Predicate):
3641    pass
key = 'nullsafeneq'
class Distance(Binary):
3644class Distance(Binary):
3645    pass
key = 'distance'
class Escape(Binary):
3648class Escape(Binary):
3649    pass
key = 'escape'
class Glob(Binary, Predicate):
3652class Glob(Binary, Predicate):
3653    pass
key = 'glob'
class GT(Binary, Predicate):
3656class GT(Binary, Predicate):
3657    pass
key = 'gt'
class GTE(Binary, Predicate):
3660class GTE(Binary, Predicate):
3661    pass
key = 'gte'
class ILike(Binary, Predicate):
3664class ILike(Binary, Predicate):
3665    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3668class ILikeAny(Binary, Predicate):
3669    pass
key = 'ilikeany'
class IntDiv(Binary):
3672class IntDiv(Binary):
3673    pass
key = 'intdiv'
class Is(Binary, Predicate):
3676class Is(Binary, Predicate):
3677    pass
key = 'is'
class Kwarg(Binary):
3680class Kwarg(Binary):
3681    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3684class Like(Binary, Predicate):
3685    pass
key = 'like'
class LikeAny(Binary, Predicate):
3688class LikeAny(Binary, Predicate):
3689    pass
key = 'likeany'
class LT(Binary, Predicate):
3692class LT(Binary, Predicate):
3693    pass
key = 'lt'
class LTE(Binary, Predicate):
3696class LTE(Binary, Predicate):
3697    pass
key = 'lte'
class Mod(Binary):
3700class Mod(Binary):
3701    pass
key = 'mod'
class Mul(Binary):
3704class Mul(Binary):
3705    pass
key = 'mul'
class NEQ(Binary, Predicate):
3708class NEQ(Binary, Predicate):
3709    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3712class SimilarTo(Binary, Predicate):
3713    pass
key = 'similarto'
class Slice(Binary):
3716class Slice(Binary):
3717    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3720class Sub(Binary):
3721    pass
key = 'sub'
class ArrayOverlaps(Binary):
3724class ArrayOverlaps(Binary):
3725    pass
key = 'arrayoverlaps'
class Unary(Condition):
3730class Unary(Condition):
3731    pass
key = 'unary'
class BitwiseNot(Unary):
3734class BitwiseNot(Unary):
3735    pass
key = 'bitwisenot'
class Not(Unary):
3738class Not(Unary):
3739    pass
key = 'not'
class Paren(Unary):
3742class Paren(Unary):
3743    arg_types = {"this": True, "with": False}
3744
3745    @property
3746    def output_name(self) -> str:
3747        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):
3750class Neg(Unary):
3751    pass
key = 'neg'
class Alias(Expression):
3754class Alias(Expression):
3755    arg_types = {"this": True, "alias": False}
3756
3757    @property
3758    def output_name(self) -> str:
3759        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):
3762class Aliases(Expression):
3763    arg_types = {"this": True, "expressions": True}
3764
3765    @property
3766    def aliases(self):
3767        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3770class AtTimeZone(Expression):
3771    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3774class Between(Predicate):
3775    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3778class Bracket(Condition):
3779    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3782class SafeBracket(Bracket):
3783    """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):
3786class Distinct(Expression):
3787    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3790class In(Predicate):
3791    arg_types = {
3792        "this": True,
3793        "expressions": False,
3794        "query": False,
3795        "unnest": False,
3796        "field": False,
3797        "is_global": False,
3798    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3801class TimeUnit(Expression):
3802    """Automatically converts unit arg into a var."""
3803
3804    arg_types = {"unit": False}
3805
3806    def __init__(self, **args):
3807        unit = args.get("unit")
3808        if isinstance(unit, (Column, Literal)):
3809            args["unit"] = Var(this=unit.name)
3810        elif isinstance(unit, Week):
3811            unit.set("this", Var(this=unit.this.name))
3812
3813        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3806    def __init__(self, **args):
3807        unit = args.get("unit")
3808        if isinstance(unit, (Column, Literal)):
3809            args["unit"] = Var(this=unit.name)
3810        elif isinstance(unit, Week):
3811            unit.set("this", Var(this=unit.this.name))
3812
3813        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3816class Interval(TimeUnit):
3817    arg_types = {"this": False, "unit": False}
3818
3819    @property
3820    def unit(self) -> t.Optional[Var]:
3821        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3824class IgnoreNulls(Expression):
3825    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3828class RespectNulls(Expression):
3829    pass
key = 'respectnulls'
class Func(Condition):
3833class Func(Condition):
3834    """
3835    The base class for all function expressions.
3836
3837    Attributes:
3838        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3839            treated as a variable length argument and the argument's value will be stored as a list.
3840        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3841            for this function expression. These values are used to map this node to a name during parsing
3842            as well as to provide the function's name during SQL string generation. By default the SQL
3843            name is set to the expression's class name transformed to snake case.
3844    """
3845
3846    is_var_len_args = False
3847
3848    @classmethod
3849    def from_arg_list(cls, args):
3850        if cls.is_var_len_args:
3851            all_arg_keys = list(cls.arg_types)
3852            # If this function supports variable length argument treat the last argument as such.
3853            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3854            num_non_var = len(non_var_len_arg_keys)
3855
3856            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3857            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3858        else:
3859            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3860
3861        return cls(**args_dict)
3862
3863    @classmethod
3864    def sql_names(cls):
3865        if cls is Func:
3866            raise NotImplementedError(
3867                "SQL name is only supported by concrete function implementations"
3868            )
3869        if "_sql_names" not in cls.__dict__:
3870            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3871        return cls._sql_names
3872
3873    @classmethod
3874    def sql_name(cls):
3875        return cls.sql_names()[0]
3876
3877    @classmethod
3878    def default_parser_mappings(cls):
3879        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):
3848    @classmethod
3849    def from_arg_list(cls, args):
3850        if cls.is_var_len_args:
3851            all_arg_keys = list(cls.arg_types)
3852            # If this function supports variable length argument treat the last argument as such.
3853            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3854            num_non_var = len(non_var_len_arg_keys)
3855
3856            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3857            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3858        else:
3859            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3860
3861        return cls(**args_dict)
@classmethod
def sql_names(cls):
3863    @classmethod
3864    def sql_names(cls):
3865        if cls is Func:
3866            raise NotImplementedError(
3867                "SQL name is only supported by concrete function implementations"
3868            )
3869        if "_sql_names" not in cls.__dict__:
3870            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3871        return cls._sql_names
@classmethod
def sql_name(cls):
3873    @classmethod
3874    def sql_name(cls):
3875        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3877    @classmethod
3878    def default_parser_mappings(cls):
3879        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3882class AggFunc(Func):
3883    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3886class ParameterizedAgg(AggFunc):
3887    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3890class Abs(Func):
3891    pass
key = 'abs'
class Transform(Func):
3895class Transform(Func):
3896    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
3899class Anonymous(Func):
3900    arg_types = {"this": True, "expressions": False}
3901    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3906class Hll(AggFunc):
3907    arg_types = {"this": True, "expressions": False}
3908    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3911class ApproxDistinct(AggFunc):
3912    arg_types = {"this": True, "accuracy": False}
3913    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3916class Array(Func):
3917    arg_types = {"expressions": False}
3918    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3922class ToChar(Func):
3923    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3926class GenerateSeries(Func):
3927    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3930class ArrayAgg(AggFunc):
3931    pass
key = 'arrayagg'
class ArrayAll(Func):
3934class ArrayAll(Func):
3935    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3938class ArrayAny(Func):
3939    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3942class ArrayConcat(Func):
3943    arg_types = {"this": True, "expressions": False}
3944    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3947class ArrayContains(Binary, Func):
3948    pass
key = 'arraycontains'
class ArrayContained(Binary):
3951class ArrayContained(Binary):
3952    pass
key = 'arraycontained'
class ArrayFilter(Func):
3955class ArrayFilter(Func):
3956    arg_types = {"this": True, "expression": True}
3957    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3960class ArrayJoin(Func):
3961    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3964class ArraySize(Func):
3965    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3968class ArraySort(Func):
3969    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3972class ArraySum(Func):
3973    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3976class ArrayUnionAgg(AggFunc):
3977    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3980class Avg(AggFunc):
3981    pass
key = 'avg'
class AnyValue(AggFunc):
3984class AnyValue(AggFunc):
3985    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
3988class Case(Func):
3989    arg_types = {"this": False, "ifs": True, "default": False}
3990
3991    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3992        instance = _maybe_copy(self, copy)
3993        instance.append(
3994            "ifs",
3995            If(
3996                this=maybe_parse(condition, copy=copy, **opts),
3997                true=maybe_parse(then, copy=copy, **opts),
3998            ),
3999        )
4000        return instance
4001
4002    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4003        instance = _maybe_copy(self, copy)
4004        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4005        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:
3991    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3992        instance = _maybe_copy(self, copy)
3993        instance.append(
3994            "ifs",
3995            If(
3996                this=maybe_parse(condition, copy=copy, **opts),
3997                true=maybe_parse(then, copy=copy, **opts),
3998            ),
3999        )
4000        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4002    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4003        instance = _maybe_copy(self, copy)
4004        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4005        return instance
key = 'case'
class Cast(Func):
4008class Cast(Func):
4009    arg_types = {"this": True, "to": True, "format": False}
4010
4011    @property
4012    def name(self) -> str:
4013        return self.this.name
4014
4015    @property
4016    def to(self) -> DataType:
4017        return self.args["to"]
4018
4019    @property
4020    def output_name(self) -> str:
4021        return self.name
4022
4023    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4024        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:
4023    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4024        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
4027class CastToStrType(Func):
4028    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
4031class Collate(Binary):
4032    pass
key = 'collate'
class TryCast(Cast):
4035class TryCast(Cast):
4036    pass
key = 'trycast'
class Ceil(Func):
4039class Ceil(Func):
4040    arg_types = {"this": True, "decimals": False}
4041    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4044class Coalesce(Func):
4045    arg_types = {"this": True, "expressions": False}
4046    is_var_len_args = True
4047    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4050class Concat(Func):
4051    arg_types = {"expressions": True}
4052    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4055class SafeConcat(Concat):
4056    pass
key = 'safeconcat'
class ConcatWs(Concat):
4059class ConcatWs(Concat):
4060    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4063class Count(AggFunc):
4064    arg_types = {"this": False, "expressions": False}
4065    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4068class CountIf(AggFunc):
4069    pass
key = 'countif'
class CurrentDate(Func):
4072class CurrentDate(Func):
4073    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4076class CurrentDatetime(Func):
4077    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4080class CurrentTime(Func):
4081    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4084class CurrentTimestamp(Func):
4085    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4088class CurrentUser(Func):
4089    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4092class DateAdd(Func, TimeUnit):
4093    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4096class DateSub(Func, TimeUnit):
4097    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4100class DateDiff(Func, TimeUnit):
4101    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4102    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4105class DateTrunc(Func):
4106    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4109class DatetimeAdd(Func, TimeUnit):
4110    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4113class DatetimeSub(Func, TimeUnit):
4114    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4117class DatetimeDiff(Func, TimeUnit):
4118    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4121class DatetimeTrunc(Func, TimeUnit):
4122    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4125class DayOfWeek(Func):
4126    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4129class DayOfMonth(Func):
4130    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4133class DayOfYear(Func):
4134    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4137class WeekOfYear(Func):
4138    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4141class MonthsBetween(Func):
4142    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4145class LastDateOfMonth(Func):
4146    pass
key = 'lastdateofmonth'
class Extract(Func):
4149class Extract(Func):
4150    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4153class TimestampAdd(Func, TimeUnit):
4154    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4157class TimestampSub(Func, TimeUnit):
4158    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4161class TimestampDiff(Func, TimeUnit):
4162    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4165class TimestampTrunc(Func, TimeUnit):
4166    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4169class TimeAdd(Func, TimeUnit):
4170    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4173class TimeSub(Func, TimeUnit):
4174    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4177class TimeDiff(Func, TimeUnit):
4178    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4181class TimeTrunc(Func, TimeUnit):
4182    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4185class DateFromParts(Func):
4186    _sql_names = ["DATEFROMPARTS"]
4187    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4190class DateStrToDate(Func):
4191    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4194class DateToDateStr(Func):
4195    pass
key = 'datetodatestr'
class DateToDi(Func):
4198class DateToDi(Func):
4199    pass
key = 'datetodi'
class Date(Func):
4203class Date(Func):
4204    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4207class Day(Func):
4208    pass
key = 'day'
class Decode(Func):
4211class Decode(Func):
4212    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4215class DiToDate(Func):
4216    pass
key = 'ditodate'
class Encode(Func):
4219class Encode(Func):
4220    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4223class Exp(Func):
4224    pass
key = 'exp'
class Explode(Func):
4227class Explode(Func):
4228    pass
key = 'explode'
class Floor(Func):
4231class Floor(Func):
4232    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4235class FromBase64(Func):
4236    pass
key = 'frombase64'
class ToBase64(Func):
4239class ToBase64(Func):
4240    pass
key = 'tobase64'
class Greatest(Func):
4243class Greatest(Func):
4244    arg_types = {"this": True, "expressions": False}
4245    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4248class GroupConcat(Func):
4249    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4252class Hex(Func):
4253    pass
key = 'hex'
class Xor(Connector, Func):
4256class Xor(Connector, Func):
4257    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4260class If(Func):
4261    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4264class Initcap(Func):
4265    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4268class JSONKeyValue(Expression):
4269    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4272class JSONObject(Func):
4273    arg_types = {
4274        "expressions": False,
4275        "null_handling": False,
4276        "unique_keys": False,
4277        "return_type": False,
4278        "format_json": False,
4279        "encoding": False,
4280    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4283class OpenJSONColumnDef(Expression):
4284    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):
4287class OpenJSON(Func):
4288    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4291class JSONBContains(Binary):
4292    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4295class JSONExtract(Binary, Func):
4296    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4299class JSONExtractScalar(JSONExtract):
4300    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4303class JSONBExtract(JSONExtract):
4304    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4307class JSONBExtractScalar(JSONExtract):
4308    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4311class JSONFormat(Func):
4312    arg_types = {"this": False, "options": False}
4313    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4317class JSONArrayContains(Binary, Predicate, Func):
4318    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4321class Least(Func):
4322    arg_types = {"this": True, "expressions": False}
4323    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4326class Left(Func):
4327    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4334class Length(Func):
4335    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4338class Levenshtein(Func):
4339    arg_types = {
4340        "this": True,
4341        "expression": False,
4342        "ins_cost": False,
4343        "del_cost": False,
4344        "sub_cost": False,
4345    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4348class Ln(Func):
4349    pass
key = 'ln'
class Log(Func):
4352class Log(Func):
4353    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4356class Log2(Func):
4357    pass
key = 'log2'
class Log10(Func):
4360class Log10(Func):
4361    pass
key = 'log10'
class LogicalOr(AggFunc):
4364class LogicalOr(AggFunc):
4365    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4368class LogicalAnd(AggFunc):
4369    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4372class Lower(Func):
4373    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4376class Map(Func):
4377    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4380class MapFromEntries(Func):
4381    pass
key = 'mapfromentries'
class StarMap(Func):
4384class StarMap(Func):
4385    pass
key = 'starmap'
class VarMap(Func):
4388class VarMap(Func):
4389    arg_types = {"keys": True, "values": True}
4390    is_var_len_args = True
4391
4392    @property
4393    def keys(self) -> t.List[Expression]:
4394        return self.args["keys"].expressions
4395
4396    @property
4397    def values(self) -> t.List[Expression]:
4398        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4402class MatchAgainst(Func):
4403    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4406class Max(AggFunc):
4407    arg_types = {"this": True, "expressions": False}
4408    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4411class MD5(Func):
4412    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4416class MD5Digest(Func):
4417    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4420class Min(AggFunc):
4421    arg_types = {"this": True, "expressions": False}
4422    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4425class Month(Func):
4426    pass
key = 'month'
class Nvl2(Func):
4429class Nvl2(Func):
4430    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4433class Posexplode(Func):
4434    pass
key = 'posexplode'
class Pow(Binary, Func):
4437class Pow(Binary, Func):
4438    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4441class PercentileCont(AggFunc):
4442    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4445class PercentileDisc(AggFunc):
4446    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4449class Quantile(AggFunc):
4450    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4453class ApproxQuantile(Quantile):
4454    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):
4457class RangeN(Func):
4458    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4461class ReadCSV(Func):
4462    _sql_names = ["READ_CSV"]
4463    is_var_len_args = True
4464    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4467class Reduce(Func):
4468    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):
4471class RegexpExtract(Func):
4472    arg_types = {
4473        "this": True,
4474        "expression": True,
4475        "position": False,
4476        "occurrence": False,
4477        "parameters": False,
4478        "group": False,
4479    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4482class RegexpReplace(Func):
4483    arg_types = {
4484        "this": True,
4485        "expression": True,
4486        "replacement": True,
4487        "position": False,
4488        "occurrence": False,
4489        "parameters": False,
4490    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4493class RegexpLike(Binary, Func):
4494    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4497class RegexpILike(Func):
4498    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4503class RegexpSplit(Func):
4504    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4507class Repeat(Func):
4508    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4511class Round(Func):
4512    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4515class RowNumber(Func):
4516    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4519class SafeDivide(Func):
4520    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4523class SetAgg(AggFunc):
4524    pass
key = 'setagg'
class SHA(Func):
4527class SHA(Func):
4528    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4531class SHA2(Func):
4532    _sql_names = ["SHA2"]
4533    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4536class SortArray(Func):
4537    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4540class Split(Func):
4541    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4546class Substring(Func):
4547    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4550class StandardHash(Func):
4551    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4554class StrPosition(Func):
4555    arg_types = {
4556        "this": True,
4557        "substr": True,
4558        "position": False,
4559        "instance": False,
4560    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4563class StrToDate(Func):
4564    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4567class StrToTime(Func):
4568    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4573class StrToUnix(Func):
4574    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4577class NumberToStr(Func):
4578    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4581class FromBase(Func):
4582    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4585class Struct(Func):
4586    arg_types = {"expressions": True}
4587    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4590class StructExtract(Func):
4591    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4594class Sum(AggFunc):
4595    pass
key = 'sum'
class Sqrt(Func):
4598class Sqrt(Func):
4599    pass
key = 'sqrt'
class Stddev(AggFunc):
4602class Stddev(AggFunc):
4603    pass
key = 'stddev'
class StddevPop(AggFunc):
4606class StddevPop(AggFunc):
4607    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4610class StddevSamp(AggFunc):
4611    pass
key = 'stddevsamp'
class TimeToStr(Func):
4614class TimeToStr(Func):
4615    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4618class TimeToTimeStr(Func):
4619    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4622class TimeToUnix(Func):
4623    pass
key = 'timetounix'
class TimeStrToDate(Func):
4626class TimeStrToDate(Func):
4627    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4630class TimeStrToTime(Func):
4631    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4634class TimeStrToUnix(Func):
4635    pass
key = 'timestrtounix'
class Trim(Func):
4638class Trim(Func):
4639    arg_types = {
4640        "this": True,
4641        "expression": False,
4642        "position": False,
4643        "collation": False,
4644    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4647class TsOrDsAdd(Func, TimeUnit):
4648    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4651class TsOrDsToDateStr(Func):
4652    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4655class TsOrDsToDate(Func):
4656    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4659class TsOrDiToDi(Func):
4660    pass
key = 'tsorditodi'
class Unhex(Func):
4663class Unhex(Func):
4664    pass
key = 'unhex'
class UnixToStr(Func):
4667class UnixToStr(Func):
4668    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4673class UnixToTime(Func):
4674    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4675
4676    SECONDS = Literal.string("seconds")
4677    MILLIS = Literal.string("millis")
4678    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):
4681class UnixToTimeStr(Func):
4682    pass
key = 'unixtotimestr'
class Upper(Func):
4685class Upper(Func):
4686    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4689class Variance(AggFunc):
4690    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4693class VariancePop(AggFunc):
4694    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4697class Week(Func):
4698    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4701class XMLTable(Func):
4702    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):
4705class Year(Func):
4706    pass
key = 'year'
class Use(Expression):
4709class Use(Expression):
4710    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4713class Merge(Expression):
4714    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):
4717class When(Func):
4718    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):
4723class NextValueFor(Func):
4724    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.JSONArrayContains'>, <class 'sqlglot.expressions.JSONBExtract'>, <class 'sqlglot.expressions.JSONBExtractScalar'>, <class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.JSONExtractScalar'>, <class 'sqlglot.expressions.JSONFormat'>, <class 'sqlglot.expressions.JSONObject'>, <class 'sqlglot.expressions.LastDateOfMonth'>, <class 'sqlglot.expressions.Least'>, <class 'sqlglot.expressions.Left'>, <class 'sqlglot.expressions.Length'>, <class 'sqlglot.expressions.Levenshtein'>, <class 'sqlglot.expressions.Ln'>, <class 'sqlglot.expressions.Log'>, <class 'sqlglot.expressions.Log10'>, <class 'sqlglot.expressions.Log2'>, <class 'sqlglot.expressions.LogicalAnd'>, <class 'sqlglot.expressions.LogicalOr'>, <class 'sqlglot.expressions.Lower'>, <class 'sqlglot.expressions.MD5'>, <class 'sqlglot.expressions.MD5Digest'>, <class 'sqlglot.expressions.Map'>, <class 'sqlglot.expressions.MapFromEntries'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <class 'sqlglot.expressions.MonthsBetween'>, <class 'sqlglot.expressions.NextValueFor'>, <class 'sqlglot.expressions.NumberToStr'>, <class 'sqlglot.expressions.Nvl2'>, <class 'sqlglot.expressions.OpenJSON'>, <class 'sqlglot.expressions.ParameterizedAgg'>, <class 'sqlglot.expressions.PercentileCont'>, <class 'sqlglot.expressions.PercentileDisc'>, <class 'sqlglot.expressions.Posexplode'>, <class 'sqlglot.expressions.Pow'>, <class 'sqlglot.expressions.Quantile'>, <class 'sqlglot.expressions.RangeN'>, <class 'sqlglot.expressions.ReadCSV'>, <class 'sqlglot.expressions.Reduce'>, <class 'sqlglot.expressions.RegexpExtract'>, <class 'sqlglot.expressions.RegexpILike'>, <class 'sqlglot.expressions.RegexpLike'>, <class 'sqlglot.expressions.RegexpReplace'>, <class 'sqlglot.expressions.RegexpSplit'>, <class 'sqlglot.expressions.Repeat'>, <class 'sqlglot.expressions.Right'>, <class 'sqlglot.expressions.Round'>, <class 'sqlglot.expressions.RowNumber'>, <class 'sqlglot.expressions.SHA'>, <class 'sqlglot.expressions.SHA2'>, <class 'sqlglot.expressions.SafeConcat'>, <class 'sqlglot.expressions.SafeDivide'>, <class 'sqlglot.expressions.SetAgg'>, <class 'sqlglot.expressions.SortArray'>, <class 'sqlglot.expressions.Split'>, <class 'sqlglot.expressions.Sqrt'>, <class 'sqlglot.expressions.StandardHash'>, <class 'sqlglot.expressions.StarMap'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.Transform'>, <class 'sqlglot.expressions.Trim'>, <class 'sqlglot.expressions.TryCast'>, <class 'sqlglot.expressions.TsOrDiToDi'>, <class 'sqlglot.expressions.TsOrDsAdd'>, <class 'sqlglot.expressions.TsOrDsToDate'>, <class 'sqlglot.expressions.TsOrDsToDateStr'>, <class 'sqlglot.expressions.Unhex'>, <class 'sqlglot.expressions.UnixToStr'>, <class 'sqlglot.expressions.UnixToTime'>, <class 'sqlglot.expressions.UnixToTimeStr'>, <class 'sqlglot.expressions.Upper'>, <class 'sqlglot.expressions.VarMap'>, <class 'sqlglot.expressions.Variance'>, <class 'sqlglot.expressions.VariancePop'>, <class 'sqlglot.expressions.Week'>, <class 'sqlglot.expressions.WeekOfYear'>, <class 'sqlglot.expressions.When'>, <class 'sqlglot.expressions.XMLTable'>, <class 'sqlglot.expressions.Xor'>, <class 'sqlglot.expressions.Year'>]
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4761def maybe_parse(
4762    sql_or_expression: ExpOrStr,
4763    *,
4764    into: t.Optional[IntoType] = None,
4765    dialect: DialectType = None,
4766    prefix: t.Optional[str] = None,
4767    copy: bool = False,
4768    **opts,
4769) -> Expression:
4770    """Gracefully handle a possible string or expression.
4771
4772    Example:
4773        >>> maybe_parse("1")
4774        (LITERAL this: 1, is_string: False)
4775        >>> maybe_parse(to_identifier("x"))
4776        (IDENTIFIER this: x, quoted: False)
4777
4778    Args:
4779        sql_or_expression: the SQL code string or an expression
4780        into: the SQLGlot Expression to parse into
4781        dialect: the dialect used to parse the input expressions (in the case that an
4782            input expression is a SQL string).
4783        prefix: a string to prefix the sql with before it gets parsed
4784            (automatically includes a space)
4785        copy: whether or not to copy the expression.
4786        **opts: other options to use to parse the input expressions (again, in the case
4787            that an input expression is a SQL string).
4788
4789    Returns:
4790        Expression: the parsed or given expression.
4791    """
4792    if isinstance(sql_or_expression, Expression):
4793        if copy:
4794            return sql_or_expression.copy()
4795        return sql_or_expression
4796
4797    if sql_or_expression is None:
4798        raise ParseError(f"SQL cannot be None")
4799
4800    import sqlglot
4801
4802    sql = str(sql_or_expression)
4803    if prefix:
4804        sql = f"{prefix} {sql}"
4805
4806    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

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

Expression: the parsed or given expression.

def union( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Union:
4990def union(
4991    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4992) -> Union:
4993    """
4994    Initializes a syntax tree from one UNION expression.
4995
4996    Example:
4997        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4998        'SELECT * FROM foo UNION SELECT * FROM bla'
4999
5000    Args:
5001        left: the SQL code string corresponding to the left-hand side.
5002            If an `Expression` instance is passed, it will be used as-is.
5003        right: the SQL code string corresponding to the right-hand side.
5004            If an `Expression` instance is passed, it will be used as-is.
5005        distinct: set the DISTINCT flag if and only if this is true.
5006        dialect: the dialect used to parse the input expression.
5007        opts: other options to use to parse the input expressions.
5008
5009    Returns:
5010        The new Union instance.
5011    """
5012    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5013    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5014
5015    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:
5018def intersect(
5019    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5020) -> Intersect:
5021    """
5022    Initializes a syntax tree from one INTERSECT expression.
5023
5024    Example:
5025        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5026        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5027
5028    Args:
5029        left: the SQL code string corresponding to the left-hand side.
5030            If an `Expression` instance is passed, it will be used as-is.
5031        right: the SQL code string corresponding to the right-hand side.
5032            If an `Expression` instance is passed, it will be used as-is.
5033        distinct: set the DISTINCT flag if and only if this is true.
5034        dialect: the dialect used to parse the input expression.
5035        opts: other options to use to parse the input expressions.
5036
5037    Returns:
5038        The new Intersect instance.
5039    """
5040    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5041    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5042
5043    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:
5046def except_(
5047    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5048) -> Except:
5049    """
5050    Initializes a syntax tree from one EXCEPT expression.
5051
5052    Example:
5053        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5054        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5055
5056    Args:
5057        left: the SQL code string corresponding to the left-hand side.
5058            If an `Expression` instance is passed, it will be used as-is.
5059        right: the SQL code string corresponding to the right-hand side.
5060            If an `Expression` instance is passed, it will be used as-is.
5061        distinct: set the DISTINCT flag if and only if this is true.
5062        dialect: the dialect used to parse the input expression.
5063        opts: other options to use to parse the input expressions.
5064
5065    Returns:
5066        The new Except instance.
5067    """
5068    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5069    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5070
5071    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:
5074def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5075    """
5076    Initializes a syntax tree from one or multiple SELECT expressions.
5077
5078    Example:
5079        >>> select("col1", "col2").from_("tbl").sql()
5080        'SELECT col1, col2 FROM tbl'
5081
5082    Args:
5083        *expressions: the SQL code string to parse as the expressions of a
5084            SELECT statement. If an Expression instance is passed, this is used as-is.
5085        dialect: the dialect used to parse the input expressions (in the case that an
5086            input expression is a SQL string).
5087        **opts: other options to use to parse the input expressions (again, in the case
5088            that an input expression is a SQL string).
5089
5090    Returns:
5091        Select: the syntax tree for the SELECT statement.
5092    """
5093    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:
5096def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5097    """
5098    Initializes a syntax tree from a FROM expression.
5099
5100    Example:
5101        >>> from_("tbl").select("col1", "col2").sql()
5102        'SELECT col1, col2 FROM tbl'
5103
5104    Args:
5105        *expression: the SQL code string to parse as the FROM expressions of a
5106            SELECT statement. If an Expression instance is passed, this is used as-is.
5107        dialect: the dialect used to parse the input expression (in the case that the
5108            input expression is a SQL string).
5109        **opts: other options to use to parse the input expressions (again, in the case
5110            that the input expression is a SQL string).
5111
5112    Returns:
5113        Select: the syntax tree for the SELECT statement.
5114    """
5115    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:
5118def update(
5119    table: str | Table,
5120    properties: dict,
5121    where: t.Optional[ExpOrStr] = None,
5122    from_: t.Optional[ExpOrStr] = None,
5123    dialect: DialectType = None,
5124    **opts,
5125) -> Update:
5126    """
5127    Creates an update statement.
5128
5129    Example:
5130        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5131        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5132
5133    Args:
5134        *properties: dictionary of properties to set which are
5135            auto converted to sql objects eg None -> NULL
5136        where: sql conditional parsed into a WHERE statement
5137        from_: sql statement parsed into a FROM statement
5138        dialect: the dialect used to parse the input expressions.
5139        **opts: other options to use to parse the input expressions.
5140
5141    Returns:
5142        Update: the syntax tree for the UPDATE statement.
5143    """
5144    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5145    update_expr.set(
5146        "expressions",
5147        [
5148            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5149            for k, v in properties.items()
5150        ],
5151    )
5152    if from_:
5153        update_expr.set(
5154            "from",
5155            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5156        )
5157    if isinstance(where, Condition):
5158        where = Where(this=where)
5159    if where:
5160        update_expr.set(
5161            "where",
5162            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5163        )
5164    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:
5167def delete(
5168    table: ExpOrStr,
5169    where: t.Optional[ExpOrStr] = None,
5170    returning: t.Optional[ExpOrStr] = None,
5171    dialect: DialectType = None,
5172    **opts,
5173) -> Delete:
5174    """
5175    Builds a delete statement.
5176
5177    Example:
5178        >>> delete("my_table", where="id > 1").sql()
5179        'DELETE FROM my_table WHERE id > 1'
5180
5181    Args:
5182        where: sql conditional parsed into a WHERE statement
5183        returning: sql conditional parsed into a RETURNING statement
5184        dialect: the dialect used to parse the input expressions.
5185        **opts: other options to use to parse the input expressions.
5186
5187    Returns:
5188        Delete: the syntax tree for the DELETE statement.
5189    """
5190    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5191    if where:
5192        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5193    if returning:
5194        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5195    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:
5198def insert(
5199    expression: ExpOrStr,
5200    into: ExpOrStr,
5201    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5202    overwrite: t.Optional[bool] = None,
5203    dialect: DialectType = None,
5204    copy: bool = True,
5205    **opts,
5206) -> Insert:
5207    """
5208    Builds an INSERT statement.
5209
5210    Example:
5211        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5212        'INSERT INTO tbl VALUES (1, 2, 3)'
5213
5214    Args:
5215        expression: the sql string or expression of the INSERT statement
5216        into: the tbl to insert data to.
5217        columns: optionally the table's column names.
5218        overwrite: whether to INSERT OVERWRITE or not.
5219        dialect: the dialect used to parse the input expressions.
5220        copy: whether or not to copy the expression.
5221        **opts: other options to use to parse the input expressions.
5222
5223    Returns:
5224        Insert: the syntax tree for the INSERT statement.
5225    """
5226    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5227    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5228
5229    if columns:
5230        this = _apply_list_builder(
5231            *columns,
5232            instance=Schema(this=this),
5233            arg="expressions",
5234            into=Identifier,
5235            copy=False,
5236            dialect=dialect,
5237            **opts,
5238        )
5239
5240    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:
5243def condition(
5244    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5245) -> Condition:
5246    """
5247    Initialize a logical condition expression.
5248
5249    Example:
5250        >>> condition("x=1").sql()
5251        'x = 1'
5252
5253        This is helpful for composing larger logical syntax trees:
5254        >>> where = condition("x=1")
5255        >>> where = where.and_("y=1")
5256        >>> Select().from_("tbl").select("*").where(where).sql()
5257        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5258
5259    Args:
5260        *expression: the SQL code string to parse.
5261            If an Expression instance is passed, this is used as-is.
5262        dialect: the dialect used to parse the input expression (in the case that the
5263            input expression is a SQL string).
5264        copy: Whether or not to copy `expression` (only applies to expressions).
5265        **opts: other options to use to parse the input expressions (again, in the case
5266            that the input expression is a SQL string).
5267
5268    Returns:
5269        The new Condition instance
5270    """
5271    return maybe_parse(
5272        expression,
5273        into=Condition,
5274        dialect=dialect,
5275        copy=copy,
5276        **opts,
5277    )

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

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

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:
5605def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5606    """Cast an expression to a data type.
5607
5608    Example:
5609        >>> cast('x + 1', 'int').sql()
5610        'CAST(x + 1 AS INT)'
5611
5612    Args:
5613        expression: The expression to cast.
5614        to: The datatype to cast to.
5615
5616    Returns:
5617        The new Cast instance.
5618    """
5619    expression = maybe_parse(expression, **opts)
5620    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:
5623def table_(
5624    table: Identifier | str,
5625    db: t.Optional[Identifier | str] = None,
5626    catalog: t.Optional[Identifier | str] = None,
5627    quoted: t.Optional[bool] = None,
5628    alias: t.Optional[Identifier | str] = None,
5629) -> Table:
5630    """Build a Table.
5631
5632    Args:
5633        table: Table name.
5634        db: Database name.
5635        catalog: Catalog name.
5636        quote: Whether to force quotes on the table's identifiers.
5637        alias: Table's alias.
5638
5639    Returns:
5640        The new Table instance.
5641    """
5642    return Table(
5643        this=to_identifier(table, quoted=quoted),
5644        db=to_identifier(db, quoted=quoted),
5645        catalog=to_identifier(catalog, quoted=quoted),
5646        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5647    )

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

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

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

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

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

Returns a true Boolean expression.

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

Returns a false Boolean expression.

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

Returns a Null expression.

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