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

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

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

Converts the column into a dot expression.

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

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:
1345    def where(
1346        self,
1347        *expressions: t.Optional[ExpOrStr],
1348        append: bool = True,
1349        dialect: DialectType = None,
1350        copy: bool = True,
1351        **opts,
1352    ) -> Delete:
1353        """
1354        Append to or set the WHERE expressions.
1355
1356        Example:
1357            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1358            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1359
1360        Args:
1361            *expressions: the SQL code strings to parse.
1362                If an `Expression` instance is passed, it will be used as-is.
1363                Multiple expressions are combined with an AND operator.
1364            append: if `True`, AND the new expressions to any existing expression.
1365                Otherwise, this resets the expression.
1366            dialect: the dialect used to parse the input expressions.
1367            copy: if `False`, modify this expression instance in-place.
1368            opts: other options to use to parse the input expressions.
1369
1370        Returns:
1371            Delete: the modified expression.
1372        """
1373        return _apply_conjunction_builder(
1374            *expressions,
1375            instance=self,
1376            arg="where",
1377            append=append,
1378            into=Where,
1379            dialect=dialect,
1380            copy=copy,
1381            **opts,
1382        )

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:
1384    def returning(
1385        self,
1386        expression: ExpOrStr,
1387        dialect: DialectType = None,
1388        copy: bool = True,
1389        **opts,
1390    ) -> Delete:
1391        """
1392        Set the RETURNING expression. Not supported by all dialects.
1393
1394        Example:
1395            >>> delete("tbl").returning("*", dialect="postgres").sql()
1396            'DELETE FROM tbl RETURNING *'
1397
1398        Args:
1399            expression: the SQL code strings to parse.
1400                If an `Expression` instance is passed, it will be used as-is.
1401            dialect: the dialect used to parse the input expressions.
1402            copy: if `False`, modify this expression instance in-place.
1403            opts: other options to use to parse the input expressions.
1404
1405        Returns:
1406            Delete: the modified expression.
1407        """
1408        return _apply_builder(
1409            expression=expression,
1410            instance=self,
1411            arg="returning",
1412            prefix="RETURNING",
1413            dialect=dialect,
1414            copy=copy,
1415            into=Returning,
1416            **opts,
1417        )

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):
1420class Drop(Expression):
1421    arg_types = {
1422        "this": False,
1423        "kind": False,
1424        "exists": False,
1425        "temporary": False,
1426        "materialized": False,
1427        "cascade": False,
1428        "constraints": False,
1429        "purge": False,
1430    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1433class Filter(Expression):
1434    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1437class Check(Expression):
1438    pass
key = 'check'
class Directory(Expression):
1441class Directory(Expression):
1442    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1443    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1446class ForeignKey(Expression):
1447    arg_types = {
1448        "expressions": True,
1449        "reference": False,
1450        "delete": False,
1451        "update": False,
1452    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1455class PrimaryKey(Expression):
1456    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1461class Into(Expression):
1462    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1465class From(Expression):
1466    @property
1467    def name(self) -> str:
1468        return self.this.name
1469
1470    @property
1471    def alias_or_name(self) -> str:
1472        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1475class Having(Expression):
1476    pass
key = 'having'
class Hint(Expression):
1479class Hint(Expression):
1480    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1483class JoinHint(Expression):
1484    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1487class Identifier(Expression):
1488    arg_types = {"this": True, "quoted": False}
1489
1490    @property
1491    def quoted(self) -> bool:
1492        return bool(self.args.get("quoted"))
1493
1494    @property
1495    def hashable_args(self) -> t.Any:
1496        return (self.this, self.quoted)
1497
1498    @property
1499    def output_name(self) -> str:
1500        return self.name
arg_types = {'this': True, 'quoted': False}
quoted: bool
hashable_args: Any
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'identifier'
class Index(Expression):
1503class Index(Expression):
1504    arg_types = {
1505        "this": False,
1506        "table": False,
1507        "using": False,
1508        "where": False,
1509        "columns": False,
1510        "unique": False,
1511        "primary": False,
1512        "amp": False,  # teradata
1513        "partition_by": False,  # teradata
1514    }
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):
1517class Insert(Expression):
1518    arg_types = {
1519        "with": False,
1520        "this": True,
1521        "expression": False,
1522        "conflict": False,
1523        "returning": False,
1524        "overwrite": False,
1525        "exists": False,
1526        "partition": False,
1527        "alternative": False,
1528        "where": False,
1529        "ignore": False,
1530    }
1531
1532    def with_(
1533        self,
1534        alias: ExpOrStr,
1535        as_: ExpOrStr,
1536        recursive: t.Optional[bool] = None,
1537        append: bool = True,
1538        dialect: DialectType = None,
1539        copy: bool = True,
1540        **opts,
1541    ) -> Insert:
1542        """
1543        Append to or set the common table expressions.
1544
1545        Example:
1546            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1547            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1548
1549        Args:
1550            alias: the SQL code string to parse as the table name.
1551                If an `Expression` instance is passed, this is used as-is.
1552            as_: the SQL code string to parse as the table expression.
1553                If an `Expression` instance is passed, it will be used as-is.
1554            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1555            append: if `True`, add to any existing expressions.
1556                Otherwise, this resets the expressions.
1557            dialect: the dialect used to parse the input expression.
1558            copy: if `False`, modify this expression instance in-place.
1559            opts: other options to use to parse the input expressions.
1560
1561        Returns:
1562            The modified expression.
1563        """
1564        return _apply_cte_builder(
1565            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1566        )
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:
1532    def with_(
1533        self,
1534        alias: ExpOrStr,
1535        as_: ExpOrStr,
1536        recursive: t.Optional[bool] = None,
1537        append: bool = True,
1538        dialect: DialectType = None,
1539        copy: bool = True,
1540        **opts,
1541    ) -> Insert:
1542        """
1543        Append to or set the common table expressions.
1544
1545        Example:
1546            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1547            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1548
1549        Args:
1550            alias: the SQL code string to parse as the table name.
1551                If an `Expression` instance is passed, this is used as-is.
1552            as_: the SQL code string to parse as the table expression.
1553                If an `Expression` instance is passed, it will be used as-is.
1554            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1555            append: if `True`, add to any existing expressions.
1556                Otherwise, this resets the expressions.
1557            dialect: the dialect used to parse the input expression.
1558            copy: if `False`, modify this expression instance in-place.
1559            opts: other options to use to parse the input expressions.
1560
1561        Returns:
1562            The modified expression.
1563        """
1564        return _apply_cte_builder(
1565            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1566        )

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):
1569class OnConflict(Expression):
1570    arg_types = {
1571        "duplicate": False,
1572        "expressions": False,
1573        "nothing": False,
1574        "key": False,
1575        "constraint": False,
1576    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1579class Returning(Expression):
1580    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1584class Introducer(Expression):
1585    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1589class National(Expression):
1590    pass
key = 'national'
class LoadData(Expression):
1593class LoadData(Expression):
1594    arg_types = {
1595        "this": True,
1596        "local": False,
1597        "overwrite": False,
1598        "inpath": True,
1599        "partition": False,
1600        "input_format": False,
1601        "serde": False,
1602    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1605class Partition(Expression):
1606    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1609class Fetch(Expression):
1610    arg_types = {
1611        "direction": False,
1612        "count": False,
1613        "percent": False,
1614        "with_ties": False,
1615    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1618class Group(Expression):
1619    arg_types = {
1620        "expressions": False,
1621        "grouping_sets": False,
1622        "cube": False,
1623        "rollup": False,
1624        "totals": False,
1625        "all": False,
1626    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1629class Lambda(Expression):
1630    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1633class Limit(Expression):
1634    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1637class Literal(Condition):
1638    arg_types = {"this": True, "is_string": True}
1639
1640    @property
1641    def hashable_args(self) -> t.Any:
1642        return (self.this, self.args.get("is_string"))
1643
1644    @classmethod
1645    def number(cls, number) -> Literal:
1646        return cls(this=str(number), is_string=False)
1647
1648    @classmethod
1649    def string(cls, string) -> Literal:
1650        return cls(this=str(string), is_string=True)
1651
1652    @property
1653    def output_name(self) -> str:
1654        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1644    @classmethod
1645    def number(cls, number) -> Literal:
1646        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1648    @classmethod
1649    def string(cls, string) -> Literal:
1650        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):
1657class Join(Expression):
1658    arg_types = {
1659        "this": True,
1660        "on": False,
1661        "side": False,
1662        "kind": False,
1663        "using": False,
1664        "method": False,
1665        "global": False,
1666        "hint": False,
1667    }
1668
1669    @property
1670    def method(self) -> str:
1671        return self.text("method").upper()
1672
1673    @property
1674    def kind(self) -> str:
1675        return self.text("kind").upper()
1676
1677    @property
1678    def side(self) -> str:
1679        return self.text("side").upper()
1680
1681    @property
1682    def hint(self) -> str:
1683        return self.text("hint").upper()
1684
1685    @property
1686    def alias_or_name(self) -> str:
1687        return self.this.alias_or_name
1688
1689    def on(
1690        self,
1691        *expressions: t.Optional[ExpOrStr],
1692        append: bool = True,
1693        dialect: DialectType = None,
1694        copy: bool = True,
1695        **opts,
1696    ) -> Join:
1697        """
1698        Append to or set the ON expressions.
1699
1700        Example:
1701            >>> import sqlglot
1702            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1703            'JOIN x ON y = 1'
1704
1705        Args:
1706            *expressions: the SQL code strings to parse.
1707                If an `Expression` instance is passed, it will be used as-is.
1708                Multiple expressions are combined with an AND operator.
1709            append: if `True`, AND the new expressions to any existing expression.
1710                Otherwise, this resets the expression.
1711            dialect: the dialect used to parse the input expressions.
1712            copy: if `False`, modify this expression instance in-place.
1713            opts: other options to use to parse the input expressions.
1714
1715        Returns:
1716            The modified Join expression.
1717        """
1718        join = _apply_conjunction_builder(
1719            *expressions,
1720            instance=self,
1721            arg="on",
1722            append=append,
1723            dialect=dialect,
1724            copy=copy,
1725            **opts,
1726        )
1727
1728        if join.kind == "CROSS":
1729            join.set("kind", None)
1730
1731        return join
1732
1733    def using(
1734        self,
1735        *expressions: t.Optional[ExpOrStr],
1736        append: bool = True,
1737        dialect: DialectType = None,
1738        copy: bool = True,
1739        **opts,
1740    ) -> Join:
1741        """
1742        Append to or set the USING expressions.
1743
1744        Example:
1745            >>> import sqlglot
1746            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1747            'JOIN x USING (foo, bla)'
1748
1749        Args:
1750            *expressions: the SQL code strings to parse.
1751                If an `Expression` instance is passed, it will be used as-is.
1752            append: if `True`, concatenate the new expressions to the existing "using" list.
1753                Otherwise, this resets the expression.
1754            dialect: the dialect used to parse the input expressions.
1755            copy: if `False`, modify this expression instance in-place.
1756            opts: other options to use to parse the input expressions.
1757
1758        Returns:
1759            The modified Join expression.
1760        """
1761        join = _apply_list_builder(
1762            *expressions,
1763            instance=self,
1764            arg="using",
1765            append=append,
1766            dialect=dialect,
1767            copy=copy,
1768            **opts,
1769        )
1770
1771        if join.kind == "CROSS":
1772            join.set("kind", None)
1773
1774        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:
1689    def on(
1690        self,
1691        *expressions: t.Optional[ExpOrStr],
1692        append: bool = True,
1693        dialect: DialectType = None,
1694        copy: bool = True,
1695        **opts,
1696    ) -> Join:
1697        """
1698        Append to or set the ON expressions.
1699
1700        Example:
1701            >>> import sqlglot
1702            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1703            'JOIN x ON y = 1'
1704
1705        Args:
1706            *expressions: the SQL code strings to parse.
1707                If an `Expression` instance is passed, it will be used as-is.
1708                Multiple expressions are combined with an AND operator.
1709            append: if `True`, AND the new expressions to any existing expression.
1710                Otherwise, this resets the expression.
1711            dialect: the dialect used to parse the input expressions.
1712            copy: if `False`, modify this expression instance in-place.
1713            opts: other options to use to parse the input expressions.
1714
1715        Returns:
1716            The modified Join expression.
1717        """
1718        join = _apply_conjunction_builder(
1719            *expressions,
1720            instance=self,
1721            arg="on",
1722            append=append,
1723            dialect=dialect,
1724            copy=copy,
1725            **opts,
1726        )
1727
1728        if join.kind == "CROSS":
1729            join.set("kind", None)
1730
1731        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:
1733    def using(
1734        self,
1735        *expressions: t.Optional[ExpOrStr],
1736        append: bool = True,
1737        dialect: DialectType = None,
1738        copy: bool = True,
1739        **opts,
1740    ) -> Join:
1741        """
1742        Append to or set the USING expressions.
1743
1744        Example:
1745            >>> import sqlglot
1746            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1747            'JOIN x USING (foo, bla)'
1748
1749        Args:
1750            *expressions: the SQL code strings to parse.
1751                If an `Expression` instance is passed, it will be used as-is.
1752            append: if `True`, concatenate the new expressions to the existing "using" list.
1753                Otherwise, this resets the expression.
1754            dialect: the dialect used to parse the input expressions.
1755            copy: if `False`, modify this expression instance in-place.
1756            opts: other options to use to parse the input expressions.
1757
1758        Returns:
1759            The modified Join expression.
1760        """
1761        join = _apply_list_builder(
1762            *expressions,
1763            instance=self,
1764            arg="using",
1765            append=append,
1766            dialect=dialect,
1767            copy=copy,
1768            **opts,
1769        )
1770
1771        if join.kind == "CROSS":
1772            join.set("kind", None)
1773
1774        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):
1777class Lateral(UDTF):
1778    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):
1781class MatchRecognize(Expression):
1782    arg_types = {
1783        "partition_by": False,
1784        "order": False,
1785        "measures": False,
1786        "rows": False,
1787        "after": False,
1788        "pattern": False,
1789        "define": False,
1790        "alias": False,
1791    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1796class Final(Expression):
1797    pass
key = 'final'
class Offset(Expression):
1800class Offset(Expression):
1801    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1804class Order(Expression):
1805    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1810class Cluster(Order):
1811    pass
key = 'cluster'
class Distribute(Order):
1814class Distribute(Order):
1815    pass
key = 'distribute'
class Sort(Order):
1818class Sort(Order):
1819    pass
key = 'sort'
class Ordered(Expression):
1822class Ordered(Expression):
1823    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1826class Property(Expression):
1827    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1830class AlgorithmProperty(Property):
1831    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1834class AutoIncrementProperty(Property):
1835    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1838class BlockCompressionProperty(Property):
1839    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):
1842class CharacterSetProperty(Property):
1843    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1846class ChecksumProperty(Property):
1847    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1850class CollateProperty(Property):
1851    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1854class CopyGrantsProperty(Property):
1855    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1858class DataBlocksizeProperty(Property):
1859    arg_types = {
1860        "size": False,
1861        "units": False,
1862        "minimum": False,
1863        "maximum": False,
1864        "default": False,
1865    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1868class DefinerProperty(Property):
1869    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1872class DistKeyProperty(Property):
1873    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1876class DistStyleProperty(Property):
1877    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1880class EngineProperty(Property):
1881    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1884class ToTableProperty(Property):
1885    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1888class ExecuteAsProperty(Property):
1889    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1892class ExternalProperty(Property):
1893    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1896class FallbackProperty(Property):
1897    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1900class FileFormatProperty(Property):
1901    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1904class FreespaceProperty(Property):
1905    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1908class InputOutputFormat(Expression):
1909    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1912class IsolatedLoadingProperty(Property):
1913    arg_types = {
1914        "no": True,
1915        "concurrent": True,
1916        "for_all": True,
1917        "for_insert": True,
1918        "for_none": True,
1919    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1922class JournalProperty(Property):
1923    arg_types = {
1924        "no": False,
1925        "dual": False,
1926        "before": False,
1927        "local": False,
1928        "after": False,
1929    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1932class LanguageProperty(Property):
1933    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1937class ClusteredByProperty(Property):
1938    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1941class DictProperty(Property):
1942    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1945class DictSubProperty(Property):
1946    pass
key = 'dictsubproperty'
class DictRange(Property):
1949class DictRange(Property):
1950    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1955class OnCluster(Property):
1956    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1959class LikeProperty(Property):
1960    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1963class LocationProperty(Property):
1964    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
1967class LockingProperty(Property):
1968    arg_types = {
1969        "this": False,
1970        "kind": True,
1971        "for_or_in": True,
1972        "lock_type": True,
1973        "override": False,
1974    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
1977class LogProperty(Property):
1978    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
1981class MaterializedProperty(Property):
1982    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
1985class MergeBlockRatioProperty(Property):
1986    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):
1989class NoPrimaryIndexProperty(Property):
1990    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
1993class OnCommitProperty(Property):
1994    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
1997class PartitionedByProperty(Property):
1998    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2001class ReturnsProperty(Property):
2002    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2005class RowFormatProperty(Property):
2006    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2009class RowFormatDelimitedProperty(Property):
2010    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2011    arg_types = {
2012        "fields": False,
2013        "escaped": False,
2014        "collection_items": False,
2015        "map_keys": False,
2016        "lines": False,
2017        "null": False,
2018        "serde": False,
2019    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2022class RowFormatSerdeProperty(Property):
2023    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatserdeproperty'
class SchemaCommentProperty(Property):
2026class SchemaCommentProperty(Property):
2027    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2030class SerdeProperties(Property):
2031    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2034class SetProperty(Property):
2035    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2038class SettingsProperty(Property):
2039    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2042class SortKeyProperty(Property):
2043    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2046class SqlSecurityProperty(Property):
2047    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2050class StabilityProperty(Property):
2051    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2054class TemporaryProperty(Property):
2055    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2058class TransientProperty(Property):
2059    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2062class VolatileProperty(Property):
2063    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2066class WithDataProperty(Property):
2067    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2070class WithJournalTableProperty(Property):
2071    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2074class Properties(Expression):
2075    arg_types = {"expressions": True}
2076
2077    NAME_TO_PROPERTY = {
2078        "ALGORITHM": AlgorithmProperty,
2079        "AUTO_INCREMENT": AutoIncrementProperty,
2080        "CHARACTER SET": CharacterSetProperty,
2081        "CLUSTERED_BY": ClusteredByProperty,
2082        "COLLATE": CollateProperty,
2083        "COMMENT": SchemaCommentProperty,
2084        "DEFINER": DefinerProperty,
2085        "DISTKEY": DistKeyProperty,
2086        "DISTSTYLE": DistStyleProperty,
2087        "ENGINE": EngineProperty,
2088        "EXECUTE AS": ExecuteAsProperty,
2089        "FORMAT": FileFormatProperty,
2090        "LANGUAGE": LanguageProperty,
2091        "LOCATION": LocationProperty,
2092        "PARTITIONED_BY": PartitionedByProperty,
2093        "RETURNS": ReturnsProperty,
2094        "ROW_FORMAT": RowFormatProperty,
2095        "SORTKEY": SortKeyProperty,
2096    }
2097
2098    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2099
2100    # CREATE property locations
2101    # Form: schema specified
2102    #   create [POST_CREATE]
2103    #     table a [POST_NAME]
2104    #     (b int) [POST_SCHEMA]
2105    #     with ([POST_WITH])
2106    #     index (b) [POST_INDEX]
2107    #
2108    # Form: alias selection
2109    #   create [POST_CREATE]
2110    #     table a [POST_NAME]
2111    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2112    #     index (c) [POST_INDEX]
2113    class Location(AutoName):
2114        POST_CREATE = auto()
2115        POST_NAME = auto()
2116        POST_SCHEMA = auto()
2117        POST_WITH = auto()
2118        POST_ALIAS = auto()
2119        POST_EXPRESSION = auto()
2120        POST_INDEX = auto()
2121        UNSUPPORTED = auto()
2122
2123    @classmethod
2124    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2125        expressions = []
2126        for key, value in properties_dict.items():
2127            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2128            if property_cls:
2129                expressions.append(property_cls(this=convert(value)))
2130            else:
2131                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2132
2133        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:
2123    @classmethod
2124    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2125        expressions = []
2126        for key, value in properties_dict.items():
2127            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2128            if property_cls:
2129                expressions.append(property_cls(this=convert(value)))
2130            else:
2131                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2132
2133        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2113    class Location(AutoName):
2114        POST_CREATE = auto()
2115        POST_NAME = auto()
2116        POST_SCHEMA = auto()
2117        POST_WITH = auto()
2118        POST_ALIAS = auto()
2119        POST_EXPRESSION = auto()
2120        POST_INDEX = auto()
2121        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):
2136class Qualify(Expression):
2137    pass
key = 'qualify'
class Return(Expression):
2141class Return(Expression):
2142    pass
key = 'return'
class Reference(Expression):
2145class Reference(Expression):
2146    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2149class Tuple(Expression):
2150    arg_types = {"expressions": False}
2151
2152    def isin(
2153        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2154    ) -> In:
2155        return In(
2156            this=_maybe_copy(self, copy),
2157            expressions=[convert(e, copy=copy) for e in expressions],
2158            query=maybe_parse(query, copy=copy, **opts) if query else None,
2159        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2152    def isin(
2153        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2154    ) -> In:
2155        return In(
2156            this=_maybe_copy(self, copy),
2157            expressions=[convert(e, copy=copy) for e in expressions],
2158            query=maybe_parse(query, copy=copy, **opts) if query else None,
2159        )
key = 'tuple'
class Subqueryable(Unionable):
2162class Subqueryable(Unionable):
2163    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2164        """
2165        Convert this expression to an aliased expression that can be used as a Subquery.
2166
2167        Example:
2168            >>> subquery = Select().select("x").from_("tbl").subquery()
2169            >>> Select().select("x").from_(subquery).sql()
2170            'SELECT x FROM (SELECT x FROM tbl)'
2171
2172        Args:
2173            alias (str | Identifier): an optional alias for the subquery
2174            copy (bool): if `False`, modify this expression instance in-place.
2175
2176        Returns:
2177            Alias: the subquery
2178        """
2179        instance = _maybe_copy(self, copy)
2180        if not isinstance(alias, Expression):
2181            alias = TableAlias(this=to_identifier(alias)) if alias else None
2182
2183        return Subquery(this=instance, alias=alias)
2184
2185    def limit(
2186        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2187    ) -> Select:
2188        raise NotImplementedError
2189
2190    @property
2191    def ctes(self):
2192        with_ = self.args.get("with")
2193        if not with_:
2194            return []
2195        return with_.expressions
2196
2197    @property
2198    def selects(self) -> t.List[Expression]:
2199        raise NotImplementedError("Subqueryable objects must implement `selects`")
2200
2201    @property
2202    def named_selects(self) -> t.List[str]:
2203        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2204
2205    def with_(
2206        self,
2207        alias: ExpOrStr,
2208        as_: ExpOrStr,
2209        recursive: t.Optional[bool] = None,
2210        append: bool = True,
2211        dialect: DialectType = None,
2212        copy: bool = True,
2213        **opts,
2214    ) -> Subqueryable:
2215        """
2216        Append to or set the common table expressions.
2217
2218        Example:
2219            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2220            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2221
2222        Args:
2223            alias: the SQL code string to parse as the table name.
2224                If an `Expression` instance is passed, this is used as-is.
2225            as_: the SQL code string to parse as the table expression.
2226                If an `Expression` instance is passed, it will be used as-is.
2227            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2228            append: if `True`, add to any existing expressions.
2229                Otherwise, this resets the expressions.
2230            dialect: the dialect used to parse the input expression.
2231            copy: if `False`, modify this expression instance in-place.
2232            opts: other options to use to parse the input expressions.
2233
2234        Returns:
2235            The modified expression.
2236        """
2237        return _apply_cte_builder(
2238            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2239        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2163    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2164        """
2165        Convert this expression to an aliased expression that can be used as a Subquery.
2166
2167        Example:
2168            >>> subquery = Select().select("x").from_("tbl").subquery()
2169            >>> Select().select("x").from_(subquery).sql()
2170            'SELECT x FROM (SELECT x FROM tbl)'
2171
2172        Args:
2173            alias (str | Identifier): an optional alias for the subquery
2174            copy (bool): if `False`, modify this expression instance in-place.
2175
2176        Returns:
2177            Alias: the subquery
2178        """
2179        instance = _maybe_copy(self, copy)
2180        if not isinstance(alias, Expression):
2181            alias = TableAlias(this=to_identifier(alias)) if alias else None
2182
2183        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:
2185    def limit(
2186        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2187    ) -> Select:
2188        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:
2205    def with_(
2206        self,
2207        alias: ExpOrStr,
2208        as_: ExpOrStr,
2209        recursive: t.Optional[bool] = None,
2210        append: bool = True,
2211        dialect: DialectType = None,
2212        copy: bool = True,
2213        **opts,
2214    ) -> Subqueryable:
2215        """
2216        Append to or set the common table expressions.
2217
2218        Example:
2219            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2220            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2221
2222        Args:
2223            alias: the SQL code string to parse as the table name.
2224                If an `Expression` instance is passed, this is used as-is.
2225            as_: the SQL code string to parse as the table expression.
2226                If an `Expression` instance is passed, it will be used as-is.
2227            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2228            append: if `True`, add to any existing expressions.
2229                Otherwise, this resets the expressions.
2230            dialect: the dialect used to parse the input expression.
2231            copy: if `False`, modify this expression instance in-place.
2232            opts: other options to use to parse the input expressions.
2233
2234        Returns:
2235            The modified expression.
2236        """
2237        return _apply_cte_builder(
2238            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2239        )

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):
2266class WithTableHint(Expression):
2267    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2271class IndexTableHint(Expression):
2272    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2275class Table(Expression):
2276    arg_types = {
2277        "this": True,
2278        "alias": False,
2279        "db": False,
2280        "catalog": False,
2281        "laterals": False,
2282        "joins": False,
2283        "pivots": False,
2284        "hints": False,
2285        "system_time": False,
2286    }
2287
2288    @property
2289    def name(self) -> str:
2290        if isinstance(self.this, Func):
2291            return ""
2292        return self.this.name
2293
2294    @property
2295    def db(self) -> str:
2296        return self.text("db")
2297
2298    @property
2299    def catalog(self) -> str:
2300        return self.text("catalog")
2301
2302    @property
2303    def selects(self) -> t.List[Expression]:
2304        return []
2305
2306    @property
2307    def named_selects(self) -> t.List[str]:
2308        return []
2309
2310    @property
2311    def parts(self) -> t.List[Identifier]:
2312        """Return the parts of a table in order catalog, db, table."""
2313        parts: t.List[Identifier] = []
2314
2315        for arg in ("catalog", "db", "this"):
2316            part = self.args.get(arg)
2317
2318            if isinstance(part, Identifier):
2319                parts.append(part)
2320            elif isinstance(part, Dot):
2321                parts.extend(part.flatten())
2322
2323        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):
2327class SystemTime(Expression):
2328    arg_types = {
2329        "this": False,
2330        "expression": False,
2331        "kind": True,
2332    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2335class Union(Subqueryable):
2336    arg_types = {
2337        "with": False,
2338        "this": True,
2339        "expression": True,
2340        "distinct": False,
2341        **QUERY_MODIFIERS,
2342    }
2343
2344    def limit(
2345        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2346    ) -> Select:
2347        """
2348        Set the LIMIT expression.
2349
2350        Example:
2351            >>> select("1").union(select("1")).limit(1).sql()
2352            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2353
2354        Args:
2355            expression: the SQL code string to parse.
2356                This can also be an integer.
2357                If a `Limit` instance is passed, this is used as-is.
2358                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2359            dialect: the dialect used to parse the input expression.
2360            copy: if `False`, modify this expression instance in-place.
2361            opts: other options to use to parse the input expressions.
2362
2363        Returns:
2364            The limited subqueryable.
2365        """
2366        return (
2367            select("*")
2368            .from_(self.subquery(alias="_l_0", copy=copy))
2369            .limit(expression, dialect=dialect, copy=False, **opts)
2370        )
2371
2372    def select(
2373        self,
2374        *expressions: t.Optional[ExpOrStr],
2375        append: bool = True,
2376        dialect: DialectType = None,
2377        copy: bool = True,
2378        **opts,
2379    ) -> Union:
2380        """Append to or set the SELECT of the union recursively.
2381
2382        Example:
2383            >>> from sqlglot import parse_one
2384            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2385            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2386
2387        Args:
2388            *expressions: the SQL code strings to parse.
2389                If an `Expression` instance is passed, it will be used as-is.
2390            append: if `True`, add to any existing expressions.
2391                Otherwise, this resets the expressions.
2392            dialect: the dialect used to parse the input expressions.
2393            copy: if `False`, modify this expression instance in-place.
2394            opts: other options to use to parse the input expressions.
2395
2396        Returns:
2397            Union: the modified expression.
2398        """
2399        this = self.copy() if copy else self
2400        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2401        this.expression.unnest().select(
2402            *expressions, append=append, dialect=dialect, copy=False, **opts
2403        )
2404        return this
2405
2406    @property
2407    def named_selects(self) -> t.List[str]:
2408        return self.this.unnest().named_selects
2409
2410    @property
2411    def is_star(self) -> bool:
2412        return self.this.is_star or self.expression.is_star
2413
2414    @property
2415    def selects(self) -> t.List[Expression]:
2416        return self.this.unnest().selects
2417
2418    @property
2419    def left(self):
2420        return self.this
2421
2422    @property
2423    def right(self):
2424        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:
2344    def limit(
2345        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2346    ) -> Select:
2347        """
2348        Set the LIMIT expression.
2349
2350        Example:
2351            >>> select("1").union(select("1")).limit(1).sql()
2352            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2353
2354        Args:
2355            expression: the SQL code string to parse.
2356                This can also be an integer.
2357                If a `Limit` instance is passed, this is used as-is.
2358                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2359            dialect: the dialect used to parse the input expression.
2360            copy: if `False`, modify this expression instance in-place.
2361            opts: other options to use to parse the input expressions.
2362
2363        Returns:
2364            The limited subqueryable.
2365        """
2366        return (
2367            select("*")
2368            .from_(self.subquery(alias="_l_0", copy=copy))
2369            .limit(expression, dialect=dialect, copy=False, **opts)
2370        )

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

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:
2522    def group_by(
2523        self,
2524        *expressions: t.Optional[ExpOrStr],
2525        append: bool = True,
2526        dialect: DialectType = None,
2527        copy: bool = True,
2528        **opts,
2529    ) -> Select:
2530        """
2531        Set the GROUP BY expression.
2532
2533        Example:
2534            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2535            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2536
2537        Args:
2538            *expressions: the SQL code strings to parse.
2539                If a `Group` instance is passed, this is used as-is.
2540                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2541                If nothing is passed in then a group by is not applied to the expression
2542            append: if `True`, add to any existing expressions.
2543                Otherwise, this flattens all the `Group` expression into a single expression.
2544            dialect: the dialect used to parse the input expression.
2545            copy: if `False`, modify this expression instance in-place.
2546            opts: other options to use to parse the input expressions.
2547
2548        Returns:
2549            The modified Select expression.
2550        """
2551        if not expressions:
2552            return self if not copy else self.copy()
2553
2554        return _apply_child_list_builder(
2555            *expressions,
2556            instance=self,
2557            arg="group",
2558            append=append,
2559            copy=copy,
2560            prefix="GROUP BY",
2561            into=Group,
2562            dialect=dialect,
2563            **opts,
2564        )

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:
2566    def order_by(
2567        self,
2568        *expressions: t.Optional[ExpOrStr],
2569        append: bool = True,
2570        dialect: DialectType = None,
2571        copy: bool = True,
2572        **opts,
2573    ) -> Select:
2574        """
2575        Set the ORDER BY expression.
2576
2577        Example:
2578            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2579            'SELECT x FROM tbl ORDER BY x DESC'
2580
2581        Args:
2582            *expressions: the SQL code strings to parse.
2583                If a `Group` instance is passed, this is used as-is.
2584                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2585            append: if `True`, add to any existing expressions.
2586                Otherwise, this flattens all the `Order` expression into a single expression.
2587            dialect: the dialect used to parse the input expression.
2588            copy: if `False`, modify this expression instance in-place.
2589            opts: other options to use to parse the input expressions.
2590
2591        Returns:
2592            The modified Select expression.
2593        """
2594        return _apply_child_list_builder(
2595            *expressions,
2596            instance=self,
2597            arg="order",
2598            append=append,
2599            copy=copy,
2600            prefix="ORDER BY",
2601            into=Order,
2602            dialect=dialect,
2603            **opts,
2604        )

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

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

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:
2686    def limit(
2687        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2688    ) -> Select:
2689        """
2690        Set the LIMIT expression.
2691
2692        Example:
2693            >>> Select().from_("tbl").select("x").limit(10).sql()
2694            'SELECT x FROM tbl LIMIT 10'
2695
2696        Args:
2697            expression: the SQL code string to parse.
2698                This can also be an integer.
2699                If a `Limit` instance is passed, this is used as-is.
2700                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2701            dialect: the dialect used to parse the input expression.
2702            copy: if `False`, modify this expression instance in-place.
2703            opts: other options to use to parse the input expressions.
2704
2705        Returns:
2706            Select: the modified expression.
2707        """
2708        return _apply_builder(
2709            expression=expression,
2710            instance=self,
2711            arg="limit",
2712            into=Limit,
2713            prefix="LIMIT",
2714            dialect=dialect,
2715            copy=copy,
2716            **opts,
2717        )

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

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:
2752    def select(
2753        self,
2754        *expressions: t.Optional[ExpOrStr],
2755        append: bool = True,
2756        dialect: DialectType = None,
2757        copy: bool = True,
2758        **opts,
2759    ) -> Select:
2760        """
2761        Append to or set the SELECT expressions.
2762
2763        Example:
2764            >>> Select().select("x", "y").sql()
2765            'SELECT x, y'
2766
2767        Args:
2768            *expressions: the SQL code strings to parse.
2769                If an `Expression` instance is passed, it will be used as-is.
2770            append: if `True`, add to any existing expressions.
2771                Otherwise, this resets the expressions.
2772            dialect: the dialect used to parse the input expressions.
2773            copy: if `False`, modify this expression instance in-place.
2774            opts: other options to use to parse the input expressions.
2775
2776        Returns:
2777            The modified Select expression.
2778        """
2779        return _apply_list_builder(
2780            *expressions,
2781            instance=self,
2782            arg="expressions",
2783            append=append,
2784            dialect=dialect,
2785            copy=copy,
2786            **opts,
2787        )

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:
2789    def lateral(
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 LATERAL expressions.
2799
2800        Example:
2801            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2802            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
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="laterals",
2820            append=append,
2821            into=Lateral,
2822            prefix="LATERAL VIEW",
2823            dialect=dialect,
2824            copy=copy,
2825            **opts,
2826        )

Append to or set the LATERAL expressions.

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

The modified Select expression.

def join( self, expression: Union[str, sqlglot.expressions.Expression], on: Union[str, sqlglot.expressions.Expression, NoneType] = None, using: Union[str, sqlglot.expressions.Expression, List[Union[str, sqlglot.expressions.Expression]], NoneType] = None, append: bool = True, join_type: Optional[str] = None, join_alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2828    def join(
2829        self,
2830        expression: ExpOrStr,
2831        on: t.Optional[ExpOrStr] = None,
2832        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2833        append: bool = True,
2834        join_type: t.Optional[str] = None,
2835        join_alias: t.Optional[Identifier | str] = None,
2836        dialect: DialectType = None,
2837        copy: bool = True,
2838        **opts,
2839    ) -> Select:
2840        """
2841        Append to or set the JOIN expressions.
2842
2843        Example:
2844            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2845            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2846
2847            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2848            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2849
2850            Use `join_type` to change the type of join:
2851
2852            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2853            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2854
2855        Args:
2856            expression: the SQL code string to parse.
2857                If an `Expression` instance is passed, it will be used as-is.
2858            on: optionally specify the join "on" criteria as a SQL string.
2859                If an `Expression` instance is passed, it will be used as-is.
2860            using: optionally specify the join "using" criteria as a SQL string.
2861                If an `Expression` instance is passed, it will be used as-is.
2862            append: if `True`, add to any existing expressions.
2863                Otherwise, this resets the expressions.
2864            join_type: if set, alter the parsed join type.
2865            join_alias: an optional alias for the joined source.
2866            dialect: the dialect used to parse the input expressions.
2867            copy: if `False`, modify this expression instance in-place.
2868            opts: other options to use to parse the input expressions.
2869
2870        Returns:
2871            Select: the modified expression.
2872        """
2873        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2874
2875        try:
2876            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2877        except ParseError:
2878            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2879
2880        join = expression if isinstance(expression, Join) else Join(this=expression)
2881
2882        if isinstance(join.this, Select):
2883            join.this.replace(join.this.subquery())
2884
2885        if join_type:
2886            method: t.Optional[Token]
2887            side: t.Optional[Token]
2888            kind: t.Optional[Token]
2889
2890            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2891
2892            if method:
2893                join.set("method", method.text)
2894            if side:
2895                join.set("side", side.text)
2896            if kind:
2897                join.set("kind", kind.text)
2898
2899        if on:
2900            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2901            join.set("on", on)
2902
2903        if using:
2904            join = _apply_list_builder(
2905                *ensure_list(using),
2906                instance=join,
2907                arg="using",
2908                append=append,
2909                copy=copy,
2910                **opts,
2911            )
2912
2913        if join_alias:
2914            join.set("this", alias_(join.this, join_alias, table=True))
2915
2916        return _apply_list_builder(
2917            join,
2918            instance=self,
2919            arg="joins",
2920            append=append,
2921            copy=copy,
2922            **opts,
2923        )

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:
2925    def where(
2926        self,
2927        *expressions: t.Optional[ExpOrStr],
2928        append: bool = True,
2929        dialect: DialectType = None,
2930        copy: bool = True,
2931        **opts,
2932    ) -> Select:
2933        """
2934        Append to or set the WHERE expressions.
2935
2936        Example:
2937            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2938            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2939
2940        Args:
2941            *expressions: the SQL code strings to parse.
2942                If an `Expression` instance is passed, it will be used as-is.
2943                Multiple expressions are combined with an AND operator.
2944            append: if `True`, AND the new expressions to any existing expression.
2945                Otherwise, this resets the expression.
2946            dialect: the dialect used to parse the input expressions.
2947            copy: if `False`, modify this expression instance in-place.
2948            opts: other options to use to parse the input expressions.
2949
2950        Returns:
2951            Select: the modified expression.
2952        """
2953        return _apply_conjunction_builder(
2954            *expressions,
2955            instance=self,
2956            arg="where",
2957            append=append,
2958            into=Where,
2959            dialect=dialect,
2960            copy=copy,
2961            **opts,
2962        )

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

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:
3003    def window(
3004        self,
3005        *expressions: t.Optional[ExpOrStr],
3006        append: bool = True,
3007        dialect: DialectType = None,
3008        copy: bool = True,
3009        **opts,
3010    ) -> Select:
3011        return _apply_list_builder(
3012            *expressions,
3013            instance=self,
3014            arg="windows",
3015            append=append,
3016            into=Window,
3017            dialect=dialect,
3018            copy=copy,
3019            **opts,
3020        )
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:
3022    def qualify(
3023        self,
3024        *expressions: t.Optional[ExpOrStr],
3025        append: bool = True,
3026        dialect: DialectType = None,
3027        copy: bool = True,
3028        **opts,
3029    ) -> Select:
3030        return _apply_conjunction_builder(
3031            *expressions,
3032            instance=self,
3033            arg="qualify",
3034            append=append,
3035            into=Qualify,
3036            dialect=dialect,
3037            copy=copy,
3038            **opts,
3039        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3041    def distinct(
3042        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3043    ) -> Select:
3044        """
3045        Set the OFFSET expression.
3046
3047        Example:
3048            >>> Select().from_("tbl").select("x").distinct().sql()
3049            'SELECT DISTINCT x FROM tbl'
3050
3051        Args:
3052            ons: the expressions to distinct on
3053            distinct: whether the Select should be distinct
3054            copy: if `False`, modify this expression instance in-place.
3055
3056        Returns:
3057            Select: the modified expression.
3058        """
3059        instance = _maybe_copy(self, copy)
3060        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3061        instance.set("distinct", Distinct(on=on) if distinct else None)
3062        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:
3064    def ctas(
3065        self,
3066        table: ExpOrStr,
3067        properties: t.Optional[t.Dict] = None,
3068        dialect: DialectType = None,
3069        copy: bool = True,
3070        **opts,
3071    ) -> Create:
3072        """
3073        Convert this expression to a CREATE TABLE AS statement.
3074
3075        Example:
3076            >>> Select().select("*").from_("tbl").ctas("x").sql()
3077            'CREATE TABLE x AS SELECT * FROM tbl'
3078
3079        Args:
3080            table: the SQL code string to parse as the table name.
3081                If another `Expression` instance is passed, it will be used as-is.
3082            properties: an optional mapping of table properties
3083            dialect: the dialect used to parse the input table.
3084            copy: if `False`, modify this expression instance in-place.
3085            opts: other options to use to parse the input table.
3086
3087        Returns:
3088            The new Create expression.
3089        """
3090        instance = _maybe_copy(self, copy)
3091        table_expression = maybe_parse(
3092            table,
3093            into=Table,
3094            dialect=dialect,
3095            **opts,
3096        )
3097        properties_expression = None
3098        if properties:
3099            properties_expression = Properties.from_dict(properties)
3100
3101        return Create(
3102            this=table_expression,
3103            kind="table",
3104            expression=instance,
3105            properties=properties_expression,
3106        )

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:
3108    def lock(self, update: bool = True, copy: bool = True) -> Select:
3109        """
3110        Set the locking read mode for this expression.
3111
3112        Examples:
3113            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3114            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3115
3116            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3117            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3118
3119        Args:
3120            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3121            copy: if `False`, modify this expression instance in-place.
3122
3123        Returns:
3124            The modified expression.
3125        """
3126        inst = _maybe_copy(self, copy)
3127        inst.set("locks", [Lock(update=update)])
3128
3129        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:
3131    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3132        """
3133        Set hints for this expression.
3134
3135        Examples:
3136            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3137            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3138
3139        Args:
3140            hints: The SQL code strings to parse as the hints.
3141                If an `Expression` instance is passed, it will be used as-is.
3142            dialect: The dialect used to parse the hints.
3143            copy: If `False`, modify this expression instance in-place.
3144
3145        Returns:
3146            The modified expression.
3147        """
3148        inst = _maybe_copy(self, copy)
3149        inst.set(
3150            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3151        )
3152
3153        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):
3168class Subquery(DerivedTable, Unionable):
3169    arg_types = {
3170        "this": True,
3171        "alias": False,
3172        "with": False,
3173        **QUERY_MODIFIERS,
3174    }
3175
3176    def unnest(self):
3177        """
3178        Returns the first non subquery.
3179        """
3180        expression = self
3181        while isinstance(expression, Subquery):
3182            expression = expression.this
3183        return expression
3184
3185    @property
3186    def is_star(self) -> bool:
3187        return self.this.is_star
3188
3189    @property
3190    def output_name(self) -> str:
3191        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):
3176    def unnest(self):
3177        """
3178        Returns the first non subquery.
3179        """
3180        expression = self
3181        while isinstance(expression, Subquery):
3182            expression = expression.this
3183        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):
3194class TableSample(Expression):
3195    arg_types = {
3196        "this": False,
3197        "method": False,
3198        "bucket_numerator": False,
3199        "bucket_denominator": False,
3200        "bucket_field": False,
3201        "percent": False,
3202        "rows": False,
3203        "size": False,
3204        "seed": False,
3205        "kind": False,
3206    }
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):
3209class Tag(Expression):
3210    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3211
3212    arg_types = {
3213        "this": False,
3214        "prefix": False,
3215        "postfix": False,
3216    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3221class Pivot(Expression):
3222    arg_types = {
3223        "this": False,
3224        "alias": False,
3225        "expressions": True,
3226        "field": False,
3227        "unpivot": False,
3228        "using": False,
3229        "group": False,
3230        "columns": False,
3231    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3234class Window(Expression):
3235    arg_types = {
3236        "this": True,
3237        "partition_by": False,
3238        "order": False,
3239        "spec": False,
3240        "alias": False,
3241        "over": False,
3242        "first": False,
3243    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3246class WindowSpec(Expression):
3247    arg_types = {
3248        "kind": False,
3249        "start": False,
3250        "start_side": False,
3251        "end": False,
3252        "end_side": False,
3253    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3256class Where(Expression):
3257    pass
key = 'where'
class Star(Expression):
3260class Star(Expression):
3261    arg_types = {"except": False, "replace": False}
3262
3263    @property
3264    def name(self) -> str:
3265        return "*"
3266
3267    @property
3268    def output_name(self) -> str:
3269        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):
3272class Parameter(Condition):
3273    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3276class SessionParameter(Condition):
3277    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3280class Placeholder(Condition):
3281    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3284class Null(Condition):
3285    arg_types: t.Dict[str, t.Any] = {}
3286
3287    @property
3288    def name(self) -> str:
3289        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3292class Boolean(Condition):
3293    pass
key = 'boolean'
class DataTypeSize(Expression):
3296class DataTypeSize(Expression):
3297    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3300class DataType(Expression):
3301    arg_types = {
3302        "this": True,
3303        "expressions": False,
3304        "nested": False,
3305        "values": False,
3306        "prefix": False,
3307    }
3308
3309    class Type(AutoName):
3310        ARRAY = auto()
3311        BIGDECIMAL = auto()
3312        BIGINT = auto()
3313        BIGSERIAL = auto()
3314        BINARY = auto()
3315        BIT = auto()
3316        BOOLEAN = auto()
3317        CHAR = auto()
3318        DATE = auto()
3319        DATETIME = auto()
3320        DATETIME64 = auto()
3321        ENUM = auto()
3322        INT4RANGE = auto()
3323        INT4MULTIRANGE = auto()
3324        INT8RANGE = auto()
3325        INT8MULTIRANGE = auto()
3326        NUMRANGE = auto()
3327        NUMMULTIRANGE = auto()
3328        TSRANGE = auto()
3329        TSMULTIRANGE = auto()
3330        TSTZRANGE = auto()
3331        TSTZMULTIRANGE = auto()
3332        DATERANGE = auto()
3333        DATEMULTIRANGE = auto()
3334        DECIMAL = auto()
3335        DOUBLE = auto()
3336        FLOAT = auto()
3337        GEOGRAPHY = auto()
3338        GEOMETRY = auto()
3339        HLLSKETCH = auto()
3340        HSTORE = auto()
3341        IMAGE = auto()
3342        INET = auto()
3343        INT = auto()
3344        INT128 = auto()
3345        INT256 = auto()
3346        INTERVAL = auto()
3347        JSON = auto()
3348        JSONB = auto()
3349        LONGBLOB = auto()
3350        LONGTEXT = auto()
3351        MAP = auto()
3352        MEDIUMBLOB = auto()
3353        MEDIUMTEXT = auto()
3354        MONEY = auto()
3355        NCHAR = auto()
3356        NULL = auto()
3357        NULLABLE = auto()
3358        NVARCHAR = auto()
3359        OBJECT = auto()
3360        ROWVERSION = auto()
3361        SERIAL = auto()
3362        SET = auto()
3363        SMALLINT = auto()
3364        SMALLMONEY = auto()
3365        SMALLSERIAL = auto()
3366        STRUCT = auto()
3367        SUPER = auto()
3368        TEXT = auto()
3369        TIME = auto()
3370        TIMESTAMP = auto()
3371        TIMESTAMPTZ = auto()
3372        TIMESTAMPLTZ = auto()
3373        TINYINT = auto()
3374        UBIGINT = auto()
3375        UINT = auto()
3376        USMALLINT = auto()
3377        UTINYINT = auto()
3378        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3379        UINT128 = auto()
3380        UINT256 = auto()
3381        UNIQUEIDENTIFIER = auto()
3382        USERDEFINED = "USER-DEFINED"
3383        UUID = auto()
3384        VARBINARY = auto()
3385        VARCHAR = auto()
3386        VARIANT = auto()
3387        XML = auto()
3388
3389    TEXT_TYPES = {
3390        Type.CHAR,
3391        Type.NCHAR,
3392        Type.VARCHAR,
3393        Type.NVARCHAR,
3394        Type.TEXT,
3395    }
3396
3397    INTEGER_TYPES = {
3398        Type.INT,
3399        Type.TINYINT,
3400        Type.SMALLINT,
3401        Type.BIGINT,
3402        Type.INT128,
3403        Type.INT256,
3404    }
3405
3406    FLOAT_TYPES = {
3407        Type.FLOAT,
3408        Type.DOUBLE,
3409    }
3410
3411    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3412
3413    TEMPORAL_TYPES = {
3414        Type.TIME,
3415        Type.TIMESTAMP,
3416        Type.TIMESTAMPTZ,
3417        Type.TIMESTAMPLTZ,
3418        Type.DATE,
3419        Type.DATETIME,
3420        Type.DATETIME64,
3421    }
3422
3423    META_TYPES = {"UNKNOWN", "NULL"}
3424
3425    @classmethod
3426    def build(
3427        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3428    ) -> DataType:
3429        from sqlglot import parse_one
3430
3431        if isinstance(dtype, str):
3432            upper = dtype.upper()
3433            if upper in DataType.META_TYPES:
3434                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3435            else:
3436                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3437
3438            if data_type_exp is None:
3439                raise ValueError(f"Unparsable data type value: {dtype}")
3440        elif isinstance(dtype, DataType.Type):
3441            data_type_exp = DataType(this=dtype)
3442        elif isinstance(dtype, DataType):
3443            return dtype
3444        else:
3445            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3446
3447        return DataType(**{**data_type_exp.args, **kwargs})
3448
3449    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3450        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False}
TEXT_TYPES = {<Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.TEXT: 'TEXT'>, <Type.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>}
INTEGER_TYPES = {<Type.SMALLINT: 'SMALLINT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT256: 'INT256'>, <Type.INT128: 'INT128'>, <Type.INT: 'INT'>, <Type.TINYINT: 'TINYINT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.INT256: 'INT256'>, <Type.SMALLINT: 'SMALLINT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT128: 'INT128'>, <Type.DOUBLE: 'DOUBLE'>, <Type.INT: 'INT'>, <Type.TINYINT: 'TINYINT'>, <Type.FLOAT: 'FLOAT'>}
TEMPORAL_TYPES = {<Type.DATETIME: 'DATETIME'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.DATE: 'DATE'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.DATETIME64: 'DATETIME64'>, <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:
3425    @classmethod
3426    def build(
3427        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3428    ) -> DataType:
3429        from sqlglot import parse_one
3430
3431        if isinstance(dtype, str):
3432            upper = dtype.upper()
3433            if upper in DataType.META_TYPES:
3434                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3435            else:
3436                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3437
3438            if data_type_exp is None:
3439                raise ValueError(f"Unparsable data type value: {dtype}")
3440        elif isinstance(dtype, DataType.Type):
3441            data_type_exp = DataType(this=dtype)
3442        elif isinstance(dtype, DataType):
3443            return dtype
3444        else:
3445            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3446
3447        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3449    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3450        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3309    class Type(AutoName):
3310        ARRAY = auto()
3311        BIGDECIMAL = auto()
3312        BIGINT = auto()
3313        BIGSERIAL = auto()
3314        BINARY = auto()
3315        BIT = auto()
3316        BOOLEAN = auto()
3317        CHAR = auto()
3318        DATE = auto()
3319        DATETIME = auto()
3320        DATETIME64 = auto()
3321        ENUM = auto()
3322        INT4RANGE = auto()
3323        INT4MULTIRANGE = auto()
3324        INT8RANGE = auto()
3325        INT8MULTIRANGE = auto()
3326        NUMRANGE = auto()
3327        NUMMULTIRANGE = auto()
3328        TSRANGE = auto()
3329        TSMULTIRANGE = auto()
3330        TSTZRANGE = auto()
3331        TSTZMULTIRANGE = auto()
3332        DATERANGE = auto()
3333        DATEMULTIRANGE = auto()
3334        DECIMAL = auto()
3335        DOUBLE = auto()
3336        FLOAT = auto()
3337        GEOGRAPHY = auto()
3338        GEOMETRY = auto()
3339        HLLSKETCH = auto()
3340        HSTORE = auto()
3341        IMAGE = auto()
3342        INET = auto()
3343        INT = auto()
3344        INT128 = auto()
3345        INT256 = auto()
3346        INTERVAL = auto()
3347        JSON = auto()
3348        JSONB = auto()
3349        LONGBLOB = auto()
3350        LONGTEXT = auto()
3351        MAP = auto()
3352        MEDIUMBLOB = auto()
3353        MEDIUMTEXT = auto()
3354        MONEY = auto()
3355        NCHAR = auto()
3356        NULL = auto()
3357        NULLABLE = auto()
3358        NVARCHAR = auto()
3359        OBJECT = auto()
3360        ROWVERSION = auto()
3361        SERIAL = auto()
3362        SET = auto()
3363        SMALLINT = auto()
3364        SMALLMONEY = auto()
3365        SMALLSERIAL = auto()
3366        STRUCT = auto()
3367        SUPER = auto()
3368        TEXT = auto()
3369        TIME = auto()
3370        TIMESTAMP = auto()
3371        TIMESTAMPTZ = auto()
3372        TIMESTAMPLTZ = auto()
3373        TINYINT = auto()
3374        UBIGINT = auto()
3375        UINT = auto()
3376        USMALLINT = auto()
3377        UTINYINT = auto()
3378        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3379        UINT128 = auto()
3380        UINT256 = auto()
3381        UNIQUEIDENTIFIER = auto()
3382        USERDEFINED = "USER-DEFINED"
3383        UUID = auto()
3384        VARBINARY = auto()
3385        VARCHAR = auto()
3386        VARIANT = auto()
3387        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):
3454class PseudoType(Expression):
3455    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3459class SubqueryPredicate(Predicate):
3460    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3463class All(SubqueryPredicate):
3464    pass
key = 'all'
class Any(SubqueryPredicate):
3467class Any(SubqueryPredicate):
3468    pass
key = 'any'
class Exists(SubqueryPredicate):
3471class Exists(SubqueryPredicate):
3472    pass
key = 'exists'
class Command(Expression):
3477class Command(Expression):
3478    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3481class Transaction(Expression):
3482    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3485class Commit(Expression):
3486    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3489class Rollback(Expression):
3490    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3493class AlterTable(Expression):
3494    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3497class AddConstraint(Expression):
3498    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3501class DropPartition(Expression):
3502    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3506class Binary(Condition):
3507    arg_types = {"this": True, "expression": True}
3508
3509    @property
3510    def left(self):
3511        return self.this
3512
3513    @property
3514    def right(self):
3515        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3518class Add(Binary):
3519    pass
key = 'add'
class Connector(Binary):
3522class Connector(Binary):
3523    pass
key = 'connector'
class And(Connector):
3526class And(Connector):
3527    pass
key = 'and'
class Or(Connector):
3530class Or(Connector):
3531    pass
key = 'or'
class Xor(Connector):
3534class Xor(Connector):
3535    pass
key = 'xor'
class BitwiseAnd(Binary):
3538class BitwiseAnd(Binary):
3539    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3542class BitwiseLeftShift(Binary):
3543    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3546class BitwiseOr(Binary):
3547    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3550class BitwiseRightShift(Binary):
3551    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3554class BitwiseXor(Binary):
3555    pass
key = 'bitwisexor'
class Div(Binary):
3558class Div(Binary):
3559    pass
key = 'div'
class Overlaps(Binary):
3562class Overlaps(Binary):
3563    pass
key = 'overlaps'
class Dot(Binary):
3566class Dot(Binary):
3567    @property
3568    def name(self) -> str:
3569        return self.expression.name
3570
3571    @property
3572    def output_name(self) -> str:
3573        return self.name
3574
3575    @classmethod
3576    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3577        """Build a Dot object with a sequence of expressions."""
3578        if len(expressions) < 2:
3579            raise ValueError(f"Dot requires >= 2 expressions.")
3580
3581        a, b, *expressions = expressions
3582        dot = Dot(this=a, expression=b)
3583
3584        for expression in expressions:
3585            dot = Dot(this=dot, expression=expression)
3586
3587        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:
3575    @classmethod
3576    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3577        """Build a Dot object with a sequence of expressions."""
3578        if len(expressions) < 2:
3579            raise ValueError(f"Dot requires >= 2 expressions.")
3580
3581        a, b, *expressions = expressions
3582        dot = Dot(this=a, expression=b)
3583
3584        for expression in expressions:
3585            dot = Dot(this=dot, expression=expression)
3586
3587        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3590class DPipe(Binary):
3591    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3594class SafeDPipe(DPipe):
3595    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3598class EQ(Binary, Predicate):
3599    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3602class NullSafeEQ(Binary, Predicate):
3603    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3606class NullSafeNEQ(Binary, Predicate):
3607    pass
key = 'nullsafeneq'
class Distance(Binary):
3610class Distance(Binary):
3611    pass
key = 'distance'
class Escape(Binary):
3614class Escape(Binary):
3615    pass
key = 'escape'
class Glob(Binary, Predicate):
3618class Glob(Binary, Predicate):
3619    pass
key = 'glob'
class GT(Binary, Predicate):
3622class GT(Binary, Predicate):
3623    pass
key = 'gt'
class GTE(Binary, Predicate):
3626class GTE(Binary, Predicate):
3627    pass
key = 'gte'
class ILike(Binary, Predicate):
3630class ILike(Binary, Predicate):
3631    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3634class ILikeAny(Binary, Predicate):
3635    pass
key = 'ilikeany'
class IntDiv(Binary):
3638class IntDiv(Binary):
3639    pass
key = 'intdiv'
class Is(Binary, Predicate):
3642class Is(Binary, Predicate):
3643    pass
key = 'is'
class Kwarg(Binary):
3646class Kwarg(Binary):
3647    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3650class Like(Binary, Predicate):
3651    pass
key = 'like'
class LikeAny(Binary, Predicate):
3654class LikeAny(Binary, Predicate):
3655    pass
key = 'likeany'
class LT(Binary, Predicate):
3658class LT(Binary, Predicate):
3659    pass
key = 'lt'
class LTE(Binary, Predicate):
3662class LTE(Binary, Predicate):
3663    pass
key = 'lte'
class Mod(Binary):
3666class Mod(Binary):
3667    pass
key = 'mod'
class Mul(Binary):
3670class Mul(Binary):
3671    pass
key = 'mul'
class NEQ(Binary, Predicate):
3674class NEQ(Binary, Predicate):
3675    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3678class SimilarTo(Binary, Predicate):
3679    pass
key = 'similarto'
class Slice(Binary):
3682class Slice(Binary):
3683    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3686class Sub(Binary):
3687    pass
key = 'sub'
class ArrayOverlaps(Binary):
3690class ArrayOverlaps(Binary):
3691    pass
key = 'arrayoverlaps'
class Unary(Condition):
3696class Unary(Condition):
3697    pass
key = 'unary'
class BitwiseNot(Unary):
3700class BitwiseNot(Unary):
3701    pass
key = 'bitwisenot'
class Not(Unary):
3704class Not(Unary):
3705    pass
key = 'not'
class Paren(Unary):
3708class Paren(Unary):
3709    arg_types = {"this": True, "with": False}
3710
3711    @property
3712    def output_name(self) -> str:
3713        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):
3716class Neg(Unary):
3717    pass
key = 'neg'
class Alias(Expression):
3720class Alias(Expression):
3721    arg_types = {"this": True, "alias": False}
3722
3723    @property
3724    def output_name(self) -> str:
3725        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):
3728class Aliases(Expression):
3729    arg_types = {"this": True, "expressions": True}
3730
3731    @property
3732    def aliases(self):
3733        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3736class AtTimeZone(Expression):
3737    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3740class Between(Predicate):
3741    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3744class Bracket(Condition):
3745    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3748class SafeBracket(Bracket):
3749    """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):
3752class Distinct(Expression):
3753    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3756class In(Predicate):
3757    arg_types = {
3758        "this": True,
3759        "expressions": False,
3760        "query": False,
3761        "unnest": False,
3762        "field": False,
3763        "is_global": False,
3764    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3767class TimeUnit(Expression):
3768    """Automatically converts unit arg into a var."""
3769
3770    arg_types = {"unit": False}
3771
3772    def __init__(self, **args):
3773        unit = args.get("unit")
3774        if isinstance(unit, (Column, Literal)):
3775            args["unit"] = Var(this=unit.name)
3776        elif isinstance(unit, Week):
3777            unit.set("this", Var(this=unit.this.name))
3778
3779        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3772    def __init__(self, **args):
3773        unit = args.get("unit")
3774        if isinstance(unit, (Column, Literal)):
3775            args["unit"] = Var(this=unit.name)
3776        elif isinstance(unit, Week):
3777            unit.set("this", Var(this=unit.this.name))
3778
3779        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3782class Interval(TimeUnit):
3783    arg_types = {"this": False, "unit": False}
3784
3785    @property
3786    def unit(self) -> t.Optional[Var]:
3787        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3790class IgnoreNulls(Expression):
3791    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3794class RespectNulls(Expression):
3795    pass
key = 'respectnulls'
class Func(Condition):
3799class Func(Condition):
3800    """
3801    The base class for all function expressions.
3802
3803    Attributes:
3804        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3805            treated as a variable length argument and the argument's value will be stored as a list.
3806        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3807            for this function expression. These values are used to map this node to a name during parsing
3808            as well as to provide the function's name during SQL string generation. By default the SQL
3809            name is set to the expression's class name transformed to snake case.
3810    """
3811
3812    is_var_len_args = False
3813
3814    @classmethod
3815    def from_arg_list(cls, args):
3816        if cls.is_var_len_args:
3817            all_arg_keys = list(cls.arg_types)
3818            # If this function supports variable length argument treat the last argument as such.
3819            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3820            num_non_var = len(non_var_len_arg_keys)
3821
3822            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3823            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3824        else:
3825            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3826
3827        return cls(**args_dict)
3828
3829    @classmethod
3830    def sql_names(cls):
3831        if cls is Func:
3832            raise NotImplementedError(
3833                "SQL name is only supported by concrete function implementations"
3834            )
3835        if "_sql_names" not in cls.__dict__:
3836            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3837        return cls._sql_names
3838
3839    @classmethod
3840    def sql_name(cls):
3841        return cls.sql_names()[0]
3842
3843    @classmethod
3844    def default_parser_mappings(cls):
3845        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):
3814    @classmethod
3815    def from_arg_list(cls, args):
3816        if cls.is_var_len_args:
3817            all_arg_keys = list(cls.arg_types)
3818            # If this function supports variable length argument treat the last argument as such.
3819            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3820            num_non_var = len(non_var_len_arg_keys)
3821
3822            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3823            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3824        else:
3825            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3826
3827        return cls(**args_dict)
@classmethod
def sql_names(cls):
3829    @classmethod
3830    def sql_names(cls):
3831        if cls is Func:
3832            raise NotImplementedError(
3833                "SQL name is only supported by concrete function implementations"
3834            )
3835        if "_sql_names" not in cls.__dict__:
3836            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3837        return cls._sql_names
@classmethod
def sql_name(cls):
3839    @classmethod
3840    def sql_name(cls):
3841        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3843    @classmethod
3844    def default_parser_mappings(cls):
3845        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3848class AggFunc(Func):
3849    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3852class ParameterizedAgg(AggFunc):
3853    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3856class Abs(Func):
3857    pass
key = 'abs'
class Anonymous(Func):
3860class Anonymous(Func):
3861    arg_types = {"this": True, "expressions": False}
3862    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3867class Hll(AggFunc):
3868    arg_types = {"this": True, "expressions": False}
3869    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3872class ApproxDistinct(AggFunc):
3873    arg_types = {"this": True, "accuracy": False}
3874    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3877class Array(Func):
3878    arg_types = {"expressions": False}
3879    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3883class ToChar(Func):
3884    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3887class GenerateSeries(Func):
3888    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3891class ArrayAgg(AggFunc):
3892    pass
key = 'arrayagg'
class ArrayAll(Func):
3895class ArrayAll(Func):
3896    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3899class ArrayAny(Func):
3900    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3903class ArrayConcat(Func):
3904    arg_types = {"this": True, "expressions": False}
3905    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3908class ArrayContains(Binary, Func):
3909    pass
key = 'arraycontains'
class ArrayContained(Binary):
3912class ArrayContained(Binary):
3913    pass
key = 'arraycontained'
class ArrayFilter(Func):
3916class ArrayFilter(Func):
3917    arg_types = {"this": True, "expression": True}
3918    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3921class ArrayJoin(Func):
3922    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3925class ArraySize(Func):
3926    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3929class ArraySort(Func):
3930    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3933class ArraySum(Func):
3934    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3937class ArrayUnionAgg(AggFunc):
3938    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3941class Avg(AggFunc):
3942    pass
key = 'avg'
class AnyValue(AggFunc):
3945class AnyValue(AggFunc):
3946    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
3949class Case(Func):
3950    arg_types = {"this": False, "ifs": True, "default": False}
3951
3952    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3953        instance = _maybe_copy(self, copy)
3954        instance.append(
3955            "ifs",
3956            If(
3957                this=maybe_parse(condition, copy=copy, **opts),
3958                true=maybe_parse(then, copy=copy, **opts),
3959            ),
3960        )
3961        return instance
3962
3963    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3964        instance = _maybe_copy(self, copy)
3965        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3966        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:
3952    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3953        instance = _maybe_copy(self, copy)
3954        instance.append(
3955            "ifs",
3956            If(
3957                this=maybe_parse(condition, copy=copy, **opts),
3958                true=maybe_parse(then, copy=copy, **opts),
3959            ),
3960        )
3961        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3963    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3964        instance = _maybe_copy(self, copy)
3965        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3966        return instance
key = 'case'
class Cast(Func):
3969class Cast(Func):
3970    arg_types = {"this": True, "to": True, "format": False}
3971
3972    @property
3973    def name(self) -> str:
3974        return self.this.name
3975
3976    @property
3977    def to(self) -> DataType:
3978        return self.args["to"]
3979
3980    @property
3981    def output_name(self) -> str:
3982        return self.name
3983
3984    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3985        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:
3984    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3985        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
3988class CastToStrType(Func):
3989    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
3992class Collate(Binary):
3993    pass
key = 'collate'
class TryCast(Cast):
3996class TryCast(Cast):
3997    pass
key = 'trycast'
class Ceil(Func):
4000class Ceil(Func):
4001    arg_types = {"this": True, "decimals": False}
4002    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4005class Coalesce(Func):
4006    arg_types = {"this": True, "expressions": False}
4007    is_var_len_args = True
4008    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4011class Concat(Func):
4012    arg_types = {"expressions": True}
4013    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4016class SafeConcat(Concat):
4017    pass
key = 'safeconcat'
class ConcatWs(Concat):
4020class ConcatWs(Concat):
4021    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4024class Count(AggFunc):
4025    arg_types = {"this": False, "expressions": False}
4026    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4029class CountIf(AggFunc):
4030    pass
key = 'countif'
class CurrentDate(Func):
4033class CurrentDate(Func):
4034    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4037class CurrentDatetime(Func):
4038    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4041class CurrentTime(Func):
4042    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4045class CurrentTimestamp(Func):
4046    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4049class CurrentUser(Func):
4050    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4053class DateAdd(Func, TimeUnit):
4054    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4057class DateSub(Func, TimeUnit):
4058    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4061class DateDiff(Func, TimeUnit):
4062    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4063    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4066class DateTrunc(Func):
4067    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4070class DatetimeAdd(Func, TimeUnit):
4071    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4074class DatetimeSub(Func, TimeUnit):
4075    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4078class DatetimeDiff(Func, TimeUnit):
4079    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4082class DatetimeTrunc(Func, TimeUnit):
4083    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4086class DayOfWeek(Func):
4087    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4090class DayOfMonth(Func):
4091    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4094class DayOfYear(Func):
4095    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4098class WeekOfYear(Func):
4099    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4102class MonthsBetween(Func):
4103    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4106class LastDateOfMonth(Func):
4107    pass
key = 'lastdateofmonth'
class Extract(Func):
4110class Extract(Func):
4111    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4114class TimestampAdd(Func, TimeUnit):
4115    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4118class TimestampSub(Func, TimeUnit):
4119    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4122class TimestampDiff(Func, TimeUnit):
4123    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4126class TimestampTrunc(Func, TimeUnit):
4127    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4130class TimeAdd(Func, TimeUnit):
4131    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4134class TimeSub(Func, TimeUnit):
4135    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4138class TimeDiff(Func, TimeUnit):
4139    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4142class TimeTrunc(Func, TimeUnit):
4143    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4146class DateFromParts(Func):
4147    _sql_names = ["DATEFROMPARTS"]
4148    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4151class DateStrToDate(Func):
4152    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4155class DateToDateStr(Func):
4156    pass
key = 'datetodatestr'
class DateToDi(Func):
4159class DateToDi(Func):
4160    pass
key = 'datetodi'
class Date(Func):
4164class Date(Func):
4165    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4168class Day(Func):
4169    pass
key = 'day'
class Decode(Func):
4172class Decode(Func):
4173    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4176class DiToDate(Func):
4177    pass
key = 'ditodate'
class Encode(Func):
4180class Encode(Func):
4181    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4184class Exp(Func):
4185    pass
key = 'exp'
class Explode(Func):
4188class Explode(Func):
4189    pass
key = 'explode'
class Floor(Func):
4192class Floor(Func):
4193    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4196class FromBase64(Func):
4197    pass
key = 'frombase64'
class ToBase64(Func):
4200class ToBase64(Func):
4201    pass
key = 'tobase64'
class Greatest(Func):
4204class Greatest(Func):
4205    arg_types = {"this": True, "expressions": False}
4206    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4209class GroupConcat(Func):
4210    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4213class Hex(Func):
4214    pass
key = 'hex'
class If(Func):
4217class If(Func):
4218    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4221class Initcap(Func):
4222    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4225class JSONKeyValue(Expression):
4226    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4229class JSONObject(Func):
4230    arg_types = {
4231        "expressions": False,
4232        "null_handling": False,
4233        "unique_keys": False,
4234        "return_type": False,
4235        "format_json": False,
4236        "encoding": False,
4237    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4240class OpenJSONColumnDef(Expression):
4241    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):
4244class OpenJSON(Func):
4245    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4248class JSONBContains(Binary):
4249    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4252class JSONExtract(Binary, Func):
4253    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4256class JSONExtractScalar(JSONExtract):
4257    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4260class JSONBExtract(JSONExtract):
4261    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4264class JSONBExtractScalar(JSONExtract):
4265    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4268class JSONFormat(Func):
4269    arg_types = {"this": False, "options": False}
4270    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4274class JSONArrayContains(Binary, Predicate, Func):
4275    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4278class Least(Func):
4279    arg_types = {"this": True, "expressions": False}
4280    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4283class Left(Func):
4284    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4291class Length(Func):
4292    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4295class Levenshtein(Func):
4296    arg_types = {
4297        "this": True,
4298        "expression": False,
4299        "ins_cost": False,
4300        "del_cost": False,
4301        "sub_cost": False,
4302    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4305class Ln(Func):
4306    pass
key = 'ln'
class Log(Func):
4309class Log(Func):
4310    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4313class Log2(Func):
4314    pass
key = 'log2'
class Log10(Func):
4317class Log10(Func):
4318    pass
key = 'log10'
class LogicalOr(AggFunc):
4321class LogicalOr(AggFunc):
4322    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4325class LogicalAnd(AggFunc):
4326    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4329class Lower(Func):
4330    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4333class Map(Func):
4334    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4337class MapFromEntries(Func):
4338    pass
key = 'mapfromentries'
class StarMap(Func):
4341class StarMap(Func):
4342    pass
key = 'starmap'
class VarMap(Func):
4345class VarMap(Func):
4346    arg_types = {"keys": True, "values": True}
4347    is_var_len_args = True
4348
4349    @property
4350    def keys(self) -> t.List[Expression]:
4351        return self.args["keys"].expressions
4352
4353    @property
4354    def values(self) -> t.List[Expression]:
4355        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4359class MatchAgainst(Func):
4360    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4363class Max(AggFunc):
4364    arg_types = {"this": True, "expressions": False}
4365    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4368class MD5(Func):
4369    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4373class MD5Digest(Func):
4374    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4377class Min(AggFunc):
4378    arg_types = {"this": True, "expressions": False}
4379    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4382class Month(Func):
4383    pass
key = 'month'
class Nvl2(Func):
4386class Nvl2(Func):
4387    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4390class Posexplode(Func):
4391    pass
key = 'posexplode'
class Pow(Binary, Func):
4394class Pow(Binary, Func):
4395    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4398class PercentileCont(AggFunc):
4399    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4402class PercentileDisc(AggFunc):
4403    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4406class Quantile(AggFunc):
4407    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4410class ApproxQuantile(Quantile):
4411    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):
4414class RangeN(Func):
4415    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4418class ReadCSV(Func):
4419    _sql_names = ["READ_CSV"]
4420    is_var_len_args = True
4421    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4424class Reduce(Func):
4425    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):
4428class RegexpExtract(Func):
4429    arg_types = {
4430        "this": True,
4431        "expression": True,
4432        "position": False,
4433        "occurrence": False,
4434        "parameters": False,
4435        "group": False,
4436    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4439class RegexpReplace(Func):
4440    arg_types = {
4441        "this": True,
4442        "expression": True,
4443        "replacement": True,
4444        "position": False,
4445        "occurrence": False,
4446        "parameters": False,
4447    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Func):
4450class RegexpLike(Func):
4451    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4454class RegexpILike(Func):
4455    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4460class RegexpSplit(Func):
4461    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4464class Repeat(Func):
4465    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4468class Round(Func):
4469    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4472class RowNumber(Func):
4473    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4476class SafeDivide(Func):
4477    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4480class SetAgg(AggFunc):
4481    pass
key = 'setagg'
class SHA(Func):
4484class SHA(Func):
4485    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4488class SHA2(Func):
4489    _sql_names = ["SHA2"]
4490    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4493class SortArray(Func):
4494    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4497class Split(Func):
4498    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4503class Substring(Func):
4504    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4507class StandardHash(Func):
4508    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4511class StrPosition(Func):
4512    arg_types = {
4513        "this": True,
4514        "substr": True,
4515        "position": False,
4516        "instance": False,
4517    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4520class StrToDate(Func):
4521    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4524class StrToTime(Func):
4525    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4530class StrToUnix(Func):
4531    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4534class NumberToStr(Func):
4535    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4538class FromBase(Func):
4539    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4542class Struct(Func):
4543    arg_types = {"expressions": True}
4544    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4547class StructExtract(Func):
4548    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4551class Sum(AggFunc):
4552    pass
key = 'sum'
class Sqrt(Func):
4555class Sqrt(Func):
4556    pass
key = 'sqrt'
class Stddev(AggFunc):
4559class Stddev(AggFunc):
4560    pass
key = 'stddev'
class StddevPop(AggFunc):
4563class StddevPop(AggFunc):
4564    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4567class StddevSamp(AggFunc):
4568    pass
key = 'stddevsamp'
class TimeToStr(Func):
4571class TimeToStr(Func):
4572    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4575class TimeToTimeStr(Func):
4576    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4579class TimeToUnix(Func):
4580    pass
key = 'timetounix'
class TimeStrToDate(Func):
4583class TimeStrToDate(Func):
4584    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4587class TimeStrToTime(Func):
4588    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4591class TimeStrToUnix(Func):
4592    pass
key = 'timestrtounix'
class Trim(Func):
4595class Trim(Func):
4596    arg_types = {
4597        "this": True,
4598        "expression": False,
4599        "position": False,
4600        "collation": False,
4601    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4604class TsOrDsAdd(Func, TimeUnit):
4605    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4608class TsOrDsToDateStr(Func):
4609    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4612class TsOrDsToDate(Func):
4613    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4616class TsOrDiToDi(Func):
4617    pass
key = 'tsorditodi'
class Unhex(Func):
4620class Unhex(Func):
4621    pass
key = 'unhex'
class UnixToStr(Func):
4624class UnixToStr(Func):
4625    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4630class UnixToTime(Func):
4631    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4632
4633    SECONDS = Literal.string("seconds")
4634    MILLIS = Literal.string("millis")
4635    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):
4638class UnixToTimeStr(Func):
4639    pass
key = 'unixtotimestr'
class Upper(Func):
4642class Upper(Func):
4643    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4646class Variance(AggFunc):
4647    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4650class VariancePop(AggFunc):
4651    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4654class Week(Func):
4655    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4658class XMLTable(Func):
4659    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):
4662class Year(Func):
4663    pass
key = 'year'
class Use(Expression):
4666class Use(Expression):
4667    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4670class Merge(Expression):
4671    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):
4674class When(Func):
4675    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):
4680class NextValueFor(Func):
4681    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.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.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:
4718def maybe_parse(
4719    sql_or_expression: ExpOrStr,
4720    *,
4721    into: t.Optional[IntoType] = None,
4722    dialect: DialectType = None,
4723    prefix: t.Optional[str] = None,
4724    copy: bool = False,
4725    **opts,
4726) -> Expression:
4727    """Gracefully handle a possible string or expression.
4728
4729    Example:
4730        >>> maybe_parse("1")
4731        (LITERAL this: 1, is_string: False)
4732        >>> maybe_parse(to_identifier("x"))
4733        (IDENTIFIER this: x, quoted: False)
4734
4735    Args:
4736        sql_or_expression: the SQL code string or an expression
4737        into: the SQLGlot Expression to parse into
4738        dialect: the dialect used to parse the input expressions (in the case that an
4739            input expression is a SQL string).
4740        prefix: a string to prefix the sql with before it gets parsed
4741            (automatically includes a space)
4742        copy: whether or not to copy the expression.
4743        **opts: other options to use to parse the input expressions (again, in the case
4744            that an input expression is a SQL string).
4745
4746    Returns:
4747        Expression: the parsed or given expression.
4748    """
4749    if isinstance(sql_or_expression, Expression):
4750        if copy:
4751            return sql_or_expression.copy()
4752        return sql_or_expression
4753
4754    if sql_or_expression is None:
4755        raise ParseError(f"SQL cannot be None")
4756
4757    import sqlglot
4758
4759    sql = str(sql_or_expression)
4760    if prefix:
4761        sql = f"{prefix} {sql}"
4762
4763    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:
4947def union(
4948    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4949) -> Union:
4950    """
4951    Initializes a syntax tree from one UNION expression.
4952
4953    Example:
4954        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4955        'SELECT * FROM foo UNION SELECT * FROM bla'
4956
4957    Args:
4958        left: the SQL code string corresponding to the left-hand side.
4959            If an `Expression` instance is passed, it will be used as-is.
4960        right: the SQL code string corresponding to the right-hand side.
4961            If an `Expression` instance is passed, it will be used as-is.
4962        distinct: set the DISTINCT flag if and only if this is true.
4963        dialect: the dialect used to parse the input expression.
4964        opts: other options to use to parse the input expressions.
4965
4966    Returns:
4967        The new Union instance.
4968    """
4969    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4970    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4971
4972    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:
4975def intersect(
4976    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4977) -> Intersect:
4978    """
4979    Initializes a syntax tree from one INTERSECT expression.
4980
4981    Example:
4982        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4983        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4984
4985    Args:
4986        left: the SQL code string corresponding to the left-hand side.
4987            If an `Expression` instance is passed, it will be used as-is.
4988        right: the SQL code string corresponding to the right-hand side.
4989            If an `Expression` instance is passed, it will be used as-is.
4990        distinct: set the DISTINCT flag if and only if this is true.
4991        dialect: the dialect used to parse the input expression.
4992        opts: other options to use to parse the input expressions.
4993
4994    Returns:
4995        The new Intersect instance.
4996    """
4997    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4998    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4999
5000    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:
5003def except_(
5004    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5005) -> Except:
5006    """
5007    Initializes a syntax tree from one EXCEPT expression.
5008
5009    Example:
5010        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5011        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5012
5013    Args:
5014        left: the SQL code string corresponding to the left-hand side.
5015            If an `Expression` instance is passed, it will be used as-is.
5016        right: the SQL code string corresponding to the right-hand side.
5017            If an `Expression` instance is passed, it will be used as-is.
5018        distinct: set the DISTINCT flag if and only if this is true.
5019        dialect: the dialect used to parse the input expression.
5020        opts: other options to use to parse the input expressions.
5021
5022    Returns:
5023        The new Except instance.
5024    """
5025    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5026    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5027
5028    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:
5031def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5032    """
5033    Initializes a syntax tree from one or multiple SELECT expressions.
5034
5035    Example:
5036        >>> select("col1", "col2").from_("tbl").sql()
5037        'SELECT col1, col2 FROM tbl'
5038
5039    Args:
5040        *expressions: the SQL code string to parse as the expressions of a
5041            SELECT statement. If an Expression instance is passed, this is used as-is.
5042        dialect: the dialect used to parse the input expressions (in the case that an
5043            input expression is a SQL string).
5044        **opts: other options to use to parse the input expressions (again, in the case
5045            that an input expression is a SQL string).
5046
5047    Returns:
5048        Select: the syntax tree for the SELECT statement.
5049    """
5050    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:
5053def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5054    """
5055    Initializes a syntax tree from a FROM expression.
5056
5057    Example:
5058        >>> from_("tbl").select("col1", "col2").sql()
5059        'SELECT col1, col2 FROM tbl'
5060
5061    Args:
5062        *expression: the SQL code string to parse as the FROM expressions of a
5063            SELECT statement. If an Expression instance is passed, this is used as-is.
5064        dialect: the dialect used to parse the input expression (in the case that the
5065            input expression is a SQL string).
5066        **opts: other options to use to parse the input expressions (again, in the case
5067            that the input expression is a SQL string).
5068
5069    Returns:
5070        Select: the syntax tree for the SELECT statement.
5071    """
5072    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:
5075def update(
5076    table: str | Table,
5077    properties: dict,
5078    where: t.Optional[ExpOrStr] = None,
5079    from_: t.Optional[ExpOrStr] = None,
5080    dialect: DialectType = None,
5081    **opts,
5082) -> Update:
5083    """
5084    Creates an update statement.
5085
5086    Example:
5087        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5088        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5089
5090    Args:
5091        *properties: dictionary of properties to set which are
5092            auto converted to sql objects eg None -> NULL
5093        where: sql conditional parsed into a WHERE statement
5094        from_: sql statement parsed into a FROM statement
5095        dialect: the dialect used to parse the input expressions.
5096        **opts: other options to use to parse the input expressions.
5097
5098    Returns:
5099        Update: the syntax tree for the UPDATE statement.
5100    """
5101    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5102    update_expr.set(
5103        "expressions",
5104        [
5105            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5106            for k, v in properties.items()
5107        ],
5108    )
5109    if from_:
5110        update_expr.set(
5111            "from",
5112            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5113        )
5114    if isinstance(where, Condition):
5115        where = Where(this=where)
5116    if where:
5117        update_expr.set(
5118            "where",
5119            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5120        )
5121    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:
5124def delete(
5125    table: ExpOrStr,
5126    where: t.Optional[ExpOrStr] = None,
5127    returning: t.Optional[ExpOrStr] = None,
5128    dialect: DialectType = None,
5129    **opts,
5130) -> Delete:
5131    """
5132    Builds a delete statement.
5133
5134    Example:
5135        >>> delete("my_table", where="id > 1").sql()
5136        'DELETE FROM my_table WHERE id > 1'
5137
5138    Args:
5139        where: sql conditional parsed into a WHERE statement
5140        returning: sql conditional parsed into a RETURNING statement
5141        dialect: the dialect used to parse the input expressions.
5142        **opts: other options to use to parse the input expressions.
5143
5144    Returns:
5145        Delete: the syntax tree for the DELETE statement.
5146    """
5147    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5148    if where:
5149        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5150    if returning:
5151        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5152    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:
5155def insert(
5156    expression: ExpOrStr,
5157    into: ExpOrStr,
5158    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5159    overwrite: t.Optional[bool] = None,
5160    dialect: DialectType = None,
5161    copy: bool = True,
5162    **opts,
5163) -> Insert:
5164    """
5165    Builds an INSERT statement.
5166
5167    Example:
5168        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5169        'INSERT INTO tbl VALUES (1, 2, 3)'
5170
5171    Args:
5172        expression: the sql string or expression of the INSERT statement
5173        into: the tbl to insert data to.
5174        columns: optionally the table's column names.
5175        overwrite: whether to INSERT OVERWRITE or not.
5176        dialect: the dialect used to parse the input expressions.
5177        copy: whether or not to copy the expression.
5178        **opts: other options to use to parse the input expressions.
5179
5180    Returns:
5181        Insert: the syntax tree for the INSERT statement.
5182    """
5183    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5184    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5185
5186    if columns:
5187        this = _apply_list_builder(
5188            *columns,
5189            instance=Schema(this=this),
5190            arg="expressions",
5191            into=Identifier,
5192            copy=False,
5193            dialect=dialect,
5194            **opts,
5195        )
5196
5197    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:
5200def condition(
5201    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5202) -> Condition:
5203    """
5204    Initialize a logical condition expression.
5205
5206    Example:
5207        >>> condition("x=1").sql()
5208        'x = 1'
5209
5210        This is helpful for composing larger logical syntax trees:
5211        >>> where = condition("x=1")
5212        >>> where = where.and_("y=1")
5213        >>> Select().from_("tbl").select("*").where(where).sql()
5214        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5215
5216    Args:
5217        *expression: the SQL code string to parse.
5218            If an Expression instance is passed, this is used as-is.
5219        dialect: the dialect used to parse the input expression (in the case that the
5220            input expression is a SQL string).
5221        copy: Whether or not to copy `expression` (only applies to expressions).
5222        **opts: other options to use to parse the input expressions (again, in the case
5223            that the input expression is a SQL string).
5224
5225    Returns:
5226        The new Condition instance
5227    """
5228    return maybe_parse(
5229        expression,
5230        into=Condition,
5231        dialect=dialect,
5232        copy=copy,
5233        **opts,
5234    )

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:
5237def and_(
5238    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5239) -> Condition:
5240    """
5241    Combine multiple conditions with an AND logical operator.
5242
5243    Example:
5244        >>> and_("x=1", and_("y=1", "z=1")).sql()
5245        'x = 1 AND (y = 1 AND z = 1)'
5246
5247    Args:
5248        *expressions: the SQL code strings to parse.
5249            If an Expression instance is passed, this is used as-is.
5250        dialect: the dialect used to parse the input expression.
5251        copy: whether or not to copy `expressions` (only applies to Expressions).
5252        **opts: other options to use to parse the input expressions.
5253
5254    Returns:
5255        And: the new condition
5256    """
5257    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:
5260def or_(
5261    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5262) -> Condition:
5263    """
5264    Combine multiple conditions with an OR logical operator.
5265
5266    Example:
5267        >>> or_("x=1", or_("y=1", "z=1")).sql()
5268        'x = 1 OR (y = 1 OR z = 1)'
5269
5270    Args:
5271        *expressions: the SQL code strings to parse.
5272            If an Expression instance is passed, this is used as-is.
5273        dialect: the dialect used to parse the input expression.
5274        copy: whether or not to copy `expressions` (only applies to Expressions).
5275        **opts: other options to use to parse the input expressions.
5276
5277    Returns:
5278        Or: the new condition
5279    """
5280    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:
5283def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5284    """
5285    Wrap a condition with a NOT operator.
5286
5287    Example:
5288        >>> not_("this_suit='black'").sql()
5289        "NOT this_suit = 'black'"
5290
5291    Args:
5292        expression: the SQL code string to parse.
5293            If an Expression instance is passed, this is used as-is.
5294        dialect: the dialect used to parse the input expression.
5295        copy: whether to copy the expression or not.
5296        **opts: other options to use to parse the input expressions.
5297
5298    Returns:
5299        The new condition.
5300    """
5301    this = condition(
5302        expression,
5303        dialect=dialect,
5304        copy=copy,
5305        **opts,
5306    )
5307    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:
5310def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5311    """
5312    Wrap an expression in parentheses.
5313
5314    Example:
5315        >>> paren("5 + 3").sql()
5316        '(5 + 3)'
5317
5318    Args:
5319        expression: the SQL code string to parse.
5320            If an Expression instance is passed, this is used as-is.
5321        copy: whether to copy the expression or not.
5322
5323    Returns:
5324        The wrapped expression.
5325    """
5326    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):
5344def to_identifier(name, quoted=None, copy=True):
5345    """Builds an identifier.
5346
5347    Args:
5348        name: The name to turn into an identifier.
5349        quoted: Whether or not force quote the identifier.
5350        copy: Whether or not to copy a passed in Identefier node.
5351
5352    Returns:
5353        The identifier ast node.
5354    """
5355
5356    if name is None:
5357        return None
5358
5359    if isinstance(name, Identifier):
5360        identifier = _maybe_copy(name, copy)
5361    elif isinstance(name, str):
5362        identifier = Identifier(
5363            this=name,
5364            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5365        )
5366    else:
5367        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5368    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:
5374def to_interval(interval: str | Literal) -> Interval:
5375    """Builds an interval expression from a string like '1 day' or '5 months'."""
5376    if isinstance(interval, Literal):
5377        if not interval.is_string:
5378            raise ValueError("Invalid interval string.")
5379
5380        interval = interval.this
5381
5382    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5383
5384    if not interval_parts:
5385        raise ValueError("Invalid interval string.")
5386
5387    return Interval(
5388        this=Literal.string(interval_parts.group(1)),
5389        unit=Var(this=interval_parts.group(2)),
5390    )

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]:
5403def to_table(
5404    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5405) -> t.Optional[Table]:
5406    """
5407    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5408    If a table is passed in then that table is returned.
5409
5410    Args:
5411        sql_path: a `[catalog].[schema].[table]` string.
5412        dialect: the source dialect according to which the table name will be parsed.
5413        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5414
5415    Returns:
5416        A table expression.
5417    """
5418    if sql_path is None or isinstance(sql_path, Table):
5419        return sql_path
5420    if not isinstance(sql_path, str):
5421        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5422
5423    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5424    if table:
5425        for k, v in kwargs.items():
5426            table.set(k, v)
5427
5428    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:
5431def to_column(sql_path: str | Column, **kwargs) -> Column:
5432    """
5433    Create a column from a `[table].[column]` sql path. Schema is optional.
5434
5435    If a column is passed in then that column is returned.
5436
5437    Args:
5438        sql_path: `[table].[column]` string
5439    Returns:
5440        Table: A column expression
5441    """
5442    if sql_path is None or isinstance(sql_path, Column):
5443        return sql_path
5444    if not isinstance(sql_path, str):
5445        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5446    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):
5449def alias_(
5450    expression: ExpOrStr,
5451    alias: str | Identifier,
5452    table: bool | t.Sequence[str | Identifier] = False,
5453    quoted: t.Optional[bool] = None,
5454    dialect: DialectType = None,
5455    copy: bool = True,
5456    **opts,
5457):
5458    """Create an Alias expression.
5459
5460    Example:
5461        >>> alias_('foo', 'bar').sql()
5462        'foo AS bar'
5463
5464        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5465        '(SELECT 1, 2) AS bar(a, b)'
5466
5467    Args:
5468        expression: the SQL code strings to parse.
5469            If an Expression instance is passed, this is used as-is.
5470        alias: the alias name to use. If the name has
5471            special characters it is quoted.
5472        table: Whether or not to create a table alias, can also be a list of columns.
5473        quoted: whether or not to quote the alias
5474        dialect: the dialect used to parse the input expression.
5475        copy: Whether or not to copy the expression.
5476        **opts: other options to use to parse the input expressions.
5477
5478    Returns:
5479        Alias: the aliased expression
5480    """
5481    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5482    alias = to_identifier(alias, quoted=quoted)
5483
5484    if table:
5485        table_alias = TableAlias(this=alias)
5486        exp.set("alias", table_alias)
5487
5488        if not isinstance(table, bool):
5489            for column in table:
5490                table_alias.append("columns", to_identifier(column, quoted=quoted))
5491
5492        return exp
5493
5494    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5495    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5496    # for the complete Window expression.
5497    #
5498    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5499
5500    if "alias" in exp.arg_types and not isinstance(exp, Window):
5501        exp.set("alias", alias)
5502        return exp
5503    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:
5506def subquery(
5507    expression: ExpOrStr,
5508    alias: t.Optional[Identifier | str] = None,
5509    dialect: DialectType = None,
5510    **opts,
5511) -> Select:
5512    """
5513    Build a subquery expression.
5514
5515    Example:
5516        >>> subquery('select x from tbl', 'bar').select('x').sql()
5517        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5518
5519    Args:
5520        expression: the SQL code strings to parse.
5521            If an Expression instance is passed, this is used as-is.
5522        alias: the alias name to use.
5523        dialect: the dialect used to parse the input expression.
5524        **opts: other options to use to parse the input expressions.
5525
5526    Returns:
5527        A new Select instance with the subquery expression included.
5528    """
5529
5530    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5531    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:
5534def column(
5535    col: str | Identifier,
5536    table: t.Optional[str | Identifier] = None,
5537    db: t.Optional[str | Identifier] = None,
5538    catalog: t.Optional[str | Identifier] = None,
5539    quoted: t.Optional[bool] = None,
5540) -> Column:
5541    """
5542    Build a Column.
5543
5544    Args:
5545        col: Column name.
5546        table: Table name.
5547        db: Database name.
5548        catalog: Catalog name.
5549        quoted: Whether to force quotes on the column's identifiers.
5550
5551    Returns:
5552        The new Column instance.
5553    """
5554    return Column(
5555        this=to_identifier(col, quoted=quoted),
5556        table=to_identifier(table, quoted=quoted),
5557        db=to_identifier(db, quoted=quoted),
5558        catalog=to_identifier(catalog, quoted=quoted),
5559    )

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:
5562def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5563    """Cast an expression to a data type.
5564
5565    Example:
5566        >>> cast('x + 1', 'int').sql()
5567        'CAST(x + 1 AS INT)'
5568
5569    Args:
5570        expression: The expression to cast.
5571        to: The datatype to cast to.
5572
5573    Returns:
5574        The new Cast instance.
5575    """
5576    expression = maybe_parse(expression, **opts)
5577    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:
5580def table_(
5581    table: Identifier | str,
5582    db: t.Optional[Identifier | str] = None,
5583    catalog: t.Optional[Identifier | str] = None,
5584    quoted: t.Optional[bool] = None,
5585    alias: t.Optional[Identifier | str] = None,
5586) -> Table:
5587    """Build a Table.
5588
5589    Args:
5590        table: Table name.
5591        db: Database name.
5592        catalog: Catalog name.
5593        quote: Whether to force quotes on the table's identifiers.
5594        alias: Table's alias.
5595
5596    Returns:
5597        The new Table instance.
5598    """
5599    return Table(
5600        this=to_identifier(table, quoted=quoted),
5601        db=to_identifier(db, quoted=quoted),
5602        catalog=to_identifier(catalog, quoted=quoted),
5603        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5604    )

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:
5607def values(
5608    values: t.Iterable[t.Tuple[t.Any, ...]],
5609    alias: t.Optional[str] = None,
5610    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5611) -> Values:
5612    """Build VALUES statement.
5613
5614    Example:
5615        >>> values([(1, '2')]).sql()
5616        "VALUES (1, '2')"
5617
5618    Args:
5619        values: values statements that will be converted to SQL
5620        alias: optional alias
5621        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5622         If either are provided then an alias is also required.
5623
5624    Returns:
5625        Values: the Values expression object
5626    """
5627    if columns and not alias:
5628        raise ValueError("Alias is required when providing columns")
5629
5630    return Values(
5631        expressions=[convert(tup) for tup in values],
5632        alias=(
5633            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5634            if columns
5635            else (TableAlias(this=to_identifier(alias)) if alias else None)
5636        ),
5637    )

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:
5640def var(name: t.Optional[ExpOrStr]) -> Var:
5641    """Build a SQL variable.
5642
5643    Example:
5644        >>> repr(var('x'))
5645        '(VAR this: x)'
5646
5647        >>> repr(var(column('x', table='y')))
5648        '(VAR this: x)'
5649
5650    Args:
5651        name: The name of the var or an expression who's name will become the var.
5652
5653    Returns:
5654        The new variable node.
5655    """
5656    if not name:
5657        raise ValueError("Cannot convert empty name into var.")
5658
5659    if isinstance(name, Expression):
5660        name = name.name
5661    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:
5664def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5665    """Build ALTER TABLE... RENAME... expression
5666
5667    Args:
5668        old_name: The old name of the table
5669        new_name: The new name of the table
5670
5671    Returns:
5672        Alter table expression
5673    """
5674    old_table = to_table(old_name)
5675    new_table = to_table(new_name)
5676    return AlterTable(
5677        this=old_table,
5678        actions=[
5679            RenameTable(this=new_table),
5680        ],
5681    )

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:
5684def convert(value: t.Any, copy: bool = False) -> Expression:
5685    """Convert a python value into an expression object.
5686
5687    Raises an error if a conversion is not possible.
5688
5689    Args:
5690        value: A python object.
5691        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5692
5693    Returns:
5694        Expression: the equivalent expression object.
5695    """
5696    if isinstance(value, Expression):
5697        return _maybe_copy(value, copy)
5698    if isinstance(value, str):
5699        return Literal.string(value)
5700    if isinstance(value, bool):
5701        return Boolean(this=value)
5702    if value is None or (isinstance(value, float) and math.isnan(value)):
5703        return NULL
5704    if isinstance(value, numbers.Number):
5705        return Literal.number(value)
5706    if isinstance(value, datetime.datetime):
5707        datetime_literal = Literal.string(
5708            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5709        )
5710        return TimeStrToTime(this=datetime_literal)
5711    if isinstance(value, datetime.date):
5712        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5713        return DateStrToDate(this=date_literal)
5714    if isinstance(value, tuple):
5715        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5716    if isinstance(value, list):
5717        return Array(expressions=[convert(v, copy=copy) for v in value])
5718    if isinstance(value, dict):
5719        return Map(
5720            keys=[convert(k, copy=copy) for k in value],
5721            values=[convert(v, copy=copy) for v in value.values()],
5722        )
5723    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:
5726def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5727    """
5728    Replace children of an expression with the result of a lambda fun(child) -> exp.
5729    """
5730    for k, v in expression.args.items():
5731        is_list_arg = type(v) is list
5732
5733        child_nodes = v if is_list_arg else [v]
5734        new_child_nodes = []
5735
5736        for cn in child_nodes:
5737            if isinstance(cn, Expression):
5738                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5739                    new_child_nodes.append(child_node)
5740                    child_node.parent = expression
5741                    child_node.arg_key = k
5742            else:
5743                new_child_nodes.append(cn)
5744
5745        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]:
5748def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5749    """
5750    Return all table names referenced through columns in an expression.
5751
5752    Example:
5753        >>> import sqlglot
5754        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5755        ['a', 'c']
5756
5757    Args:
5758        expression: expression to find table names.
5759        exclude: a table name to exclude
5760
5761    Returns:
5762        A list of unique names.
5763    """
5764    return {
5765        table
5766        for table in (column.table for column in expression.find_all(Column))
5767        if table and table != exclude
5768    }

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:
5771def table_name(table: Table | str, dialect: DialectType = None) -> str:
5772    """Get the full name of a table as a string.
5773
5774    Args:
5775        table: Table expression node or string.
5776        dialect: The dialect to generate the table name for.
5777
5778    Examples:
5779        >>> from sqlglot import exp, parse_one
5780        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5781        'a.b.c'
5782
5783    Returns:
5784        The table name.
5785    """
5786
5787    table = maybe_parse(table, into=Table)
5788
5789    if not table:
5790        raise ValueError(f"Cannot parse {table}")
5791
5792    return ".".join(
5793        part.sql(dialect=dialect, identify=True)
5794        if not SAFE_IDENTIFIER_RE.match(part.name)
5795        else part.name
5796        for part in table.parts
5797    )

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:
5800def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5801    """Replace all tables in expression according to the mapping.
5802
5803    Args:
5804        expression: expression node to be transformed and replaced.
5805        mapping: mapping of table names.
5806        copy: whether or not to copy the expression.
5807
5808    Examples:
5809        >>> from sqlglot import exp, parse_one
5810        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5811        'SELECT * FROM c'
5812
5813    Returns:
5814        The mapped expression.
5815    """
5816
5817    def _replace_tables(node: Expression) -> Expression:
5818        if isinstance(node, Table):
5819            new_name = mapping.get(table_name(node))
5820            if new_name:
5821                return to_table(
5822                    new_name,
5823                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5824                )
5825        return node
5826
5827    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:
5830def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5831    """Replace placeholders in an expression.
5832
5833    Args:
5834        expression: expression node to be transformed and replaced.
5835        args: positional names that will substitute unnamed placeholders in the given order.
5836        kwargs: keyword arguments that will substitute named placeholders.
5837
5838    Examples:
5839        >>> from sqlglot import exp, parse_one
5840        >>> replace_placeholders(
5841        ...     parse_one("select * from :tbl where ? = ?"),
5842        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5843        ... ).sql()
5844        "SELECT * FROM foo WHERE str_col = 'b'"
5845
5846    Returns:
5847        The mapped expression.
5848    """
5849
5850    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5851        if isinstance(node, Placeholder):
5852            if node.name:
5853                new_name = kwargs.get(node.name)
5854                if new_name:
5855                    return convert(new_name)
5856            else:
5857                try:
5858                    return convert(next(args))
5859                except StopIteration:
5860                    pass
5861        return node
5862
5863    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:
5866def expand(
5867    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5868) -> Expression:
5869    """Transforms an expression by expanding all referenced sources into subqueries.
5870
5871    Examples:
5872        >>> from sqlglot import parse_one
5873        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5874        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5875
5876        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5877        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5878
5879    Args:
5880        expression: The expression to expand.
5881        sources: A dictionary of name to Subqueryables.
5882        copy: Whether or not to copy the expression during transformation. Defaults to True.
5883
5884    Returns:
5885        The transformed expression.
5886    """
5887
5888    def _expand(node: Expression):
5889        if isinstance(node, Table):
5890            name = table_name(node)
5891            source = sources.get(name)
5892            if source:
5893                subquery = source.subquery(node.alias or name)
5894                subquery.comments = [f"source: {name}"]
5895                return subquery.transform(_expand, copy=False)
5896        return node
5897
5898    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:
5901def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5902    """
5903    Returns a Func expression.
5904
5905    Examples:
5906        >>> func("abs", 5).sql()
5907        'ABS(5)'
5908
5909        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5910        'CAST(5 AS DOUBLE)'
5911
5912    Args:
5913        name: the name of the function to build.
5914        args: the args used to instantiate the function of interest.
5915        dialect: the source dialect.
5916        kwargs: the kwargs used to instantiate the function of interest.
5917
5918    Note:
5919        The arguments `args` and `kwargs` are mutually exclusive.
5920
5921    Returns:
5922        An instance of the function of interest, or an anonymous function, if `name` doesn't
5923        correspond to an existing `sqlglot.expressions.Func` class.
5924    """
5925    if args and kwargs:
5926        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5927
5928    from sqlglot.dialects.dialect import Dialect
5929
5930    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5931    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5932
5933    parser = Dialect.get_or_raise(dialect)().parser()
5934    from_args_list = parser.FUNCTIONS.get(name.upper())
5935
5936    if from_args_list:
5937        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5938    else:
5939        kwargs = kwargs or {"expressions": converted}
5940        function = Anonymous(this=name, **kwargs)
5941
5942    for error_message in function.error_messages(converted):
5943        raise ValueError(error_message)
5944
5945    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:
5948def true() -> Boolean:
5949    """
5950    Returns a true Boolean expression.
5951    """
5952    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5955def false() -> Boolean:
5956    """
5957    Returns a false Boolean expression.
5958    """
5959    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5962def null() -> Null:
5963    """
5964    Returns a Null expression.
5965    """
5966    return Null()

Returns a Null expression.

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