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}
3482
3483
3484class Commit(Expression):
3485    arg_types = {"chain": False}
3486
3487
3488class Rollback(Expression):
3489    arg_types = {"savepoint": 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 LastDateOfMonth(Func):
4102    pass
4103
4104
4105class Extract(Func):
4106    arg_types = {"this": True, "expression": True}
4107
4108
4109class TimestampAdd(Func, TimeUnit):
4110    arg_types = {"this": True, "expression": True, "unit": False}
4111
4112
4113class TimestampSub(Func, TimeUnit):
4114    arg_types = {"this": True, "expression": True, "unit": False}
4115
4116
4117class TimestampDiff(Func, TimeUnit):
4118    arg_types = {"this": True, "expression": True, "unit": False}
4119
4120
4121class TimestampTrunc(Func, TimeUnit):
4122    arg_types = {"this": True, "unit": True, "zone": False}
4123
4124
4125class TimeAdd(Func, TimeUnit):
4126    arg_types = {"this": True, "expression": True, "unit": False}
4127
4128
4129class TimeSub(Func, TimeUnit):
4130    arg_types = {"this": True, "expression": True, "unit": False}
4131
4132
4133class TimeDiff(Func, TimeUnit):
4134    arg_types = {"this": True, "expression": True, "unit": False}
4135
4136
4137class TimeTrunc(Func, TimeUnit):
4138    arg_types = {"this": True, "unit": True, "zone": False}
4139
4140
4141class DateFromParts(Func):
4142    _sql_names = ["DATEFROMPARTS"]
4143    arg_types = {"year": True, "month": True, "day": True}
4144
4145
4146class DateStrToDate(Func):
4147    pass
4148
4149
4150class DateToDateStr(Func):
4151    pass
4152
4153
4154class DateToDi(Func):
4155    pass
4156
4157
4158# https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#date
4159class Date(Func):
4160    arg_types = {"this": True, "zone": False}
4161
4162
4163class Day(Func):
4164    pass
4165
4166
4167class Decode(Func):
4168    arg_types = {"this": True, "charset": True, "replace": False}
4169
4170
4171class DiToDate(Func):
4172    pass
4173
4174
4175class Encode(Func):
4176    arg_types = {"this": True, "charset": True}
4177
4178
4179class Exp(Func):
4180    pass
4181
4182
4183class Explode(Func):
4184    pass
4185
4186
4187class Floor(Func):
4188    arg_types = {"this": True, "decimals": False}
4189
4190
4191class FromBase64(Func):
4192    pass
4193
4194
4195class ToBase64(Func):
4196    pass
4197
4198
4199class Greatest(Func):
4200    arg_types = {"this": True, "expressions": False}
4201    is_var_len_args = True
4202
4203
4204class GroupConcat(Func):
4205    arg_types = {"this": True, "separator": False}
4206
4207
4208class Hex(Func):
4209    pass
4210
4211
4212class If(Func):
4213    arg_types = {"this": True, "true": True, "false": False}
4214
4215
4216class Initcap(Func):
4217    arg_types = {"this": True, "expression": False}
4218
4219
4220class JSONKeyValue(Expression):
4221    arg_types = {"this": True, "expression": True}
4222
4223
4224class JSONObject(Func):
4225    arg_types = {
4226        "expressions": False,
4227        "null_handling": False,
4228        "unique_keys": False,
4229        "return_type": False,
4230        "format_json": False,
4231        "encoding": False,
4232    }
4233
4234
4235class OpenJSONColumnDef(Expression):
4236    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
4237
4238
4239class OpenJSON(Func):
4240    arg_types = {"this": True, "path": False, "expressions": False}
4241
4242
4243class JSONBContains(Binary):
4244    _sql_names = ["JSONB_CONTAINS"]
4245
4246
4247class JSONExtract(Binary, Func):
4248    _sql_names = ["JSON_EXTRACT"]
4249
4250
4251class JSONExtractScalar(JSONExtract):
4252    _sql_names = ["JSON_EXTRACT_SCALAR"]
4253
4254
4255class JSONBExtract(JSONExtract):
4256    _sql_names = ["JSONB_EXTRACT"]
4257
4258
4259class JSONBExtractScalar(JSONExtract):
4260    _sql_names = ["JSONB_EXTRACT_SCALAR"]
4261
4262
4263class JSONFormat(Func):
4264    arg_types = {"this": False, "options": False}
4265    _sql_names = ["JSON_FORMAT"]
4266
4267
4268# https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#operator_member-of
4269class JSONArrayContains(Binary, Predicate, Func):
4270    _sql_names = ["JSON_ARRAY_CONTAINS"]
4271
4272
4273class Least(Func):
4274    arg_types = {"this": True, "expressions": False}
4275    is_var_len_args = True
4276
4277
4278class Left(Func):
4279    arg_types = {"this": True, "expression": True}
4280
4281
4282class Right(Func):
4283    arg_types = {"this": True, "expression": True}
4284
4285
4286class Length(Func):
4287    _sql_names = ["LENGTH", "LEN"]
4288
4289
4290class Levenshtein(Func):
4291    arg_types = {
4292        "this": True,
4293        "expression": False,
4294        "ins_cost": False,
4295        "del_cost": False,
4296        "sub_cost": False,
4297    }
4298
4299
4300class Ln(Func):
4301    pass
4302
4303
4304class Log(Func):
4305    arg_types = {"this": True, "expression": False}
4306
4307
4308class Log2(Func):
4309    pass
4310
4311
4312class Log10(Func):
4313    pass
4314
4315
4316class LogicalOr(AggFunc):
4317    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
4318
4319
4320class LogicalAnd(AggFunc):
4321    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
4322
4323
4324class Lower(Func):
4325    _sql_names = ["LOWER", "LCASE"]
4326
4327
4328class Map(Func):
4329    arg_types = {"keys": False, "values": False}
4330
4331
4332class MapFromEntries(Func):
4333    pass
4334
4335
4336class StarMap(Func):
4337    pass
4338
4339
4340class VarMap(Func):
4341    arg_types = {"keys": True, "values": True}
4342    is_var_len_args = True
4343
4344    @property
4345    def keys(self) -> t.List[Expression]:
4346        return self.args["keys"].expressions
4347
4348    @property
4349    def values(self) -> t.List[Expression]:
4350        return self.args["values"].expressions
4351
4352
4353# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
4354class MatchAgainst(Func):
4355    arg_types = {"this": True, "expressions": True, "modifier": False}
4356
4357
4358class Max(AggFunc):
4359    arg_types = {"this": True, "expressions": False}
4360    is_var_len_args = True
4361
4362
4363class MD5(Func):
4364    _sql_names = ["MD5"]
4365
4366
4367# Represents the variant of the MD5 function that returns a binary value
4368class MD5Digest(Func):
4369    _sql_names = ["MD5_DIGEST"]
4370
4371
4372class Min(AggFunc):
4373    arg_types = {"this": True, "expressions": False}
4374    is_var_len_args = True
4375
4376
4377class Month(Func):
4378    pass
4379
4380
4381class Nvl2(Func):
4382    arg_types = {"this": True, "true": True, "false": False}
4383
4384
4385class Posexplode(Func):
4386    pass
4387
4388
4389class Pow(Binary, Func):
4390    _sql_names = ["POWER", "POW"]
4391
4392
4393class PercentileCont(AggFunc):
4394    arg_types = {"this": True, "expression": False}
4395
4396
4397class PercentileDisc(AggFunc):
4398    arg_types = {"this": True, "expression": False}
4399
4400
4401class Quantile(AggFunc):
4402    arg_types = {"this": True, "quantile": True}
4403
4404
4405class ApproxQuantile(Quantile):
4406    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
4407
4408
4409class RangeN(Func):
4410    arg_types = {"this": True, "expressions": True, "each": False}
4411
4412
4413class ReadCSV(Func):
4414    _sql_names = ["READ_CSV"]
4415    is_var_len_args = True
4416    arg_types = {"this": True, "expressions": False}
4417
4418
4419class Reduce(Func):
4420    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
4421
4422
4423class RegexpExtract(Func):
4424    arg_types = {
4425        "this": True,
4426        "expression": True,
4427        "position": False,
4428        "occurrence": False,
4429        "parameters": False,
4430        "group": False,
4431    }
4432
4433
4434class RegexpLike(Func):
4435    arg_types = {"this": True, "expression": True, "flag": False}
4436
4437
4438class RegexpILike(Func):
4439    arg_types = {"this": True, "expression": True, "flag": False}
4440
4441
4442# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
4443# limit is the number of times a pattern is applied
4444class RegexpSplit(Func):
4445    arg_types = {"this": True, "expression": True, "limit": False}
4446
4447
4448class Repeat(Func):
4449    arg_types = {"this": True, "times": True}
4450
4451
4452class Round(Func):
4453    arg_types = {"this": True, "decimals": False}
4454
4455
4456class RowNumber(Func):
4457    arg_types: t.Dict[str, t.Any] = {}
4458
4459
4460class SafeDivide(Func):
4461    arg_types = {"this": True, "expression": True}
4462
4463
4464class SetAgg(AggFunc):
4465    pass
4466
4467
4468class SHA(Func):
4469    _sql_names = ["SHA", "SHA1"]
4470
4471
4472class SHA2(Func):
4473    _sql_names = ["SHA2"]
4474    arg_types = {"this": True, "length": False}
4475
4476
4477class SortArray(Func):
4478    arg_types = {"this": True, "asc": False}
4479
4480
4481class Split(Func):
4482    arg_types = {"this": True, "expression": True, "limit": False}
4483
4484
4485# Start may be omitted in the case of postgres
4486# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
4487class Substring(Func):
4488    arg_types = {"this": True, "start": False, "length": False}
4489
4490
4491class StandardHash(Func):
4492    arg_types = {"this": True, "expression": False}
4493
4494
4495class StrPosition(Func):
4496    arg_types = {
4497        "this": True,
4498        "substr": True,
4499        "position": False,
4500        "instance": False,
4501    }
4502
4503
4504class StrToDate(Func):
4505    arg_types = {"this": True, "format": True}
4506
4507
4508class StrToTime(Func):
4509    arg_types = {"this": True, "format": True, "zone": False}
4510
4511
4512# Spark allows unix_timestamp()
4513# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
4514class StrToUnix(Func):
4515    arg_types = {"this": False, "format": False}
4516
4517
4518class NumberToStr(Func):
4519    arg_types = {"this": True, "format": True}
4520
4521
4522class FromBase(Func):
4523    arg_types = {"this": True, "expression": True}
4524
4525
4526class Struct(Func):
4527    arg_types = {"expressions": True}
4528    is_var_len_args = True
4529
4530
4531class StructExtract(Func):
4532    arg_types = {"this": True, "expression": True}
4533
4534
4535class Sum(AggFunc):
4536    pass
4537
4538
4539class Sqrt(Func):
4540    pass
4541
4542
4543class Stddev(AggFunc):
4544    pass
4545
4546
4547class StddevPop(AggFunc):
4548    pass
4549
4550
4551class StddevSamp(AggFunc):
4552    pass
4553
4554
4555class TimeToStr(Func):
4556    arg_types = {"this": True, "format": True}
4557
4558
4559class TimeToTimeStr(Func):
4560    pass
4561
4562
4563class TimeToUnix(Func):
4564    pass
4565
4566
4567class TimeStrToDate(Func):
4568    pass
4569
4570
4571class TimeStrToTime(Func):
4572    pass
4573
4574
4575class TimeStrToUnix(Func):
4576    pass
4577
4578
4579class Trim(Func):
4580    arg_types = {
4581        "this": True,
4582        "expression": False,
4583        "position": False,
4584        "collation": False,
4585    }
4586
4587
4588class TsOrDsAdd(Func, TimeUnit):
4589    arg_types = {"this": True, "expression": True, "unit": False}
4590
4591
4592class TsOrDsToDateStr(Func):
4593    pass
4594
4595
4596class TsOrDsToDate(Func):
4597    arg_types = {"this": True, "format": False}
4598
4599
4600class TsOrDiToDi(Func):
4601    pass
4602
4603
4604class Unhex(Func):
4605    pass
4606
4607
4608class UnixToStr(Func):
4609    arg_types = {"this": True, "format": False}
4610
4611
4612# https://prestodb.io/docs/current/functions/datetime.html
4613# presto has weird zone/hours/minutes
4614class UnixToTime(Func):
4615    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4616
4617    SECONDS = Literal.string("seconds")
4618    MILLIS = Literal.string("millis")
4619    MICROS = Literal.string("micros")
4620
4621
4622class UnixToTimeStr(Func):
4623    pass
4624
4625
4626class Upper(Func):
4627    _sql_names = ["UPPER", "UCASE"]
4628
4629
4630class Variance(AggFunc):
4631    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
4632
4633
4634class VariancePop(AggFunc):
4635    _sql_names = ["VARIANCE_POP", "VAR_POP"]
4636
4637
4638class Week(Func):
4639    arg_types = {"this": True, "mode": False}
4640
4641
4642class XMLTable(Func):
4643    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4644
4645
4646class Year(Func):
4647    pass
4648
4649
4650class Use(Expression):
4651    arg_types = {"this": True, "kind": False}
4652
4653
4654class Merge(Expression):
4655    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4656
4657
4658class When(Func):
4659    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4660
4661
4662# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html
4663# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16
4664class NextValueFor(Func):
4665    arg_types = {"this": True, "order": False}
4666
4667
4668def _norm_arg(arg):
4669    return arg.lower() if type(arg) is str else arg
4670
4671
4672ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4673
4674
4675# Helpers
4676@t.overload
4677def maybe_parse(
4678    sql_or_expression: ExpOrStr,
4679    *,
4680    into: t.Type[E],
4681    dialect: DialectType = None,
4682    prefix: t.Optional[str] = None,
4683    copy: bool = False,
4684    **opts,
4685) -> E:
4686    ...
4687
4688
4689@t.overload
4690def maybe_parse(
4691    sql_or_expression: str | E,
4692    *,
4693    into: t.Optional[IntoType] = None,
4694    dialect: DialectType = None,
4695    prefix: t.Optional[str] = None,
4696    copy: bool = False,
4697    **opts,
4698) -> E:
4699    ...
4700
4701
4702def maybe_parse(
4703    sql_or_expression: ExpOrStr,
4704    *,
4705    into: t.Optional[IntoType] = None,
4706    dialect: DialectType = None,
4707    prefix: t.Optional[str] = None,
4708    copy: bool = False,
4709    **opts,
4710) -> Expression:
4711    """Gracefully handle a possible string or expression.
4712
4713    Example:
4714        >>> maybe_parse("1")
4715        (LITERAL this: 1, is_string: False)
4716        >>> maybe_parse(to_identifier("x"))
4717        (IDENTIFIER this: x, quoted: False)
4718
4719    Args:
4720        sql_or_expression: the SQL code string or an expression
4721        into: the SQLGlot Expression to parse into
4722        dialect: the dialect used to parse the input expressions (in the case that an
4723            input expression is a SQL string).
4724        prefix: a string to prefix the sql with before it gets parsed
4725            (automatically includes a space)
4726        copy: whether or not to copy the expression.
4727        **opts: other options to use to parse the input expressions (again, in the case
4728            that an input expression is a SQL string).
4729
4730    Returns:
4731        Expression: the parsed or given expression.
4732    """
4733    if isinstance(sql_or_expression, Expression):
4734        if copy:
4735            return sql_or_expression.copy()
4736        return sql_or_expression
4737
4738    if sql_or_expression is None:
4739        raise ParseError(f"SQL cannot be None")
4740
4741    import sqlglot
4742
4743    sql = str(sql_or_expression)
4744    if prefix:
4745        sql = f"{prefix} {sql}"
4746
4747    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4748
4749
4750def _maybe_copy(instance: E, copy: bool = True) -> E:
4751    return instance.copy() if copy else instance
4752
4753
4754def _is_wrong_expression(expression, into):
4755    return isinstance(expression, Expression) and not isinstance(expression, into)
4756
4757
4758def _apply_builder(
4759    expression,
4760    instance,
4761    arg,
4762    copy=True,
4763    prefix=None,
4764    into=None,
4765    dialect=None,
4766    **opts,
4767):
4768    if _is_wrong_expression(expression, into):
4769        expression = into(this=expression)
4770    instance = _maybe_copy(instance, copy)
4771    expression = maybe_parse(
4772        sql_or_expression=expression,
4773        prefix=prefix,
4774        into=into,
4775        dialect=dialect,
4776        **opts,
4777    )
4778    instance.set(arg, expression)
4779    return instance
4780
4781
4782def _apply_child_list_builder(
4783    *expressions,
4784    instance,
4785    arg,
4786    append=True,
4787    copy=True,
4788    prefix=None,
4789    into=None,
4790    dialect=None,
4791    properties=None,
4792    **opts,
4793):
4794    instance = _maybe_copy(instance, copy)
4795    parsed = []
4796    for expression in expressions:
4797        if expression is not None:
4798            if _is_wrong_expression(expression, into):
4799                expression = into(expressions=[expression])
4800
4801            expression = maybe_parse(
4802                expression,
4803                into=into,
4804                dialect=dialect,
4805                prefix=prefix,
4806                **opts,
4807            )
4808            parsed.extend(expression.expressions)
4809
4810    existing = instance.args.get(arg)
4811    if append and existing:
4812        parsed = existing.expressions + parsed
4813
4814    child = into(expressions=parsed)
4815    for k, v in (properties or {}).items():
4816        child.set(k, v)
4817    instance.set(arg, child)
4818
4819    return instance
4820
4821
4822def _apply_list_builder(
4823    *expressions,
4824    instance,
4825    arg,
4826    append=True,
4827    copy=True,
4828    prefix=None,
4829    into=None,
4830    dialect=None,
4831    **opts,
4832):
4833    inst = _maybe_copy(instance, copy)
4834
4835    expressions = [
4836        maybe_parse(
4837            sql_or_expression=expression,
4838            into=into,
4839            prefix=prefix,
4840            dialect=dialect,
4841            **opts,
4842        )
4843        for expression in expressions
4844        if expression is not None
4845    ]
4846
4847    existing_expressions = inst.args.get(arg)
4848    if append and existing_expressions:
4849        expressions = existing_expressions + expressions
4850
4851    inst.set(arg, expressions)
4852    return inst
4853
4854
4855def _apply_conjunction_builder(
4856    *expressions,
4857    instance,
4858    arg,
4859    into=None,
4860    append=True,
4861    copy=True,
4862    dialect=None,
4863    **opts,
4864):
4865    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4866    if not expressions:
4867        return instance
4868
4869    inst = _maybe_copy(instance, copy)
4870
4871    existing = inst.args.get(arg)
4872    if append and existing is not None:
4873        expressions = [existing.this if into else existing] + list(expressions)
4874
4875    node = and_(*expressions, dialect=dialect, copy=copy, **opts)
4876
4877    inst.set(arg, into(this=node) if into else node)
4878    return inst
4879
4880
4881def _apply_cte_builder(
4882    instance: E,
4883    alias: ExpOrStr,
4884    as_: ExpOrStr,
4885    recursive: t.Optional[bool] = None,
4886    append: bool = True,
4887    dialect: DialectType = None,
4888    copy: bool = True,
4889    **opts,
4890) -> E:
4891    alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts)
4892    as_expression = maybe_parse(as_, dialect=dialect, **opts)
4893    cte = CTE(this=as_expression, alias=alias_expression)
4894    return _apply_child_list_builder(
4895        cte,
4896        instance=instance,
4897        arg="with",
4898        append=append,
4899        copy=copy,
4900        into=With,
4901        properties={"recursive": recursive or False},
4902    )
4903
4904
4905def _combine(
4906    expressions: t.Sequence[t.Optional[ExpOrStr]],
4907    operator: t.Type[Connector],
4908    dialect: DialectType = None,
4909    copy: bool = True,
4910    **opts,
4911) -> Expression:
4912    conditions = [
4913        condition(expression, dialect=dialect, copy=copy, **opts)
4914        for expression in expressions
4915        if expression is not None
4916    ]
4917
4918    this, *rest = conditions
4919    if rest:
4920        this = _wrap(this, Connector)
4921    for expression in rest:
4922        this = operator(this=this, expression=_wrap(expression, Connector))
4923
4924    return this
4925
4926
4927def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:
4928    return Paren(this=expression) if isinstance(expression, kind) else expression
4929
4930
4931def union(
4932    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4933) -> Union:
4934    """
4935    Initializes a syntax tree from one UNION expression.
4936
4937    Example:
4938        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4939        'SELECT * FROM foo UNION SELECT * FROM bla'
4940
4941    Args:
4942        left: the SQL code string corresponding to the left-hand side.
4943            If an `Expression` instance is passed, it will be used as-is.
4944        right: the SQL code string corresponding to the right-hand side.
4945            If an `Expression` instance is passed, it will be used as-is.
4946        distinct: set the DISTINCT flag if and only if this is true.
4947        dialect: the dialect used to parse the input expression.
4948        opts: other options to use to parse the input expressions.
4949
4950    Returns:
4951        The new Union instance.
4952    """
4953    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4954    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4955
4956    return Union(this=left, expression=right, distinct=distinct)
4957
4958
4959def intersect(
4960    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4961) -> Intersect:
4962    """
4963    Initializes a syntax tree from one INTERSECT expression.
4964
4965    Example:
4966        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4967        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4968
4969    Args:
4970        left: the SQL code string corresponding to the left-hand side.
4971            If an `Expression` instance is passed, it will be used as-is.
4972        right: the SQL code string corresponding to the right-hand side.
4973            If an `Expression` instance is passed, it will be used as-is.
4974        distinct: set the DISTINCT flag if and only if this is true.
4975        dialect: the dialect used to parse the input expression.
4976        opts: other options to use to parse the input expressions.
4977
4978    Returns:
4979        The new Intersect instance.
4980    """
4981    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4982    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4983
4984    return Intersect(this=left, expression=right, distinct=distinct)
4985
4986
4987def except_(
4988    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4989) -> Except:
4990    """
4991    Initializes a syntax tree from one EXCEPT expression.
4992
4993    Example:
4994        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4995        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4996
4997    Args:
4998        left: the SQL code string corresponding to the left-hand side.
4999            If an `Expression` instance is passed, it will be used as-is.
5000        right: the SQL code string corresponding to the right-hand side.
5001            If an `Expression` instance is passed, it will be used as-is.
5002        distinct: set the DISTINCT flag if and only if this is true.
5003        dialect: the dialect used to parse the input expression.
5004        opts: other options to use to parse the input expressions.
5005
5006    Returns:
5007        The new Except instance.
5008    """
5009    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5010    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5011
5012    return Except(this=left, expression=right, distinct=distinct)
5013
5014
5015def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5016    """
5017    Initializes a syntax tree from one or multiple SELECT expressions.
5018
5019    Example:
5020        >>> select("col1", "col2").from_("tbl").sql()
5021        'SELECT col1, col2 FROM tbl'
5022
5023    Args:
5024        *expressions: the SQL code string to parse as the expressions of a
5025            SELECT statement. If an Expression instance is passed, this is used as-is.
5026        dialect: the dialect used to parse the input expressions (in the case that an
5027            input expression is a SQL string).
5028        **opts: other options to use to parse the input expressions (again, in the case
5029            that an input expression is a SQL string).
5030
5031    Returns:
5032        Select: the syntax tree for the SELECT statement.
5033    """
5034    return Select().select(*expressions, dialect=dialect, **opts)
5035
5036
5037def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5038    """
5039    Initializes a syntax tree from a FROM expression.
5040
5041    Example:
5042        >>> from_("tbl").select("col1", "col2").sql()
5043        'SELECT col1, col2 FROM tbl'
5044
5045    Args:
5046        *expression: the SQL code string to parse as the FROM expressions of a
5047            SELECT statement. If an Expression instance is passed, this is used as-is.
5048        dialect: the dialect used to parse the input expression (in the case that the
5049            input expression is a SQL string).
5050        **opts: other options to use to parse the input expressions (again, in the case
5051            that the input expression is a SQL string).
5052
5053    Returns:
5054        Select: the syntax tree for the SELECT statement.
5055    """
5056    return Select().from_(expression, dialect=dialect, **opts)
5057
5058
5059def update(
5060    table: str | Table,
5061    properties: dict,
5062    where: t.Optional[ExpOrStr] = None,
5063    from_: t.Optional[ExpOrStr] = None,
5064    dialect: DialectType = None,
5065    **opts,
5066) -> Update:
5067    """
5068    Creates an update statement.
5069
5070    Example:
5071        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5072        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5073
5074    Args:
5075        *properties: dictionary of properties to set which are
5076            auto converted to sql objects eg None -> NULL
5077        where: sql conditional parsed into a WHERE statement
5078        from_: sql statement parsed into a FROM statement
5079        dialect: the dialect used to parse the input expressions.
5080        **opts: other options to use to parse the input expressions.
5081
5082    Returns:
5083        Update: the syntax tree for the UPDATE statement.
5084    """
5085    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5086    update_expr.set(
5087        "expressions",
5088        [
5089            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5090            for k, v in properties.items()
5091        ],
5092    )
5093    if from_:
5094        update_expr.set(
5095            "from",
5096            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5097        )
5098    if isinstance(where, Condition):
5099        where = Where(this=where)
5100    if where:
5101        update_expr.set(
5102            "where",
5103            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5104        )
5105    return update_expr
5106
5107
5108def delete(
5109    table: ExpOrStr,
5110    where: t.Optional[ExpOrStr] = None,
5111    returning: t.Optional[ExpOrStr] = None,
5112    dialect: DialectType = None,
5113    **opts,
5114) -> Delete:
5115    """
5116    Builds a delete statement.
5117
5118    Example:
5119        >>> delete("my_table", where="id > 1").sql()
5120        'DELETE FROM my_table WHERE id > 1'
5121
5122    Args:
5123        where: sql conditional parsed into a WHERE statement
5124        returning: sql conditional parsed into a RETURNING statement
5125        dialect: the dialect used to parse the input expressions.
5126        **opts: other options to use to parse the input expressions.
5127
5128    Returns:
5129        Delete: the syntax tree for the DELETE statement.
5130    """
5131    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5132    if where:
5133        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5134    if returning:
5135        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5136    return delete_expr
5137
5138
5139def insert(
5140    expression: ExpOrStr,
5141    into: ExpOrStr,
5142    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5143    overwrite: t.Optional[bool] = None,
5144    dialect: DialectType = None,
5145    copy: bool = True,
5146    **opts,
5147) -> Insert:
5148    """
5149    Builds an INSERT statement.
5150
5151    Example:
5152        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5153        'INSERT INTO tbl VALUES (1, 2, 3)'
5154
5155    Args:
5156        expression: the sql string or expression of the INSERT statement
5157        into: the tbl to insert data to.
5158        columns: optionally the table's column names.
5159        overwrite: whether to INSERT OVERWRITE or not.
5160        dialect: the dialect used to parse the input expressions.
5161        copy: whether or not to copy the expression.
5162        **opts: other options to use to parse the input expressions.
5163
5164    Returns:
5165        Insert: the syntax tree for the INSERT statement.
5166    """
5167    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5168    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5169
5170    if columns:
5171        this = _apply_list_builder(
5172            *columns,
5173            instance=Schema(this=this),
5174            arg="expressions",
5175            into=Identifier,
5176            copy=False,
5177            dialect=dialect,
5178            **opts,
5179        )
5180
5181    return Insert(this=this, expression=expr, overwrite=overwrite)
5182
5183
5184def condition(
5185    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5186) -> Condition:
5187    """
5188    Initialize a logical condition expression.
5189
5190    Example:
5191        >>> condition("x=1").sql()
5192        'x = 1'
5193
5194        This is helpful for composing larger logical syntax trees:
5195        >>> where = condition("x=1")
5196        >>> where = where.and_("y=1")
5197        >>> Select().from_("tbl").select("*").where(where).sql()
5198        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5199
5200    Args:
5201        *expression: the SQL code string to parse.
5202            If an Expression instance is passed, this is used as-is.
5203        dialect: the dialect used to parse the input expression (in the case that the
5204            input expression is a SQL string).
5205        copy: Whether or not to copy `expression` (only applies to expressions).
5206        **opts: other options to use to parse the input expressions (again, in the case
5207            that the input expression is a SQL string).
5208
5209    Returns:
5210        The new Condition instance
5211    """
5212    return maybe_parse(
5213        expression,
5214        into=Condition,
5215        dialect=dialect,
5216        copy=copy,
5217        **opts,
5218    )
5219
5220
5221def and_(
5222    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5223) -> Condition:
5224    """
5225    Combine multiple conditions with an AND logical operator.
5226
5227    Example:
5228        >>> and_("x=1", and_("y=1", "z=1")).sql()
5229        'x = 1 AND (y = 1 AND z = 1)'
5230
5231    Args:
5232        *expressions: the SQL code strings to parse.
5233            If an Expression instance is passed, this is used as-is.
5234        dialect: the dialect used to parse the input expression.
5235        copy: whether or not to copy `expressions` (only applies to Expressions).
5236        **opts: other options to use to parse the input expressions.
5237
5238    Returns:
5239        And: the new condition
5240    """
5241    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))
5242
5243
5244def or_(
5245    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5246) -> Condition:
5247    """
5248    Combine multiple conditions with an OR logical operator.
5249
5250    Example:
5251        >>> or_("x=1", or_("y=1", "z=1")).sql()
5252        'x = 1 OR (y = 1 OR z = 1)'
5253
5254    Args:
5255        *expressions: the SQL code strings to parse.
5256            If an Expression instance is passed, this is used as-is.
5257        dialect: the dialect used to parse the input expression.
5258        copy: whether or not to copy `expressions` (only applies to Expressions).
5259        **opts: other options to use to parse the input expressions.
5260
5261    Returns:
5262        Or: the new condition
5263    """
5264    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))
5265
5266
5267def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5268    """
5269    Wrap a condition with a NOT operator.
5270
5271    Example:
5272        >>> not_("this_suit='black'").sql()
5273        "NOT this_suit = 'black'"
5274
5275    Args:
5276        expression: the SQL code string to parse.
5277            If an Expression instance is passed, this is used as-is.
5278        dialect: the dialect used to parse the input expression.
5279        copy: whether to copy the expression or not.
5280        **opts: other options to use to parse the input expressions.
5281
5282    Returns:
5283        The new condition.
5284    """
5285    this = condition(
5286        expression,
5287        dialect=dialect,
5288        copy=copy,
5289        **opts,
5290    )
5291    return Not(this=_wrap(this, Connector))
5292
5293
5294def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5295    """
5296    Wrap an expression in parentheses.
5297
5298    Example:
5299        >>> paren("5 + 3").sql()
5300        '(5 + 3)'
5301
5302    Args:
5303        expression: the SQL code string to parse.
5304            If an Expression instance is passed, this is used as-is.
5305        copy: whether to copy the expression or not.
5306
5307    Returns:
5308        The wrapped expression.
5309    """
5310    return Paren(this=maybe_parse(expression, copy=copy))
5311
5312
5313SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
5314
5315
5316@t.overload
5317def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None:
5318    ...
5319
5320
5321@t.overload
5322def to_identifier(
5323    name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True
5324) -> Identifier:
5325    ...
5326
5327
5328def to_identifier(name, quoted=None, copy=True):
5329    """Builds an identifier.
5330
5331    Args:
5332        name: The name to turn into an identifier.
5333        quoted: Whether or not force quote the identifier.
5334        copy: Whether or not to copy a passed in Identefier node.
5335
5336    Returns:
5337        The identifier ast node.
5338    """
5339
5340    if name is None:
5341        return None
5342
5343    if isinstance(name, Identifier):
5344        identifier = _maybe_copy(name, copy)
5345    elif isinstance(name, str):
5346        identifier = Identifier(
5347            this=name,
5348            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5349        )
5350    else:
5351        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5352    return identifier
5353
5354
5355INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
5356
5357
5358def to_interval(interval: str | Literal) -> Interval:
5359    """Builds an interval expression from a string like '1 day' or '5 months'."""
5360    if isinstance(interval, Literal):
5361        if not interval.is_string:
5362            raise ValueError("Invalid interval string.")
5363
5364        interval = interval.this
5365
5366    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5367
5368    if not interval_parts:
5369        raise ValueError("Invalid interval string.")
5370
5371    return Interval(
5372        this=Literal.string(interval_parts.group(1)),
5373        unit=Var(this=interval_parts.group(2)),
5374    )
5375
5376
5377@t.overload
5378def to_table(sql_path: str | Table, **kwargs) -> Table:
5379    ...
5380
5381
5382@t.overload
5383def to_table(sql_path: None, **kwargs) -> None:
5384    ...
5385
5386
5387def to_table(
5388    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5389) -> t.Optional[Table]:
5390    """
5391    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5392    If a table is passed in then that table is returned.
5393
5394    Args:
5395        sql_path: a `[catalog].[schema].[table]` string.
5396        dialect: the source dialect according to which the table name will be parsed.
5397        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5398
5399    Returns:
5400        A table expression.
5401    """
5402    if sql_path is None or isinstance(sql_path, Table):
5403        return sql_path
5404    if not isinstance(sql_path, str):
5405        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5406
5407    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5408    if table:
5409        for k, v in kwargs.items():
5410            table.set(k, v)
5411
5412    return table
5413
5414
5415def to_column(sql_path: str | Column, **kwargs) -> Column:
5416    """
5417    Create a column from a `[table].[column]` sql path. Schema is optional.
5418
5419    If a column is passed in then that column is returned.
5420
5421    Args:
5422        sql_path: `[table].[column]` string
5423    Returns:
5424        Table: A column expression
5425    """
5426    if sql_path is None or isinstance(sql_path, Column):
5427        return sql_path
5428    if not isinstance(sql_path, str):
5429        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5430    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
5431
5432
5433def alias_(
5434    expression: ExpOrStr,
5435    alias: str | Identifier,
5436    table: bool | t.Sequence[str | Identifier] = False,
5437    quoted: t.Optional[bool] = None,
5438    dialect: DialectType = None,
5439    copy: bool = True,
5440    **opts,
5441):
5442    """Create an Alias expression.
5443
5444    Example:
5445        >>> alias_('foo', 'bar').sql()
5446        'foo AS bar'
5447
5448        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5449        '(SELECT 1, 2) AS bar(a, b)'
5450
5451    Args:
5452        expression: the SQL code strings to parse.
5453            If an Expression instance is passed, this is used as-is.
5454        alias: the alias name to use. If the name has
5455            special characters it is quoted.
5456        table: Whether or not to create a table alias, can also be a list of columns.
5457        quoted: whether or not to quote the alias
5458        dialect: the dialect used to parse the input expression.
5459        copy: Whether or not to copy the expression.
5460        **opts: other options to use to parse the input expressions.
5461
5462    Returns:
5463        Alias: the aliased expression
5464    """
5465    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5466    alias = to_identifier(alias, quoted=quoted)
5467
5468    if table:
5469        table_alias = TableAlias(this=alias)
5470        exp.set("alias", table_alias)
5471
5472        if not isinstance(table, bool):
5473            for column in table:
5474                table_alias.append("columns", to_identifier(column, quoted=quoted))
5475
5476        return exp
5477
5478    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5479    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5480    # for the complete Window expression.
5481    #
5482    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5483
5484    if "alias" in exp.arg_types and not isinstance(exp, Window):
5485        exp.set("alias", alias)
5486        return exp
5487    return Alias(this=exp, alias=alias)
5488
5489
5490def subquery(
5491    expression: ExpOrStr,
5492    alias: t.Optional[Identifier | str] = None,
5493    dialect: DialectType = None,
5494    **opts,
5495) -> Select:
5496    """
5497    Build a subquery expression.
5498
5499    Example:
5500        >>> subquery('select x from tbl', 'bar').select('x').sql()
5501        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5502
5503    Args:
5504        expression: the SQL code strings to parse.
5505            If an Expression instance is passed, this is used as-is.
5506        alias: the alias name to use.
5507        dialect: the dialect used to parse the input expression.
5508        **opts: other options to use to parse the input expressions.
5509
5510    Returns:
5511        A new Select instance with the subquery expression included.
5512    """
5513
5514    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5515    return Select().from_(expression, dialect=dialect, **opts)
5516
5517
5518def column(
5519    col: str | Identifier,
5520    table: t.Optional[str | Identifier] = None,
5521    db: t.Optional[str | Identifier] = None,
5522    catalog: t.Optional[str | Identifier] = None,
5523    quoted: t.Optional[bool] = None,
5524) -> Column:
5525    """
5526    Build a Column.
5527
5528    Args:
5529        col: Column name.
5530        table: Table name.
5531        db: Database name.
5532        catalog: Catalog name.
5533        quoted: Whether to force quotes on the column's identifiers.
5534
5535    Returns:
5536        The new Column instance.
5537    """
5538    return Column(
5539        this=to_identifier(col, quoted=quoted),
5540        table=to_identifier(table, quoted=quoted),
5541        db=to_identifier(db, quoted=quoted),
5542        catalog=to_identifier(catalog, quoted=quoted),
5543    )
5544
5545
5546def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5547    """Cast an expression to a data type.
5548
5549    Example:
5550        >>> cast('x + 1', 'int').sql()
5551        'CAST(x + 1 AS INT)'
5552
5553    Args:
5554        expression: The expression to cast.
5555        to: The datatype to cast to.
5556
5557    Returns:
5558        The new Cast instance.
5559    """
5560    expression = maybe_parse(expression, **opts)
5561    return Cast(this=expression, to=DataType.build(to, **opts))
5562
5563
5564def table_(
5565    table: Identifier | str,
5566    db: t.Optional[Identifier | str] = None,
5567    catalog: t.Optional[Identifier | str] = None,
5568    quoted: t.Optional[bool] = None,
5569    alias: t.Optional[Identifier | str] = None,
5570) -> Table:
5571    """Build a Table.
5572
5573    Args:
5574        table: Table name.
5575        db: Database name.
5576        catalog: Catalog name.
5577        quote: Whether to force quotes on the table's identifiers.
5578        alias: Table's alias.
5579
5580    Returns:
5581        The new Table instance.
5582    """
5583    return Table(
5584        this=to_identifier(table, quoted=quoted),
5585        db=to_identifier(db, quoted=quoted),
5586        catalog=to_identifier(catalog, quoted=quoted),
5587        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5588    )
5589
5590
5591def values(
5592    values: t.Iterable[t.Tuple[t.Any, ...]],
5593    alias: t.Optional[str] = None,
5594    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5595) -> Values:
5596    """Build VALUES statement.
5597
5598    Example:
5599        >>> values([(1, '2')]).sql()
5600        "VALUES (1, '2')"
5601
5602    Args:
5603        values: values statements that will be converted to SQL
5604        alias: optional alias
5605        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5606         If either are provided then an alias is also required.
5607
5608    Returns:
5609        Values: the Values expression object
5610    """
5611    if columns and not alias:
5612        raise ValueError("Alias is required when providing columns")
5613
5614    return Values(
5615        expressions=[convert(tup) for tup in values],
5616        alias=(
5617            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5618            if columns
5619            else (TableAlias(this=to_identifier(alias)) if alias else None)
5620        ),
5621    )
5622
5623
5624def var(name: t.Optional[ExpOrStr]) -> Var:
5625    """Build a SQL variable.
5626
5627    Example:
5628        >>> repr(var('x'))
5629        '(VAR this: x)'
5630
5631        >>> repr(var(column('x', table='y')))
5632        '(VAR this: x)'
5633
5634    Args:
5635        name: The name of the var or an expression who's name will become the var.
5636
5637    Returns:
5638        The new variable node.
5639    """
5640    if not name:
5641        raise ValueError("Cannot convert empty name into var.")
5642
5643    if isinstance(name, Expression):
5644        name = name.name
5645    return Var(this=name)
5646
5647
5648def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5649    """Build ALTER TABLE... RENAME... expression
5650
5651    Args:
5652        old_name: The old name of the table
5653        new_name: The new name of the table
5654
5655    Returns:
5656        Alter table expression
5657    """
5658    old_table = to_table(old_name)
5659    new_table = to_table(new_name)
5660    return AlterTable(
5661        this=old_table,
5662        actions=[
5663            RenameTable(this=new_table),
5664        ],
5665    )
5666
5667
5668def convert(value: t.Any, copy: bool = False) -> Expression:
5669    """Convert a python value into an expression object.
5670
5671    Raises an error if a conversion is not possible.
5672
5673    Args:
5674        value: A python object.
5675        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5676
5677    Returns:
5678        Expression: the equivalent expression object.
5679    """
5680    if isinstance(value, Expression):
5681        return _maybe_copy(value, copy)
5682    if isinstance(value, str):
5683        return Literal.string(value)
5684    if isinstance(value, bool):
5685        return Boolean(this=value)
5686    if value is None or (isinstance(value, float) and math.isnan(value)):
5687        return NULL
5688    if isinstance(value, numbers.Number):
5689        return Literal.number(value)
5690    if isinstance(value, datetime.datetime):
5691        datetime_literal = Literal.string(
5692            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5693        )
5694        return TimeStrToTime(this=datetime_literal)
5695    if isinstance(value, datetime.date):
5696        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5697        return DateStrToDate(this=date_literal)
5698    if isinstance(value, tuple):
5699        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5700    if isinstance(value, list):
5701        return Array(expressions=[convert(v, copy=copy) for v in value])
5702    if isinstance(value, dict):
5703        return Map(
5704            keys=[convert(k, copy=copy) for k in value],
5705            values=[convert(v, copy=copy) for v in value.values()],
5706        )
5707    raise ValueError(f"Cannot convert {value}")
5708
5709
5710def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5711    """
5712    Replace children of an expression with the result of a lambda fun(child) -> exp.
5713    """
5714    for k, v in expression.args.items():
5715        is_list_arg = type(v) is list
5716
5717        child_nodes = v if is_list_arg else [v]
5718        new_child_nodes = []
5719
5720        for cn in child_nodes:
5721            if isinstance(cn, Expression):
5722                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5723                    new_child_nodes.append(child_node)
5724                    child_node.parent = expression
5725                    child_node.arg_key = k
5726            else:
5727                new_child_nodes.append(cn)
5728
5729        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
5730
5731
5732def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5733    """
5734    Return all table names referenced through columns in an expression.
5735
5736    Example:
5737        >>> import sqlglot
5738        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5739        ['a', 'c']
5740
5741    Args:
5742        expression: expression to find table names.
5743        exclude: a table name to exclude
5744
5745    Returns:
5746        A list of unique names.
5747    """
5748    return {
5749        table
5750        for table in (column.table for column in expression.find_all(Column))
5751        if table and table != exclude
5752    }
5753
5754
5755def table_name(table: Table | str, dialect: DialectType = None) -> str:
5756    """Get the full name of a table as a string.
5757
5758    Args:
5759        table: Table expression node or string.
5760        dialect: The dialect to generate the table name for.
5761
5762    Examples:
5763        >>> from sqlglot import exp, parse_one
5764        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5765        'a.b.c'
5766
5767    Returns:
5768        The table name.
5769    """
5770
5771    table = maybe_parse(table, into=Table)
5772
5773    if not table:
5774        raise ValueError(f"Cannot parse {table}")
5775
5776    return ".".join(
5777        part.sql(dialect=dialect, identify=True)
5778        if not SAFE_IDENTIFIER_RE.match(part.name)
5779        else part.name
5780        for part in table.parts
5781    )
5782
5783
5784def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5785    """Replace all tables in expression according to the mapping.
5786
5787    Args:
5788        expression: expression node to be transformed and replaced.
5789        mapping: mapping of table names.
5790        copy: whether or not to copy the expression.
5791
5792    Examples:
5793        >>> from sqlglot import exp, parse_one
5794        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5795        'SELECT * FROM c'
5796
5797    Returns:
5798        The mapped expression.
5799    """
5800
5801    def _replace_tables(node: Expression) -> Expression:
5802        if isinstance(node, Table):
5803            new_name = mapping.get(table_name(node))
5804            if new_name:
5805                return to_table(
5806                    new_name,
5807                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5808                )
5809        return node
5810
5811    return expression.transform(_replace_tables, copy=copy)
5812
5813
5814def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5815    """Replace placeholders in an expression.
5816
5817    Args:
5818        expression: expression node to be transformed and replaced.
5819        args: positional names that will substitute unnamed placeholders in the given order.
5820        kwargs: keyword arguments that will substitute named placeholders.
5821
5822    Examples:
5823        >>> from sqlglot import exp, parse_one
5824        >>> replace_placeholders(
5825        ...     parse_one("select * from :tbl where ? = ?"),
5826        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5827        ... ).sql()
5828        "SELECT * FROM foo WHERE str_col = 'b'"
5829
5830    Returns:
5831        The mapped expression.
5832    """
5833
5834    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5835        if isinstance(node, Placeholder):
5836            if node.name:
5837                new_name = kwargs.get(node.name)
5838                if new_name:
5839                    return convert(new_name)
5840            else:
5841                try:
5842                    return convert(next(args))
5843                except StopIteration:
5844                    pass
5845        return node
5846
5847    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5848
5849
5850def expand(
5851    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5852) -> Expression:
5853    """Transforms an expression by expanding all referenced sources into subqueries.
5854
5855    Examples:
5856        >>> from sqlglot import parse_one
5857        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5858        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5859
5860        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5861        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5862
5863    Args:
5864        expression: The expression to expand.
5865        sources: A dictionary of name to Subqueryables.
5866        copy: Whether or not to copy the expression during transformation. Defaults to True.
5867
5868    Returns:
5869        The transformed expression.
5870    """
5871
5872    def _expand(node: Expression):
5873        if isinstance(node, Table):
5874            name = table_name(node)
5875            source = sources.get(name)
5876            if source:
5877                subquery = source.subquery(node.alias or name)
5878                subquery.comments = [f"source: {name}"]
5879                return subquery.transform(_expand, copy=False)
5880        return node
5881
5882    return expression.transform(_expand, copy=copy)
5883
5884
5885def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5886    """
5887    Returns a Func expression.
5888
5889    Examples:
5890        >>> func("abs", 5).sql()
5891        'ABS(5)'
5892
5893        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5894        'CAST(5 AS DOUBLE)'
5895
5896    Args:
5897        name: the name of the function to build.
5898        args: the args used to instantiate the function of interest.
5899        dialect: the source dialect.
5900        kwargs: the kwargs used to instantiate the function of interest.
5901
5902    Note:
5903        The arguments `args` and `kwargs` are mutually exclusive.
5904
5905    Returns:
5906        An instance of the function of interest, or an anonymous function, if `name` doesn't
5907        correspond to an existing `sqlglot.expressions.Func` class.
5908    """
5909    if args and kwargs:
5910        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5911
5912    from sqlglot.dialects.dialect import Dialect
5913
5914    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5915    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5916
5917    parser = Dialect.get_or_raise(dialect)().parser()
5918    from_args_list = parser.FUNCTIONS.get(name.upper())
5919
5920    if from_args_list:
5921        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5922    else:
5923        kwargs = kwargs or {"expressions": converted}
5924        function = Anonymous(this=name, **kwargs)
5925
5926    for error_message in function.error_messages(converted):
5927        raise ValueError(error_message)
5928
5929    return function
5930
5931
5932def true() -> Boolean:
5933    """
5934    Returns a true Boolean expression.
5935    """
5936    return Boolean(this=True)
5937
5938
5939def false() -> Boolean:
5940    """
5941    Returns a false Boolean expression.
5942    """
5943    return Boolean(this=False)
5944
5945
5946def null() -> Null:
5947    """
5948    Returns a Null expression.
5949    """
5950    return Null()
5951
5952
5953# TODO: deprecate this
5954TRUE = Boolean(this=True)
5955FALSE = Boolean(this=False)
5956NULL = 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.TEXT: 'TEXT'>, <Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>}
INTEGER_TYPES = {<Type.INT256: 'INT256'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.BIGINT: 'BIGINT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.INT128: 'INT128'>, <Type.INT256: 'INT256'>, <Type.DOUBLE: 'DOUBLE'>, <Type.BIGINT: 'BIGINT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.FLOAT: 'FLOAT'>}
TEMPORAL_TYPES = {<Type.TIME: 'TIME'>, <Type.DATE: 'DATE'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATETIME: 'DATETIME'>, <Type.DATETIME64: 'DATETIME64'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>}
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}
arg_types = {'this': False, 'modes': False}
key = 'transaction'
class Commit(Expression):
3485class Commit(Expression):
3486    arg_types = {"chain": False}
arg_types = {'chain': False}
key = 'commit'
class Rollback(Expression):
3489class Rollback(Expression):
3490    arg_types = {"savepoint": False}
arg_types = {'savepoint': 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 LastDateOfMonth(Func):
4102class LastDateOfMonth(Func):
4103    pass
key = 'lastdateofmonth'
class Extract(Func):
4106class Extract(Func):
4107    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4110class TimestampAdd(Func, TimeUnit):
4111    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4114class TimestampSub(Func, TimeUnit):
4115    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4118class TimestampDiff(Func, TimeUnit):
4119    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4122class TimestampTrunc(Func, TimeUnit):
4123    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4126class TimeAdd(Func, TimeUnit):
4127    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4130class TimeSub(Func, TimeUnit):
4131    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4134class TimeDiff(Func, TimeUnit):
4135    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4138class TimeTrunc(Func, TimeUnit):
4139    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4142class DateFromParts(Func):
4143    _sql_names = ["DATEFROMPARTS"]
4144    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4147class DateStrToDate(Func):
4148    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4151class DateToDateStr(Func):
4152    pass
key = 'datetodatestr'
class DateToDi(Func):
4155class DateToDi(Func):
4156    pass
key = 'datetodi'
class Date(Func):
4160class Date(Func):
4161    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4164class Day(Func):
4165    pass
key = 'day'
class Decode(Func):
4168class Decode(Func):
4169    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4172class DiToDate(Func):
4173    pass
key = 'ditodate'
class Encode(Func):
4176class Encode(Func):
4177    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4180class Exp(Func):
4181    pass
key = 'exp'
class Explode(Func):
4184class Explode(Func):
4185    pass
key = 'explode'
class Floor(Func):
4188class Floor(Func):
4189    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4192class FromBase64(Func):
4193    pass
key = 'frombase64'
class ToBase64(Func):
4196class ToBase64(Func):
4197    pass
key = 'tobase64'
class Greatest(Func):
4200class Greatest(Func):
4201    arg_types = {"this": True, "expressions": False}
4202    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4205class GroupConcat(Func):
4206    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4209class Hex(Func):
4210    pass
key = 'hex'
class If(Func):
4213class If(Func):
4214    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4217class Initcap(Func):
4218    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4221class JSONKeyValue(Expression):
4222    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4225class JSONObject(Func):
4226    arg_types = {
4227        "expressions": False,
4228        "null_handling": False,
4229        "unique_keys": False,
4230        "return_type": False,
4231        "format_json": False,
4232        "encoding": False,
4233    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4236class OpenJSONColumnDef(Expression):
4237    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):
4240class OpenJSON(Func):
4241    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4244class JSONBContains(Binary):
4245    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4248class JSONExtract(Binary, Func):
4249    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4252class JSONExtractScalar(JSONExtract):
4253    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4256class JSONBExtract(JSONExtract):
4257    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4260class JSONBExtractScalar(JSONExtract):
4261    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4264class JSONFormat(Func):
4265    arg_types = {"this": False, "options": False}
4266    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4270class JSONArrayContains(Binary, Predicate, Func):
4271    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4274class Least(Func):
4275    arg_types = {"this": True, "expressions": False}
4276    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4279class Left(Func):
4280    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4287class Length(Func):
4288    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4291class Levenshtein(Func):
4292    arg_types = {
4293        "this": True,
4294        "expression": False,
4295        "ins_cost": False,
4296        "del_cost": False,
4297        "sub_cost": False,
4298    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4301class Ln(Func):
4302    pass
key = 'ln'
class Log(Func):
4305class Log(Func):
4306    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4309class Log2(Func):
4310    pass
key = 'log2'
class Log10(Func):
4313class Log10(Func):
4314    pass
key = 'log10'
class LogicalOr(AggFunc):
4317class LogicalOr(AggFunc):
4318    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4321class LogicalAnd(AggFunc):
4322    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4325class Lower(Func):
4326    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4329class Map(Func):
4330    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4333class MapFromEntries(Func):
4334    pass
key = 'mapfromentries'
class StarMap(Func):
4337class StarMap(Func):
4338    pass
key = 'starmap'
class VarMap(Func):
4341class VarMap(Func):
4342    arg_types = {"keys": True, "values": True}
4343    is_var_len_args = True
4344
4345    @property
4346    def keys(self) -> t.List[Expression]:
4347        return self.args["keys"].expressions
4348
4349    @property
4350    def values(self) -> t.List[Expression]:
4351        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4355class MatchAgainst(Func):
4356    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4359class Max(AggFunc):
4360    arg_types = {"this": True, "expressions": False}
4361    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4364class MD5(Func):
4365    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4369class MD5Digest(Func):
4370    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4373class Min(AggFunc):
4374    arg_types = {"this": True, "expressions": False}
4375    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4378class Month(Func):
4379    pass
key = 'month'
class Nvl2(Func):
4382class Nvl2(Func):
4383    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4386class Posexplode(Func):
4387    pass
key = 'posexplode'
class Pow(Binary, Func):
4390class Pow(Binary, Func):
4391    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4394class PercentileCont(AggFunc):
4395    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4398class PercentileDisc(AggFunc):
4399    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4402class Quantile(AggFunc):
4403    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4406class ApproxQuantile(Quantile):
4407    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):
4410class RangeN(Func):
4411    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4414class ReadCSV(Func):
4415    _sql_names = ["READ_CSV"]
4416    is_var_len_args = True
4417    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4420class Reduce(Func):
4421    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):
4424class RegexpExtract(Func):
4425    arg_types = {
4426        "this": True,
4427        "expression": True,
4428        "position": False,
4429        "occurrence": False,
4430        "parameters": False,
4431        "group": False,
4432    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpLike(Func):
4435class RegexpLike(Func):
4436    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4439class RegexpILike(Func):
4440    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4445class RegexpSplit(Func):
4446    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4449class Repeat(Func):
4450    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4453class Round(Func):
4454    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4457class RowNumber(Func):
4458    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4461class SafeDivide(Func):
4462    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4465class SetAgg(AggFunc):
4466    pass
key = 'setagg'
class SHA(Func):
4469class SHA(Func):
4470    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4473class SHA2(Func):
4474    _sql_names = ["SHA2"]
4475    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4478class SortArray(Func):
4479    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4482class Split(Func):
4483    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4488class Substring(Func):
4489    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4492class StandardHash(Func):
4493    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4496class StrPosition(Func):
4497    arg_types = {
4498        "this": True,
4499        "substr": True,
4500        "position": False,
4501        "instance": False,
4502    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4505class StrToDate(Func):
4506    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4509class StrToTime(Func):
4510    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4515class StrToUnix(Func):
4516    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4519class NumberToStr(Func):
4520    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4523class FromBase(Func):
4524    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4527class Struct(Func):
4528    arg_types = {"expressions": True}
4529    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4532class StructExtract(Func):
4533    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4536class Sum(AggFunc):
4537    pass
key = 'sum'
class Sqrt(Func):
4540class Sqrt(Func):
4541    pass
key = 'sqrt'
class Stddev(AggFunc):
4544class Stddev(AggFunc):
4545    pass
key = 'stddev'
class StddevPop(AggFunc):
4548class StddevPop(AggFunc):
4549    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4552class StddevSamp(AggFunc):
4553    pass
key = 'stddevsamp'
class TimeToStr(Func):
4556class TimeToStr(Func):
4557    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4560class TimeToTimeStr(Func):
4561    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4564class TimeToUnix(Func):
4565    pass
key = 'timetounix'
class TimeStrToDate(Func):
4568class TimeStrToDate(Func):
4569    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4572class TimeStrToTime(Func):
4573    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4576class TimeStrToUnix(Func):
4577    pass
key = 'timestrtounix'
class Trim(Func):
4580class Trim(Func):
4581    arg_types = {
4582        "this": True,
4583        "expression": False,
4584        "position": False,
4585        "collation": False,
4586    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4589class TsOrDsAdd(Func, TimeUnit):
4590    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4593class TsOrDsToDateStr(Func):
4594    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4597class TsOrDsToDate(Func):
4598    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4601class TsOrDiToDi(Func):
4602    pass
key = 'tsorditodi'
class Unhex(Func):
4605class Unhex(Func):
4606    pass
key = 'unhex'
class UnixToStr(Func):
4609class UnixToStr(Func):
4610    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4615class UnixToTime(Func):
4616    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4617
4618    SECONDS = Literal.string("seconds")
4619    MILLIS = Literal.string("millis")
4620    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):
4623class UnixToTimeStr(Func):
4624    pass
key = 'unixtotimestr'
class Upper(Func):
4627class Upper(Func):
4628    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4631class Variance(AggFunc):
4632    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4635class VariancePop(AggFunc):
4636    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4639class Week(Func):
4640    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4643class XMLTable(Func):
4644    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):
4647class Year(Func):
4648    pass
key = 'year'
class Use(Expression):
4651class Use(Expression):
4652    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4655class Merge(Expression):
4656    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):
4659class When(Func):
4660    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):
4665class NextValueFor(Func):
4666    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.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.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:
4703def maybe_parse(
4704    sql_or_expression: ExpOrStr,
4705    *,
4706    into: t.Optional[IntoType] = None,
4707    dialect: DialectType = None,
4708    prefix: t.Optional[str] = None,
4709    copy: bool = False,
4710    **opts,
4711) -> Expression:
4712    """Gracefully handle a possible string or expression.
4713
4714    Example:
4715        >>> maybe_parse("1")
4716        (LITERAL this: 1, is_string: False)
4717        >>> maybe_parse(to_identifier("x"))
4718        (IDENTIFIER this: x, quoted: False)
4719
4720    Args:
4721        sql_or_expression: the SQL code string or an expression
4722        into: the SQLGlot Expression to parse into
4723        dialect: the dialect used to parse the input expressions (in the case that an
4724            input expression is a SQL string).
4725        prefix: a string to prefix the sql with before it gets parsed
4726            (automatically includes a space)
4727        copy: whether or not to copy the expression.
4728        **opts: other options to use to parse the input expressions (again, in the case
4729            that an input expression is a SQL string).
4730
4731    Returns:
4732        Expression: the parsed or given expression.
4733    """
4734    if isinstance(sql_or_expression, Expression):
4735        if copy:
4736            return sql_or_expression.copy()
4737        return sql_or_expression
4738
4739    if sql_or_expression is None:
4740        raise ParseError(f"SQL cannot be None")
4741
4742    import sqlglot
4743
4744    sql = str(sql_or_expression)
4745    if prefix:
4746        sql = f"{prefix} {sql}"
4747
4748    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:
4932def union(
4933    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4934) -> Union:
4935    """
4936    Initializes a syntax tree from one UNION expression.
4937
4938    Example:
4939        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4940        'SELECT * FROM foo UNION SELECT * FROM bla'
4941
4942    Args:
4943        left: the SQL code string corresponding to the left-hand side.
4944            If an `Expression` instance is passed, it will be used as-is.
4945        right: the SQL code string corresponding to the right-hand side.
4946            If an `Expression` instance is passed, it will be used as-is.
4947        distinct: set the DISTINCT flag if and only if this is true.
4948        dialect: the dialect used to parse the input expression.
4949        opts: other options to use to parse the input expressions.
4950
4951    Returns:
4952        The new Union instance.
4953    """
4954    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4955    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4956
4957    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:
4960def intersect(
4961    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4962) -> Intersect:
4963    """
4964    Initializes a syntax tree from one INTERSECT expression.
4965
4966    Example:
4967        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4968        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4969
4970    Args:
4971        left: the SQL code string corresponding to the left-hand side.
4972            If an `Expression` instance is passed, it will be used as-is.
4973        right: the SQL code string corresponding to the right-hand side.
4974            If an `Expression` instance is passed, it will be used as-is.
4975        distinct: set the DISTINCT flag if and only if this is true.
4976        dialect: the dialect used to parse the input expression.
4977        opts: other options to use to parse the input expressions.
4978
4979    Returns:
4980        The new Intersect instance.
4981    """
4982    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4983    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4984
4985    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:
4988def except_(
4989    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4990) -> Except:
4991    """
4992    Initializes a syntax tree from one EXCEPT expression.
4993
4994    Example:
4995        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4996        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4997
4998    Args:
4999        left: the SQL code string corresponding to the left-hand side.
5000            If an `Expression` instance is passed, it will be used as-is.
5001        right: the SQL code string corresponding to the right-hand side.
5002            If an `Expression` instance is passed, it will be used as-is.
5003        distinct: set the DISTINCT flag if and only if this is true.
5004        dialect: the dialect used to parse the input expression.
5005        opts: other options to use to parse the input expressions.
5006
5007    Returns:
5008        The new Except instance.
5009    """
5010    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5011    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5012
5013    return 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:
5016def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5017    """
5018    Initializes a syntax tree from one or multiple SELECT expressions.
5019
5020    Example:
5021        >>> select("col1", "col2").from_("tbl").sql()
5022        'SELECT col1, col2 FROM tbl'
5023
5024    Args:
5025        *expressions: the SQL code string to parse as the expressions of a
5026            SELECT statement. If an Expression instance is passed, this is used as-is.
5027        dialect: the dialect used to parse the input expressions (in the case that an
5028            input expression is a SQL string).
5029        **opts: other options to use to parse the input expressions (again, in the case
5030            that an input expression is a SQL string).
5031
5032    Returns:
5033        Select: the syntax tree for the SELECT statement.
5034    """
5035    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:
5038def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5039    """
5040    Initializes a syntax tree from a FROM expression.
5041
5042    Example:
5043        >>> from_("tbl").select("col1", "col2").sql()
5044        'SELECT col1, col2 FROM tbl'
5045
5046    Args:
5047        *expression: the SQL code string to parse as the FROM expressions of a
5048            SELECT statement. If an Expression instance is passed, this is used as-is.
5049        dialect: the dialect used to parse the input expression (in the case that the
5050            input expression is a SQL string).
5051        **opts: other options to use to parse the input expressions (again, in the case
5052            that the input expression is a SQL string).
5053
5054    Returns:
5055        Select: the syntax tree for the SELECT statement.
5056    """
5057    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:
5060def update(
5061    table: str | Table,
5062    properties: dict,
5063    where: t.Optional[ExpOrStr] = None,
5064    from_: t.Optional[ExpOrStr] = None,
5065    dialect: DialectType = None,
5066    **opts,
5067) -> Update:
5068    """
5069    Creates an update statement.
5070
5071    Example:
5072        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5073        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5074
5075    Args:
5076        *properties: dictionary of properties to set which are
5077            auto converted to sql objects eg None -> NULL
5078        where: sql conditional parsed into a WHERE statement
5079        from_: sql statement parsed into a FROM statement
5080        dialect: the dialect used to parse the input expressions.
5081        **opts: other options to use to parse the input expressions.
5082
5083    Returns:
5084        Update: the syntax tree for the UPDATE statement.
5085    """
5086    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5087    update_expr.set(
5088        "expressions",
5089        [
5090            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5091            for k, v in properties.items()
5092        ],
5093    )
5094    if from_:
5095        update_expr.set(
5096            "from",
5097            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5098        )
5099    if isinstance(where, Condition):
5100        where = Where(this=where)
5101    if where:
5102        update_expr.set(
5103            "where",
5104            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5105        )
5106    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:
5109def delete(
5110    table: ExpOrStr,
5111    where: t.Optional[ExpOrStr] = None,
5112    returning: t.Optional[ExpOrStr] = None,
5113    dialect: DialectType = None,
5114    **opts,
5115) -> Delete:
5116    """
5117    Builds a delete statement.
5118
5119    Example:
5120        >>> delete("my_table", where="id > 1").sql()
5121        'DELETE FROM my_table WHERE id > 1'
5122
5123    Args:
5124        where: sql conditional parsed into a WHERE statement
5125        returning: sql conditional parsed into a RETURNING statement
5126        dialect: the dialect used to parse the input expressions.
5127        **opts: other options to use to parse the input expressions.
5128
5129    Returns:
5130        Delete: the syntax tree for the DELETE statement.
5131    """
5132    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5133    if where:
5134        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5135    if returning:
5136        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5137    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:
5140def insert(
5141    expression: ExpOrStr,
5142    into: ExpOrStr,
5143    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5144    overwrite: t.Optional[bool] = None,
5145    dialect: DialectType = None,
5146    copy: bool = True,
5147    **opts,
5148) -> Insert:
5149    """
5150    Builds an INSERT statement.
5151
5152    Example:
5153        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5154        'INSERT INTO tbl VALUES (1, 2, 3)'
5155
5156    Args:
5157        expression: the sql string or expression of the INSERT statement
5158        into: the tbl to insert data to.
5159        columns: optionally the table's column names.
5160        overwrite: whether to INSERT OVERWRITE or not.
5161        dialect: the dialect used to parse the input expressions.
5162        copy: whether or not to copy the expression.
5163        **opts: other options to use to parse the input expressions.
5164
5165    Returns:
5166        Insert: the syntax tree for the INSERT statement.
5167    """
5168    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5169    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5170
5171    if columns:
5172        this = _apply_list_builder(
5173            *columns,
5174            instance=Schema(this=this),
5175            arg="expressions",
5176            into=Identifier,
5177            copy=False,
5178            dialect=dialect,
5179            **opts,
5180        )
5181
5182    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:
5185def condition(
5186    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5187) -> Condition:
5188    """
5189    Initialize a logical condition expression.
5190
5191    Example:
5192        >>> condition("x=1").sql()
5193        'x = 1'
5194
5195        This is helpful for composing larger logical syntax trees:
5196        >>> where = condition("x=1")
5197        >>> where = where.and_("y=1")
5198        >>> Select().from_("tbl").select("*").where(where).sql()
5199        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5200
5201    Args:
5202        *expression: the SQL code string to parse.
5203            If an Expression instance is passed, this is used as-is.
5204        dialect: the dialect used to parse the input expression (in the case that the
5205            input expression is a SQL string).
5206        copy: Whether or not to copy `expression` (only applies to expressions).
5207        **opts: other options to use to parse the input expressions (again, in the case
5208            that the input expression is a SQL string).
5209
5210    Returns:
5211        The new Condition instance
5212    """
5213    return maybe_parse(
5214        expression,
5215        into=Condition,
5216        dialect=dialect,
5217        copy=copy,
5218        **opts,
5219    )

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:
5222def and_(
5223    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5224) -> Condition:
5225    """
5226    Combine multiple conditions with an AND logical operator.
5227
5228    Example:
5229        >>> and_("x=1", and_("y=1", "z=1")).sql()
5230        'x = 1 AND (y = 1 AND z = 1)'
5231
5232    Args:
5233        *expressions: the SQL code strings to parse.
5234            If an Expression instance is passed, this is used as-is.
5235        dialect: the dialect used to parse the input expression.
5236        copy: whether or not to copy `expressions` (only applies to Expressions).
5237        **opts: other options to use to parse the input expressions.
5238
5239    Returns:
5240        And: the new condition
5241    """
5242    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:
5245def or_(
5246    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5247) -> Condition:
5248    """
5249    Combine multiple conditions with an OR logical operator.
5250
5251    Example:
5252        >>> or_("x=1", or_("y=1", "z=1")).sql()
5253        'x = 1 OR (y = 1 OR z = 1)'
5254
5255    Args:
5256        *expressions: the SQL code strings to parse.
5257            If an Expression instance is passed, this is used as-is.
5258        dialect: the dialect used to parse the input expression.
5259        copy: whether or not to copy `expressions` (only applies to Expressions).
5260        **opts: other options to use to parse the input expressions.
5261
5262    Returns:
5263        Or: the new condition
5264    """
5265    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:
5268def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5269    """
5270    Wrap a condition with a NOT operator.
5271
5272    Example:
5273        >>> not_("this_suit='black'").sql()
5274        "NOT this_suit = 'black'"
5275
5276    Args:
5277        expression: the SQL code string to parse.
5278            If an Expression instance is passed, this is used as-is.
5279        dialect: the dialect used to parse the input expression.
5280        copy: whether to copy the expression or not.
5281        **opts: other options to use to parse the input expressions.
5282
5283    Returns:
5284        The new condition.
5285    """
5286    this = condition(
5287        expression,
5288        dialect=dialect,
5289        copy=copy,
5290        **opts,
5291    )
5292    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:
5295def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5296    """
5297    Wrap an expression in parentheses.
5298
5299    Example:
5300        >>> paren("5 + 3").sql()
5301        '(5 + 3)'
5302
5303    Args:
5304        expression: the SQL code string to parse.
5305            If an Expression instance is passed, this is used as-is.
5306        copy: whether to copy the expression or not.
5307
5308    Returns:
5309        The wrapped expression.
5310    """
5311    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):
5329def to_identifier(name, quoted=None, copy=True):
5330    """Builds an identifier.
5331
5332    Args:
5333        name: The name to turn into an identifier.
5334        quoted: Whether or not force quote the identifier.
5335        copy: Whether or not to copy a passed in Identefier node.
5336
5337    Returns:
5338        The identifier ast node.
5339    """
5340
5341    if name is None:
5342        return None
5343
5344    if isinstance(name, Identifier):
5345        identifier = _maybe_copy(name, copy)
5346    elif isinstance(name, str):
5347        identifier = Identifier(
5348            this=name,
5349            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5350        )
5351    else:
5352        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5353    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:
5359def to_interval(interval: str | Literal) -> Interval:
5360    """Builds an interval expression from a string like '1 day' or '5 months'."""
5361    if isinstance(interval, Literal):
5362        if not interval.is_string:
5363            raise ValueError("Invalid interval string.")
5364
5365        interval = interval.this
5366
5367    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5368
5369    if not interval_parts:
5370        raise ValueError("Invalid interval string.")
5371
5372    return Interval(
5373        this=Literal.string(interval_parts.group(1)),
5374        unit=Var(this=interval_parts.group(2)),
5375    )

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

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:
5547def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5548    """Cast an expression to a data type.
5549
5550    Example:
5551        >>> cast('x + 1', 'int').sql()
5552        'CAST(x + 1 AS INT)'
5553
5554    Args:
5555        expression: The expression to cast.
5556        to: The datatype to cast to.
5557
5558    Returns:
5559        The new Cast instance.
5560    """
5561    expression = maybe_parse(expression, **opts)
5562    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:
5565def table_(
5566    table: Identifier | str,
5567    db: t.Optional[Identifier | str] = None,
5568    catalog: t.Optional[Identifier | str] = None,
5569    quoted: t.Optional[bool] = None,
5570    alias: t.Optional[Identifier | str] = None,
5571) -> Table:
5572    """Build a Table.
5573
5574    Args:
5575        table: Table name.
5576        db: Database name.
5577        catalog: Catalog name.
5578        quote: Whether to force quotes on the table's identifiers.
5579        alias: Table's alias.
5580
5581    Returns:
5582        The new Table instance.
5583    """
5584    return Table(
5585        this=to_identifier(table, quoted=quoted),
5586        db=to_identifier(db, quoted=quoted),
5587        catalog=to_identifier(catalog, quoted=quoted),
5588        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5589    )

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:
5592def values(
5593    values: t.Iterable[t.Tuple[t.Any, ...]],
5594    alias: t.Optional[str] = None,
5595    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5596) -> Values:
5597    """Build VALUES statement.
5598
5599    Example:
5600        >>> values([(1, '2')]).sql()
5601        "VALUES (1, '2')"
5602
5603    Args:
5604        values: values statements that will be converted to SQL
5605        alias: optional alias
5606        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5607         If either are provided then an alias is also required.
5608
5609    Returns:
5610        Values: the Values expression object
5611    """
5612    if columns and not alias:
5613        raise ValueError("Alias is required when providing columns")
5614
5615    return Values(
5616        expressions=[convert(tup) for tup in values],
5617        alias=(
5618            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5619            if columns
5620            else (TableAlias(this=to_identifier(alias)) if alias else None)
5621        ),
5622    )

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:
5625def var(name: t.Optional[ExpOrStr]) -> Var:
5626    """Build a SQL variable.
5627
5628    Example:
5629        >>> repr(var('x'))
5630        '(VAR this: x)'
5631
5632        >>> repr(var(column('x', table='y')))
5633        '(VAR this: x)'
5634
5635    Args:
5636        name: The name of the var or an expression who's name will become the var.
5637
5638    Returns:
5639        The new variable node.
5640    """
5641    if not name:
5642        raise ValueError("Cannot convert empty name into var.")
5643
5644    if isinstance(name, Expression):
5645        name = name.name
5646    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:
5649def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5650    """Build ALTER TABLE... RENAME... expression
5651
5652    Args:
5653        old_name: The old name of the table
5654        new_name: The new name of the table
5655
5656    Returns:
5657        Alter table expression
5658    """
5659    old_table = to_table(old_name)
5660    new_table = to_table(new_name)
5661    return AlterTable(
5662        this=old_table,
5663        actions=[
5664            RenameTable(this=new_table),
5665        ],
5666    )

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

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:
5756def table_name(table: Table | str, dialect: DialectType = None) -> str:
5757    """Get the full name of a table as a string.
5758
5759    Args:
5760        table: Table expression node or string.
5761        dialect: The dialect to generate the table name for.
5762
5763    Examples:
5764        >>> from sqlglot import exp, parse_one
5765        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5766        'a.b.c'
5767
5768    Returns:
5769        The table name.
5770    """
5771
5772    table = maybe_parse(table, into=Table)
5773
5774    if not table:
5775        raise ValueError(f"Cannot parse {table}")
5776
5777    return ".".join(
5778        part.sql(dialect=dialect, identify=True)
5779        if not SAFE_IDENTIFIER_RE.match(part.name)
5780        else part.name
5781        for part in table.parts
5782    )

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

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5940def false() -> Boolean:
5941    """
5942    Returns a false Boolean expression.
5943    """
5944    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5947def null() -> Null:
5948    """
5949    Returns a Null expression.
5950    """
5951    return Null()

Returns a Null expression.

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