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        return [
2313            t.cast(Identifier, self.args[part])
2314            for part in ("catalog", "db", "this")
2315            if self.args.get(part)
2316        ]
2317
2318
2319# See the TSQL "Querying data in a system-versioned temporal table" page
2320class SystemTime(Expression):
2321    arg_types = {
2322        "this": False,
2323        "expression": False,
2324        "kind": True,
2325    }
2326
2327
2328class Union(Subqueryable):
2329    arg_types = {
2330        "with": False,
2331        "this": True,
2332        "expression": True,
2333        "distinct": False,
2334        **QUERY_MODIFIERS,
2335    }
2336
2337    def limit(
2338        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2339    ) -> Select:
2340        """
2341        Set the LIMIT expression.
2342
2343        Example:
2344            >>> select("1").union(select("1")).limit(1).sql()
2345            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2346
2347        Args:
2348            expression: the SQL code string to parse.
2349                This can also be an integer.
2350                If a `Limit` instance is passed, this is used as-is.
2351                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2352            dialect: the dialect used to parse the input expression.
2353            copy: if `False`, modify this expression instance in-place.
2354            opts: other options to use to parse the input expressions.
2355
2356        Returns:
2357            The limited subqueryable.
2358        """
2359        return (
2360            select("*")
2361            .from_(self.subquery(alias="_l_0", copy=copy))
2362            .limit(expression, dialect=dialect, copy=False, **opts)
2363        )
2364
2365    def select(
2366        self,
2367        *expressions: t.Optional[ExpOrStr],
2368        append: bool = True,
2369        dialect: DialectType = None,
2370        copy: bool = True,
2371        **opts,
2372    ) -> Union:
2373        """Append to or set the SELECT of the union recursively.
2374
2375        Example:
2376            >>> from sqlglot import parse_one
2377            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2378            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2379
2380        Args:
2381            *expressions: the SQL code strings to parse.
2382                If an `Expression` instance is passed, it will be used as-is.
2383            append: if `True`, add to any existing expressions.
2384                Otherwise, this resets the expressions.
2385            dialect: the dialect used to parse the input expressions.
2386            copy: if `False`, modify this expression instance in-place.
2387            opts: other options to use to parse the input expressions.
2388
2389        Returns:
2390            Union: the modified expression.
2391        """
2392        this = self.copy() if copy else self
2393        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2394        this.expression.unnest().select(
2395            *expressions, append=append, dialect=dialect, copy=False, **opts
2396        )
2397        return this
2398
2399    @property
2400    def named_selects(self) -> t.List[str]:
2401        return self.this.unnest().named_selects
2402
2403    @property
2404    def is_star(self) -> bool:
2405        return self.this.is_star or self.expression.is_star
2406
2407    @property
2408    def selects(self) -> t.List[Expression]:
2409        return self.this.unnest().selects
2410
2411    @property
2412    def left(self):
2413        return self.this
2414
2415    @property
2416    def right(self):
2417        return self.expression
2418
2419
2420class Except(Union):
2421    pass
2422
2423
2424class Intersect(Union):
2425    pass
2426
2427
2428class Unnest(UDTF):
2429    arg_types = {
2430        "expressions": True,
2431        "ordinality": False,
2432        "alias": False,
2433        "offset": False,
2434    }
2435
2436
2437class Update(Expression):
2438    arg_types = {
2439        "with": False,
2440        "this": False,
2441        "expressions": True,
2442        "from": False,
2443        "where": False,
2444        "returning": False,
2445        "limit": False,
2446    }
2447
2448
2449class Values(UDTF):
2450    arg_types = {
2451        "expressions": True,
2452        "ordinality": False,
2453        "alias": False,
2454    }
2455
2456
2457class Var(Expression):
2458    pass
2459
2460
2461class Schema(Expression):
2462    arg_types = {"this": False, "expressions": False}
2463
2464
2465# https://dev.mysql.com/doc/refman/8.0/en/select.html
2466# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html
2467class Lock(Expression):
2468    arg_types = {"update": True, "expressions": False, "wait": False}
2469
2470
2471class Select(Subqueryable):
2472    arg_types = {
2473        "with": False,
2474        "kind": False,
2475        "expressions": False,
2476        "hint": False,
2477        "distinct": False,
2478        "into": False,
2479        "from": False,
2480        **QUERY_MODIFIERS,
2481    }
2482
2483    def from_(
2484        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2485    ) -> Select:
2486        """
2487        Set the FROM expression.
2488
2489        Example:
2490            >>> Select().from_("tbl").select("x").sql()
2491            'SELECT x FROM tbl'
2492
2493        Args:
2494            expression : the SQL code strings to parse.
2495                If a `From` instance is passed, this is used as-is.
2496                If another `Expression` instance is passed, it will be wrapped in a `From`.
2497            dialect: the dialect used to parse the input expression.
2498            copy: if `False`, modify this expression instance in-place.
2499            opts: other options to use to parse the input expressions.
2500
2501        Returns:
2502            The modified Select expression.
2503        """
2504        return _apply_builder(
2505            expression=expression,
2506            instance=self,
2507            arg="from",
2508            into=From,
2509            prefix="FROM",
2510            dialect=dialect,
2511            copy=copy,
2512            **opts,
2513        )
2514
2515    def group_by(
2516        self,
2517        *expressions: t.Optional[ExpOrStr],
2518        append: bool = True,
2519        dialect: DialectType = None,
2520        copy: bool = True,
2521        **opts,
2522    ) -> Select:
2523        """
2524        Set the GROUP BY expression.
2525
2526        Example:
2527            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2528            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2529
2530        Args:
2531            *expressions: the SQL code strings to parse.
2532                If a `Group` instance is passed, this is used as-is.
2533                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2534                If nothing is passed in then a group by is not applied to the expression
2535            append: if `True`, add to any existing expressions.
2536                Otherwise, this flattens all the `Group` expression into a single expression.
2537            dialect: the dialect used to parse the input expression.
2538            copy: if `False`, modify this expression instance in-place.
2539            opts: other options to use to parse the input expressions.
2540
2541        Returns:
2542            The modified Select expression.
2543        """
2544        if not expressions:
2545            return self if not copy else self.copy()
2546
2547        return _apply_child_list_builder(
2548            *expressions,
2549            instance=self,
2550            arg="group",
2551            append=append,
2552            copy=copy,
2553            prefix="GROUP BY",
2554            into=Group,
2555            dialect=dialect,
2556            **opts,
2557        )
2558
2559    def order_by(
2560        self,
2561        *expressions: t.Optional[ExpOrStr],
2562        append: bool = True,
2563        dialect: DialectType = None,
2564        copy: bool = True,
2565        **opts,
2566    ) -> Select:
2567        """
2568        Set the ORDER BY expression.
2569
2570        Example:
2571            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2572            'SELECT x FROM tbl ORDER BY x DESC'
2573
2574        Args:
2575            *expressions: the SQL code strings to parse.
2576                If a `Group` instance is passed, this is used as-is.
2577                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2578            append: if `True`, add to any existing expressions.
2579                Otherwise, this flattens all the `Order` expression into a single expression.
2580            dialect: the dialect used to parse the input expression.
2581            copy: if `False`, modify this expression instance in-place.
2582            opts: other options to use to parse the input expressions.
2583
2584        Returns:
2585            The modified Select expression.
2586        """
2587        return _apply_child_list_builder(
2588            *expressions,
2589            instance=self,
2590            arg="order",
2591            append=append,
2592            copy=copy,
2593            prefix="ORDER BY",
2594            into=Order,
2595            dialect=dialect,
2596            **opts,
2597        )
2598
2599    def sort_by(
2600        self,
2601        *expressions: t.Optional[ExpOrStr],
2602        append: bool = True,
2603        dialect: DialectType = None,
2604        copy: bool = True,
2605        **opts,
2606    ) -> Select:
2607        """
2608        Set the SORT BY expression.
2609
2610        Example:
2611            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2612            'SELECT x FROM tbl SORT BY x DESC'
2613
2614        Args:
2615            *expressions: the SQL code strings to parse.
2616                If a `Group` instance is passed, this is used as-is.
2617                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2618            append: if `True`, add to any existing expressions.
2619                Otherwise, this flattens all the `Order` expression into a single expression.
2620            dialect: the dialect used to parse the input expression.
2621            copy: if `False`, modify this expression instance in-place.
2622            opts: other options to use to parse the input expressions.
2623
2624        Returns:
2625            The modified Select expression.
2626        """
2627        return _apply_child_list_builder(
2628            *expressions,
2629            instance=self,
2630            arg="sort",
2631            append=append,
2632            copy=copy,
2633            prefix="SORT BY",
2634            into=Sort,
2635            dialect=dialect,
2636            **opts,
2637        )
2638
2639    def cluster_by(
2640        self,
2641        *expressions: t.Optional[ExpOrStr],
2642        append: bool = True,
2643        dialect: DialectType = None,
2644        copy: bool = True,
2645        **opts,
2646    ) -> Select:
2647        """
2648        Set the CLUSTER BY expression.
2649
2650        Example:
2651            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2652            'SELECT x FROM tbl CLUSTER BY x DESC'
2653
2654        Args:
2655            *expressions: the SQL code strings to parse.
2656                If a `Group` instance is passed, this is used as-is.
2657                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2658            append: if `True`, add to any existing expressions.
2659                Otherwise, this flattens all the `Order` expression into a single expression.
2660            dialect: the dialect used to parse the input expression.
2661            copy: if `False`, modify this expression instance in-place.
2662            opts: other options to use to parse the input expressions.
2663
2664        Returns:
2665            The modified Select expression.
2666        """
2667        return _apply_child_list_builder(
2668            *expressions,
2669            instance=self,
2670            arg="cluster",
2671            append=append,
2672            copy=copy,
2673            prefix="CLUSTER BY",
2674            into=Cluster,
2675            dialect=dialect,
2676            **opts,
2677        )
2678
2679    def limit(
2680        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2681    ) -> Select:
2682        """
2683        Set the LIMIT expression.
2684
2685        Example:
2686            >>> Select().from_("tbl").select("x").limit(10).sql()
2687            'SELECT x FROM tbl LIMIT 10'
2688
2689        Args:
2690            expression: the SQL code string to parse.
2691                This can also be an integer.
2692                If a `Limit` instance is passed, this is used as-is.
2693                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2694            dialect: the dialect used to parse the input expression.
2695            copy: if `False`, modify this expression instance in-place.
2696            opts: other options to use to parse the input expressions.
2697
2698        Returns:
2699            Select: the modified expression.
2700        """
2701        return _apply_builder(
2702            expression=expression,
2703            instance=self,
2704            arg="limit",
2705            into=Limit,
2706            prefix="LIMIT",
2707            dialect=dialect,
2708            copy=copy,
2709            **opts,
2710        )
2711
2712    def offset(
2713        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2714    ) -> Select:
2715        """
2716        Set the OFFSET expression.
2717
2718        Example:
2719            >>> Select().from_("tbl").select("x").offset(10).sql()
2720            'SELECT x FROM tbl OFFSET 10'
2721
2722        Args:
2723            expression: the SQL code string to parse.
2724                This can also be an integer.
2725                If a `Offset` instance is passed, this is used as-is.
2726                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2727            dialect: the dialect used to parse the input expression.
2728            copy: if `False`, modify this expression instance in-place.
2729            opts: other options to use to parse the input expressions.
2730
2731        Returns:
2732            The modified Select expression.
2733        """
2734        return _apply_builder(
2735            expression=expression,
2736            instance=self,
2737            arg="offset",
2738            into=Offset,
2739            prefix="OFFSET",
2740            dialect=dialect,
2741            copy=copy,
2742            **opts,
2743        )
2744
2745    def select(
2746        self,
2747        *expressions: t.Optional[ExpOrStr],
2748        append: bool = True,
2749        dialect: DialectType = None,
2750        copy: bool = True,
2751        **opts,
2752    ) -> Select:
2753        """
2754        Append to or set the SELECT expressions.
2755
2756        Example:
2757            >>> Select().select("x", "y").sql()
2758            'SELECT x, y'
2759
2760        Args:
2761            *expressions: the SQL code strings to parse.
2762                If an `Expression` instance is passed, it will be used as-is.
2763            append: if `True`, add to any existing expressions.
2764                Otherwise, this resets the expressions.
2765            dialect: the dialect used to parse the input expressions.
2766            copy: if `False`, modify this expression instance in-place.
2767            opts: other options to use to parse the input expressions.
2768
2769        Returns:
2770            The modified Select expression.
2771        """
2772        return _apply_list_builder(
2773            *expressions,
2774            instance=self,
2775            arg="expressions",
2776            append=append,
2777            dialect=dialect,
2778            copy=copy,
2779            **opts,
2780        )
2781
2782    def lateral(
2783        self,
2784        *expressions: t.Optional[ExpOrStr],
2785        append: bool = True,
2786        dialect: DialectType = None,
2787        copy: bool = True,
2788        **opts,
2789    ) -> Select:
2790        """
2791        Append to or set the LATERAL expressions.
2792
2793        Example:
2794            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2795            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2796
2797        Args:
2798            *expressions: the SQL code strings to parse.
2799                If an `Expression` instance is passed, it will be used as-is.
2800            append: if `True`, add to any existing expressions.
2801                Otherwise, this resets the expressions.
2802            dialect: the dialect used to parse the input expressions.
2803            copy: if `False`, modify this expression instance in-place.
2804            opts: other options to use to parse the input expressions.
2805
2806        Returns:
2807            The modified Select expression.
2808        """
2809        return _apply_list_builder(
2810            *expressions,
2811            instance=self,
2812            arg="laterals",
2813            append=append,
2814            into=Lateral,
2815            prefix="LATERAL VIEW",
2816            dialect=dialect,
2817            copy=copy,
2818            **opts,
2819        )
2820
2821    def join(
2822        self,
2823        expression: ExpOrStr,
2824        on: t.Optional[ExpOrStr] = None,
2825        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2826        append: bool = True,
2827        join_type: t.Optional[str] = None,
2828        join_alias: t.Optional[Identifier | str] = None,
2829        dialect: DialectType = None,
2830        copy: bool = True,
2831        **opts,
2832    ) -> Select:
2833        """
2834        Append to or set the JOIN expressions.
2835
2836        Example:
2837            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2838            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2839
2840            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2841            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2842
2843            Use `join_type` to change the type of join:
2844
2845            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2846            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2847
2848        Args:
2849            expression: the SQL code string to parse.
2850                If an `Expression` instance is passed, it will be used as-is.
2851            on: optionally specify the join "on" criteria as a SQL string.
2852                If an `Expression` instance is passed, it will be used as-is.
2853            using: optionally specify the join "using" criteria as a SQL string.
2854                If an `Expression` instance is passed, it will be used as-is.
2855            append: if `True`, add to any existing expressions.
2856                Otherwise, this resets the expressions.
2857            join_type: if set, alter the parsed join type.
2858            join_alias: an optional alias for the joined source.
2859            dialect: the dialect used to parse the input expressions.
2860            copy: if `False`, modify this expression instance in-place.
2861            opts: other options to use to parse the input expressions.
2862
2863        Returns:
2864            Select: the modified expression.
2865        """
2866        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2867
2868        try:
2869            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2870        except ParseError:
2871            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2872
2873        join = expression if isinstance(expression, Join) else Join(this=expression)
2874
2875        if isinstance(join.this, Select):
2876            join.this.replace(join.this.subquery())
2877
2878        if join_type:
2879            method: t.Optional[Token]
2880            side: t.Optional[Token]
2881            kind: t.Optional[Token]
2882
2883            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2884
2885            if method:
2886                join.set("method", method.text)
2887            if side:
2888                join.set("side", side.text)
2889            if kind:
2890                join.set("kind", kind.text)
2891
2892        if on:
2893            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2894            join.set("on", on)
2895
2896        if using:
2897            join = _apply_list_builder(
2898                *ensure_list(using),
2899                instance=join,
2900                arg="using",
2901                append=append,
2902                copy=copy,
2903                **opts,
2904            )
2905
2906        if join_alias:
2907            join.set("this", alias_(join.this, join_alias, table=True))
2908
2909        return _apply_list_builder(
2910            join,
2911            instance=self,
2912            arg="joins",
2913            append=append,
2914            copy=copy,
2915            **opts,
2916        )
2917
2918    def where(
2919        self,
2920        *expressions: t.Optional[ExpOrStr],
2921        append: bool = True,
2922        dialect: DialectType = None,
2923        copy: bool = True,
2924        **opts,
2925    ) -> Select:
2926        """
2927        Append to or set the WHERE expressions.
2928
2929        Example:
2930            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2931            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2932
2933        Args:
2934            *expressions: the SQL code strings to parse.
2935                If an `Expression` instance is passed, it will be used as-is.
2936                Multiple expressions are combined with an AND operator.
2937            append: if `True`, AND the new expressions to any existing expression.
2938                Otherwise, this resets the expression.
2939            dialect: the dialect used to parse the input expressions.
2940            copy: if `False`, modify this expression instance in-place.
2941            opts: other options to use to parse the input expressions.
2942
2943        Returns:
2944            Select: the modified expression.
2945        """
2946        return _apply_conjunction_builder(
2947            *expressions,
2948            instance=self,
2949            arg="where",
2950            append=append,
2951            into=Where,
2952            dialect=dialect,
2953            copy=copy,
2954            **opts,
2955        )
2956
2957    def having(
2958        self,
2959        *expressions: t.Optional[ExpOrStr],
2960        append: bool = True,
2961        dialect: DialectType = None,
2962        copy: bool = True,
2963        **opts,
2964    ) -> Select:
2965        """
2966        Append to or set the HAVING expressions.
2967
2968        Example:
2969            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2970            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2971
2972        Args:
2973            *expressions: the SQL code strings to parse.
2974                If an `Expression` instance is passed, it will be used as-is.
2975                Multiple expressions are combined with an AND operator.
2976            append: if `True`, AND the new expressions to any existing expression.
2977                Otherwise, this resets the expression.
2978            dialect: the dialect used to parse the input expressions.
2979            copy: if `False`, modify this expression instance in-place.
2980            opts: other options to use to parse the input expressions.
2981
2982        Returns:
2983            The modified Select expression.
2984        """
2985        return _apply_conjunction_builder(
2986            *expressions,
2987            instance=self,
2988            arg="having",
2989            append=append,
2990            into=Having,
2991            dialect=dialect,
2992            copy=copy,
2993            **opts,
2994        )
2995
2996    def window(
2997        self,
2998        *expressions: t.Optional[ExpOrStr],
2999        append: bool = True,
3000        dialect: DialectType = None,
3001        copy: bool = True,
3002        **opts,
3003    ) -> Select:
3004        return _apply_list_builder(
3005            *expressions,
3006            instance=self,
3007            arg="windows",
3008            append=append,
3009            into=Window,
3010            dialect=dialect,
3011            copy=copy,
3012            **opts,
3013        )
3014
3015    def qualify(
3016        self,
3017        *expressions: t.Optional[ExpOrStr],
3018        append: bool = True,
3019        dialect: DialectType = None,
3020        copy: bool = True,
3021        **opts,
3022    ) -> Select:
3023        return _apply_conjunction_builder(
3024            *expressions,
3025            instance=self,
3026            arg="qualify",
3027            append=append,
3028            into=Qualify,
3029            dialect=dialect,
3030            copy=copy,
3031            **opts,
3032        )
3033
3034    def distinct(
3035        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3036    ) -> Select:
3037        """
3038        Set the OFFSET expression.
3039
3040        Example:
3041            >>> Select().from_("tbl").select("x").distinct().sql()
3042            'SELECT DISTINCT x FROM tbl'
3043
3044        Args:
3045            ons: the expressions to distinct on
3046            distinct: whether the Select should be distinct
3047            copy: if `False`, modify this expression instance in-place.
3048
3049        Returns:
3050            Select: the modified expression.
3051        """
3052        instance = _maybe_copy(self, copy)
3053        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3054        instance.set("distinct", Distinct(on=on) if distinct else None)
3055        return instance
3056
3057    def ctas(
3058        self,
3059        table: ExpOrStr,
3060        properties: t.Optional[t.Dict] = None,
3061        dialect: DialectType = None,
3062        copy: bool = True,
3063        **opts,
3064    ) -> Create:
3065        """
3066        Convert this expression to a CREATE TABLE AS statement.
3067
3068        Example:
3069            >>> Select().select("*").from_("tbl").ctas("x").sql()
3070            'CREATE TABLE x AS SELECT * FROM tbl'
3071
3072        Args:
3073            table: the SQL code string to parse as the table name.
3074                If another `Expression` instance is passed, it will be used as-is.
3075            properties: an optional mapping of table properties
3076            dialect: the dialect used to parse the input table.
3077            copy: if `False`, modify this expression instance in-place.
3078            opts: other options to use to parse the input table.
3079
3080        Returns:
3081            The new Create expression.
3082        """
3083        instance = _maybe_copy(self, copy)
3084        table_expression = maybe_parse(
3085            table,
3086            into=Table,
3087            dialect=dialect,
3088            **opts,
3089        )
3090        properties_expression = None
3091        if properties:
3092            properties_expression = Properties.from_dict(properties)
3093
3094        return Create(
3095            this=table_expression,
3096            kind="table",
3097            expression=instance,
3098            properties=properties_expression,
3099        )
3100
3101    def lock(self, update: bool = True, copy: bool = True) -> Select:
3102        """
3103        Set the locking read mode for this expression.
3104
3105        Examples:
3106            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3107            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3108
3109            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3110            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3111
3112        Args:
3113            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3114            copy: if `False`, modify this expression instance in-place.
3115
3116        Returns:
3117            The modified expression.
3118        """
3119        inst = _maybe_copy(self, copy)
3120        inst.set("locks", [Lock(update=update)])
3121
3122        return inst
3123
3124    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3125        """
3126        Set hints for this expression.
3127
3128        Examples:
3129            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3130            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3131
3132        Args:
3133            hints: The SQL code strings to parse as the hints.
3134                If an `Expression` instance is passed, it will be used as-is.
3135            dialect: The dialect used to parse the hints.
3136            copy: If `False`, modify this expression instance in-place.
3137
3138        Returns:
3139            The modified expression.
3140        """
3141        inst = _maybe_copy(self, copy)
3142        inst.set(
3143            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3144        )
3145
3146        return inst
3147
3148    @property
3149    def named_selects(self) -> t.List[str]:
3150        return [e.output_name for e in self.expressions if e.alias_or_name]
3151
3152    @property
3153    def is_star(self) -> bool:
3154        return any(expression.is_star for expression in self.expressions)
3155
3156    @property
3157    def selects(self) -> t.List[Expression]:
3158        return self.expressions
3159
3160
3161class Subquery(DerivedTable, Unionable):
3162    arg_types = {
3163        "this": True,
3164        "alias": False,
3165        "with": False,
3166        **QUERY_MODIFIERS,
3167    }
3168
3169    def unnest(self):
3170        """
3171        Returns the first non subquery.
3172        """
3173        expression = self
3174        while isinstance(expression, Subquery):
3175            expression = expression.this
3176        return expression
3177
3178    @property
3179    def is_star(self) -> bool:
3180        return self.this.is_star
3181
3182    @property
3183    def output_name(self) -> str:
3184        return self.alias
3185
3186
3187class TableSample(Expression):
3188    arg_types = {
3189        "this": False,
3190        "method": False,
3191        "bucket_numerator": False,
3192        "bucket_denominator": False,
3193        "bucket_field": False,
3194        "percent": False,
3195        "rows": False,
3196        "size": False,
3197        "seed": False,
3198        "kind": False,
3199    }
3200
3201
3202class Tag(Expression):
3203    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3204
3205    arg_types = {
3206        "this": False,
3207        "prefix": False,
3208        "postfix": False,
3209    }
3210
3211
3212# Represents both the standard SQL PIVOT operator and DuckDB's "simplified" PIVOT syntax
3213# https://duckdb.org/docs/sql/statements/pivot
3214class Pivot(Expression):
3215    arg_types = {
3216        "this": False,
3217        "alias": False,
3218        "expressions": True,
3219        "field": False,
3220        "unpivot": False,
3221        "using": False,
3222        "group": False,
3223        "columns": False,
3224    }
3225
3226
3227class Window(Expression):
3228    arg_types = {
3229        "this": True,
3230        "partition_by": False,
3231        "order": False,
3232        "spec": False,
3233        "alias": False,
3234        "over": False,
3235        "first": False,
3236    }
3237
3238
3239class WindowSpec(Expression):
3240    arg_types = {
3241        "kind": False,
3242        "start": False,
3243        "start_side": False,
3244        "end": False,
3245        "end_side": False,
3246    }
3247
3248
3249class Where(Expression):
3250    pass
3251
3252
3253class Star(Expression):
3254    arg_types = {"except": False, "replace": False}
3255
3256    @property
3257    def name(self) -> str:
3258        return "*"
3259
3260    @property
3261    def output_name(self) -> str:
3262        return self.name
3263
3264
3265class Parameter(Condition):
3266    arg_types = {"this": True, "wrapped": False}
3267
3268
3269class SessionParameter(Condition):
3270    arg_types = {"this": True, "kind": False}
3271
3272
3273class Placeholder(Condition):
3274    arg_types = {"this": False, "kind": False}
3275
3276
3277class Null(Condition):
3278    arg_types: t.Dict[str, t.Any] = {}
3279
3280    @property
3281    def name(self) -> str:
3282        return "NULL"
3283
3284
3285class Boolean(Condition):
3286    pass
3287
3288
3289class DataTypeSize(Expression):
3290    arg_types = {"this": True, "expression": False}
3291
3292
3293class DataType(Expression):
3294    arg_types = {
3295        "this": True,
3296        "expressions": False,
3297        "nested": False,
3298        "values": False,
3299        "prefix": False,
3300    }
3301
3302    class Type(AutoName):
3303        ARRAY = auto()
3304        BIGDECIMAL = auto()
3305        BIGINT = auto()
3306        BIGSERIAL = auto()
3307        BINARY = auto()
3308        BIT = auto()
3309        BOOLEAN = auto()
3310        CHAR = auto()
3311        DATE = auto()
3312        DATETIME = auto()
3313        DATETIME64 = auto()
3314        ENUM = auto()
3315        INT4RANGE = auto()
3316        INT4MULTIRANGE = auto()
3317        INT8RANGE = auto()
3318        INT8MULTIRANGE = auto()
3319        NUMRANGE = auto()
3320        NUMMULTIRANGE = auto()
3321        TSRANGE = auto()
3322        TSMULTIRANGE = auto()
3323        TSTZRANGE = auto()
3324        TSTZMULTIRANGE = auto()
3325        DATERANGE = auto()
3326        DATEMULTIRANGE = auto()
3327        DECIMAL = auto()
3328        DOUBLE = auto()
3329        FLOAT = auto()
3330        GEOGRAPHY = auto()
3331        GEOMETRY = auto()
3332        HLLSKETCH = auto()
3333        HSTORE = auto()
3334        IMAGE = auto()
3335        INET = auto()
3336        INT = auto()
3337        INT128 = auto()
3338        INT256 = auto()
3339        INTERVAL = auto()
3340        JSON = auto()
3341        JSONB = auto()
3342        LONGBLOB = auto()
3343        LONGTEXT = auto()
3344        MAP = auto()
3345        MEDIUMBLOB = auto()
3346        MEDIUMTEXT = auto()
3347        MONEY = auto()
3348        NCHAR = auto()
3349        NULL = auto()
3350        NULLABLE = auto()
3351        NVARCHAR = auto()
3352        OBJECT = auto()
3353        ROWVERSION = auto()
3354        SERIAL = auto()
3355        SET = auto()
3356        SMALLINT = auto()
3357        SMALLMONEY = auto()
3358        SMALLSERIAL = auto()
3359        STRUCT = auto()
3360        SUPER = auto()
3361        TEXT = auto()
3362        TIME = auto()
3363        TIMESTAMP = auto()
3364        TIMESTAMPTZ = auto()
3365        TIMESTAMPLTZ = auto()
3366        TINYINT = auto()
3367        UBIGINT = auto()
3368        UINT = auto()
3369        USMALLINT = auto()
3370        UTINYINT = auto()
3371        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3372        UINT128 = auto()
3373        UINT256 = auto()
3374        UNIQUEIDENTIFIER = auto()
3375        USERDEFINED = "USER-DEFINED"
3376        UUID = auto()
3377        VARBINARY = auto()
3378        VARCHAR = auto()
3379        VARIANT = auto()
3380        XML = auto()
3381
3382    TEXT_TYPES = {
3383        Type.CHAR,
3384        Type.NCHAR,
3385        Type.VARCHAR,
3386        Type.NVARCHAR,
3387        Type.TEXT,
3388    }
3389
3390    INTEGER_TYPES = {
3391        Type.INT,
3392        Type.TINYINT,
3393        Type.SMALLINT,
3394        Type.BIGINT,
3395        Type.INT128,
3396        Type.INT256,
3397    }
3398
3399    FLOAT_TYPES = {
3400        Type.FLOAT,
3401        Type.DOUBLE,
3402    }
3403
3404    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3405
3406    TEMPORAL_TYPES = {
3407        Type.TIME,
3408        Type.TIMESTAMP,
3409        Type.TIMESTAMPTZ,
3410        Type.TIMESTAMPLTZ,
3411        Type.DATE,
3412        Type.DATETIME,
3413        Type.DATETIME64,
3414    }
3415
3416    META_TYPES = {"UNKNOWN", "NULL"}
3417
3418    @classmethod
3419    def build(
3420        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3421    ) -> DataType:
3422        from sqlglot import parse_one
3423
3424        if isinstance(dtype, str):
3425            upper = dtype.upper()
3426            if upper in DataType.META_TYPES:
3427                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3428            else:
3429                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3430
3431            if data_type_exp is None:
3432                raise ValueError(f"Unparsable data type value: {dtype}")
3433        elif isinstance(dtype, DataType.Type):
3434            data_type_exp = DataType(this=dtype)
3435        elif isinstance(dtype, DataType):
3436            return dtype
3437        else:
3438            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3439
3440        return DataType(**{**data_type_exp.args, **kwargs})
3441
3442    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3443        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
3444
3445
3446# https://www.postgresql.org/docs/15/datatype-pseudo.html
3447class PseudoType(Expression):
3448    pass
3449
3450
3451# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
3452class SubqueryPredicate(Predicate):
3453    pass
3454
3455
3456class All(SubqueryPredicate):
3457    pass
3458
3459
3460class Any(SubqueryPredicate):
3461    pass
3462
3463
3464class Exists(SubqueryPredicate):
3465    pass
3466
3467
3468# Commands to interact with the databases or engines. For most of the command
3469# expressions we parse whatever comes after the command's name as a string.
3470class Command(Expression):
3471    arg_types = {"this": True, "expression": False}
3472
3473
3474class Transaction(Expression):
3475    arg_types = {"this": False, "modes": False}
3476
3477
3478class Commit(Expression):
3479    arg_types = {"chain": False}
3480
3481
3482class Rollback(Expression):
3483    arg_types = {"savepoint": False}
3484
3485
3486class AlterTable(Expression):
3487    arg_types = {"this": True, "actions": True, "exists": False}
3488
3489
3490class AddConstraint(Expression):
3491    arg_types = {"this": False, "expression": False, "enforced": False}
3492
3493
3494class DropPartition(Expression):
3495    arg_types = {"expressions": True, "exists": False}
3496
3497
3498# Binary expressions like (ADD a b)
3499class Binary(Condition):
3500    arg_types = {"this": True, "expression": True}
3501
3502    @property
3503    def left(self):
3504        return self.this
3505
3506    @property
3507    def right(self):
3508        return self.expression
3509
3510
3511class Add(Binary):
3512    pass
3513
3514
3515class Connector(Binary):
3516    pass
3517
3518
3519class And(Connector):
3520    pass
3521
3522
3523class Or(Connector):
3524    pass
3525
3526
3527class Xor(Connector):
3528    pass
3529
3530
3531class BitwiseAnd(Binary):
3532    pass
3533
3534
3535class BitwiseLeftShift(Binary):
3536    pass
3537
3538
3539class BitwiseOr(Binary):
3540    pass
3541
3542
3543class BitwiseRightShift(Binary):
3544    pass
3545
3546
3547class BitwiseXor(Binary):
3548    pass
3549
3550
3551class Div(Binary):
3552    pass
3553
3554
3555class Overlaps(Binary):
3556    pass
3557
3558
3559class Dot(Binary):
3560    @property
3561    def name(self) -> str:
3562        return self.expression.name
3563
3564    @property
3565    def output_name(self) -> str:
3566        return self.name
3567
3568    @classmethod
3569    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3570        """Build a Dot object with a sequence of expressions."""
3571        if len(expressions) < 2:
3572            raise ValueError(f"Dot requires >= 2 expressions.")
3573
3574        a, b, *expressions = expressions
3575        dot = Dot(this=a, expression=b)
3576
3577        for expression in expressions:
3578            dot = Dot(this=dot, expression=expression)
3579
3580        return dot
3581
3582
3583class DPipe(Binary):
3584    pass
3585
3586
3587class SafeDPipe(DPipe):
3588    pass
3589
3590
3591class EQ(Binary, Predicate):
3592    pass
3593
3594
3595class NullSafeEQ(Binary, Predicate):
3596    pass
3597
3598
3599class NullSafeNEQ(Binary, Predicate):
3600    pass
3601
3602
3603class Distance(Binary):
3604    pass
3605
3606
3607class Escape(Binary):
3608    pass
3609
3610
3611class Glob(Binary, Predicate):
3612    pass
3613
3614
3615class GT(Binary, Predicate):
3616    pass
3617
3618
3619class GTE(Binary, Predicate):
3620    pass
3621
3622
3623class ILike(Binary, Predicate):
3624    pass
3625
3626
3627class ILikeAny(Binary, Predicate):
3628    pass
3629
3630
3631class IntDiv(Binary):
3632    pass
3633
3634
3635class Is(Binary, Predicate):
3636    pass
3637
3638
3639class Kwarg(Binary):
3640    """Kwarg in special functions like func(kwarg => y)."""
3641
3642
3643class Like(Binary, Predicate):
3644    pass
3645
3646
3647class LikeAny(Binary, Predicate):
3648    pass
3649
3650
3651class LT(Binary, Predicate):
3652    pass
3653
3654
3655class LTE(Binary, Predicate):
3656    pass
3657
3658
3659class Mod(Binary):
3660    pass
3661
3662
3663class Mul(Binary):
3664    pass
3665
3666
3667class NEQ(Binary, Predicate):
3668    pass
3669
3670
3671class SimilarTo(Binary, Predicate):
3672    pass
3673
3674
3675class Slice(Binary):
3676    arg_types = {"this": False, "expression": False}
3677
3678
3679class Sub(Binary):
3680    pass
3681
3682
3683class ArrayOverlaps(Binary):
3684    pass
3685
3686
3687# Unary Expressions
3688# (NOT a)
3689class Unary(Condition):
3690    pass
3691
3692
3693class BitwiseNot(Unary):
3694    pass
3695
3696
3697class Not(Unary):
3698    pass
3699
3700
3701class Paren(Unary):
3702    arg_types = {"this": True, "with": False}
3703
3704    @property
3705    def output_name(self) -> str:
3706        return self.this.name
3707
3708
3709class Neg(Unary):
3710    pass
3711
3712
3713class Alias(Expression):
3714    arg_types = {"this": True, "alias": False}
3715
3716    @property
3717    def output_name(self) -> str:
3718        return self.alias
3719
3720
3721class Aliases(Expression):
3722    arg_types = {"this": True, "expressions": True}
3723
3724    @property
3725    def aliases(self):
3726        return self.expressions
3727
3728
3729class AtTimeZone(Expression):
3730    arg_types = {"this": True, "zone": True}
3731
3732
3733class Between(Predicate):
3734    arg_types = {"this": True, "low": True, "high": True}
3735
3736
3737class Bracket(Condition):
3738    arg_types = {"this": True, "expressions": True}
3739
3740
3741class SafeBracket(Bracket):
3742    """Represents array lookup where OOB index yields NULL instead of causing a failure."""
3743
3744
3745class Distinct(Expression):
3746    arg_types = {"expressions": False, "on": False}
3747
3748
3749class In(Predicate):
3750    arg_types = {
3751        "this": True,
3752        "expressions": False,
3753        "query": False,
3754        "unnest": False,
3755        "field": False,
3756        "is_global": False,
3757    }
3758
3759
3760class TimeUnit(Expression):
3761    """Automatically converts unit arg into a var."""
3762
3763    arg_types = {"unit": False}
3764
3765    def __init__(self, **args):
3766        unit = args.get("unit")
3767        if isinstance(unit, (Column, Literal)):
3768            args["unit"] = Var(this=unit.name)
3769        elif isinstance(unit, Week):
3770            unit.set("this", Var(this=unit.this.name))
3771
3772        super().__init__(**args)
3773
3774
3775class Interval(TimeUnit):
3776    arg_types = {"this": False, "unit": False}
3777
3778    @property
3779    def unit(self) -> t.Optional[Var]:
3780        return self.args.get("unit")
3781
3782
3783class IgnoreNulls(Expression):
3784    pass
3785
3786
3787class RespectNulls(Expression):
3788    pass
3789
3790
3791# Functions
3792class Func(Condition):
3793    """
3794    The base class for all function expressions.
3795
3796    Attributes:
3797        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3798            treated as a variable length argument and the argument's value will be stored as a list.
3799        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3800            for this function expression. These values are used to map this node to a name during parsing
3801            as well as to provide the function's name during SQL string generation. By default the SQL
3802            name is set to the expression's class name transformed to snake case.
3803    """
3804
3805    is_var_len_args = False
3806
3807    @classmethod
3808    def from_arg_list(cls, args):
3809        if cls.is_var_len_args:
3810            all_arg_keys = list(cls.arg_types)
3811            # If this function supports variable length argument treat the last argument as such.
3812            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3813            num_non_var = len(non_var_len_arg_keys)
3814
3815            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3816            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3817        else:
3818            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3819
3820        return cls(**args_dict)
3821
3822    @classmethod
3823    def sql_names(cls):
3824        if cls is Func:
3825            raise NotImplementedError(
3826                "SQL name is only supported by concrete function implementations"
3827            )
3828        if "_sql_names" not in cls.__dict__:
3829            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3830        return cls._sql_names
3831
3832    @classmethod
3833    def sql_name(cls):
3834        return cls.sql_names()[0]
3835
3836    @classmethod
3837    def default_parser_mappings(cls):
3838        return {name: cls.from_arg_list for name in cls.sql_names()}
3839
3840
3841class AggFunc(Func):
3842    pass
3843
3844
3845class ParameterizedAgg(AggFunc):
3846    arg_types = {"this": True, "expressions": True, "params": True}
3847
3848
3849class Abs(Func):
3850    pass
3851
3852
3853class Anonymous(Func):
3854    arg_types = {"this": True, "expressions": False}
3855    is_var_len_args = True
3856
3857
3858# https://docs.snowflake.com/en/sql-reference/functions/hll
3859# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3860class Hll(AggFunc):
3861    arg_types = {"this": True, "expressions": False}
3862    is_var_len_args = True
3863
3864
3865class ApproxDistinct(AggFunc):
3866    arg_types = {"this": True, "accuracy": False}
3867    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
3868
3869
3870class Array(Func):
3871    arg_types = {"expressions": False}
3872    is_var_len_args = True
3873
3874
3875# https://docs.snowflake.com/en/sql-reference/functions/to_char
3876class ToChar(Func):
3877    arg_types = {"this": True, "format": False}
3878
3879
3880class GenerateSeries(Func):
3881    arg_types = {"start": True, "end": True, "step": False}
3882
3883
3884class ArrayAgg(AggFunc):
3885    pass
3886
3887
3888class ArrayAll(Func):
3889    arg_types = {"this": True, "expression": True}
3890
3891
3892class ArrayAny(Func):
3893    arg_types = {"this": True, "expression": True}
3894
3895
3896class ArrayConcat(Func):
3897    arg_types = {"this": True, "expressions": False}
3898    is_var_len_args = True
3899
3900
3901class ArrayContains(Binary, Func):
3902    pass
3903
3904
3905class ArrayContained(Binary):
3906    pass
3907
3908
3909class ArrayFilter(Func):
3910    arg_types = {"this": True, "expression": True}
3911    _sql_names = ["FILTER", "ARRAY_FILTER"]
3912
3913
3914class ArrayJoin(Func):
3915    arg_types = {"this": True, "expression": True, "null": False}
3916
3917
3918class ArraySize(Func):
3919    arg_types = {"this": True, "expression": False}
3920
3921
3922class ArraySort(Func):
3923    arg_types = {"this": True, "expression": False}
3924
3925
3926class ArraySum(Func):
3927    pass
3928
3929
3930class ArrayUnionAgg(AggFunc):
3931    pass
3932
3933
3934class Avg(AggFunc):
3935    pass
3936
3937
3938class AnyValue(AggFunc):
3939    arg_types = {"this": True, "having": False, "max": False}
3940
3941
3942class Case(Func):
3943    arg_types = {"this": False, "ifs": True, "default": False}
3944
3945    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3946        instance = _maybe_copy(self, copy)
3947        instance.append(
3948            "ifs",
3949            If(
3950                this=maybe_parse(condition, copy=copy, **opts),
3951                true=maybe_parse(then, copy=copy, **opts),
3952            ),
3953        )
3954        return instance
3955
3956    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3957        instance = _maybe_copy(self, copy)
3958        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3959        return instance
3960
3961
3962class Cast(Func):
3963    arg_types = {"this": True, "to": True, "format": False}
3964
3965    @property
3966    def name(self) -> str:
3967        return self.this.name
3968
3969    @property
3970    def to(self) -> DataType:
3971        return self.args["to"]
3972
3973    @property
3974    def output_name(self) -> str:
3975        return self.name
3976
3977    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3978        return self.to.is_type(*dtypes)
3979
3980
3981class CastToStrType(Func):
3982    arg_types = {"this": True, "expression": True}
3983
3984
3985class Collate(Binary):
3986    pass
3987
3988
3989class TryCast(Cast):
3990    pass
3991
3992
3993class Ceil(Func):
3994    arg_types = {"this": True, "decimals": False}
3995    _sql_names = ["CEIL", "CEILING"]
3996
3997
3998class Coalesce(Func):
3999    arg_types = {"this": True, "expressions": False}
4000    is_var_len_args = True
4001    _sql_names = ["COALESCE", "IFNULL", "NVL"]
4002
4003
4004class Concat(Func):
4005    arg_types = {"expressions": True}
4006    is_var_len_args = True
4007
4008
4009class SafeConcat(Concat):
4010    pass
4011
4012
4013class ConcatWs(Concat):
4014    _sql_names = ["CONCAT_WS"]
4015
4016
4017class Count(AggFunc):
4018    arg_types = {"this": False, "expressions": False}
4019    is_var_len_args = True
4020
4021
4022class CountIf(AggFunc):
4023    pass
4024
4025
4026class CurrentDate(Func):
4027    arg_types = {"this": False}
4028
4029
4030class CurrentDatetime(Func):
4031    arg_types = {"this": False}
4032
4033
4034class CurrentTime(Func):
4035    arg_types = {"this": False}
4036
4037
4038class CurrentTimestamp(Func):
4039    arg_types = {"this": False}
4040
4041
4042class CurrentUser(Func):
4043    arg_types = {"this": False}
4044
4045
4046class DateAdd(Func, TimeUnit):
4047    arg_types = {"this": True, "expression": True, "unit": False}
4048
4049
4050class DateSub(Func, TimeUnit):
4051    arg_types = {"this": True, "expression": True, "unit": False}
4052
4053
4054class DateDiff(Func, TimeUnit):
4055    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4056    arg_types = {"this": True, "expression": True, "unit": False}
4057
4058
4059class DateTrunc(Func):
4060    arg_types = {"unit": True, "this": True, "zone": False}
4061
4062
4063class DatetimeAdd(Func, TimeUnit):
4064    arg_types = {"this": True, "expression": True, "unit": False}
4065
4066
4067class DatetimeSub(Func, TimeUnit):
4068    arg_types = {"this": True, "expression": True, "unit": False}
4069
4070
4071class DatetimeDiff(Func, TimeUnit):
4072    arg_types = {"this": True, "expression": True, "unit": False}
4073
4074
4075class DatetimeTrunc(Func, TimeUnit):
4076    arg_types = {"this": True, "unit": True, "zone": False}
4077
4078
4079class DayOfWeek(Func):
4080    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
4081
4082
4083class DayOfMonth(Func):
4084    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
4085
4086
4087class DayOfYear(Func):
4088    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
4089
4090
4091class WeekOfYear(Func):
4092    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
4093
4094
4095class LastDateOfMonth(Func):
4096    pass
4097
4098
4099class Extract(Func):
4100    arg_types = {"this": True, "expression": True}
4101
4102
4103class TimestampAdd(Func, TimeUnit):
4104    arg_types = {"this": True, "expression": True, "unit": False}
4105
4106
4107class TimestampSub(Func, TimeUnit):
4108    arg_types = {"this": True, "expression": True, "unit": False}
4109
4110
4111class TimestampDiff(Func, TimeUnit):
4112    arg_types = {"this": True, "expression": True, "unit": False}
4113
4114
4115class TimestampTrunc(Func, TimeUnit):
4116    arg_types = {"this": True, "unit": True, "zone": False}
4117
4118
4119class TimeAdd(Func, TimeUnit):
4120    arg_types = {"this": True, "expression": True, "unit": False}
4121
4122
4123class TimeSub(Func, TimeUnit):
4124    arg_types = {"this": True, "expression": True, "unit": False}
4125
4126
4127class TimeDiff(Func, TimeUnit):
4128    arg_types = {"this": True, "expression": True, "unit": False}
4129
4130
4131class TimeTrunc(Func, TimeUnit):
4132    arg_types = {"this": True, "unit": True, "zone": False}
4133
4134
4135class DateFromParts(Func):
4136    _sql_names = ["DATEFROMPARTS"]
4137    arg_types = {"year": True, "month": True, "day": True}
4138
4139
4140class DateStrToDate(Func):
4141    pass
4142
4143
4144class DateToDateStr(Func):
4145    pass
4146
4147
4148class DateToDi(Func):
4149    pass
4150
4151
4152# https://cloud.google.com/bigquery/docs/reference/standard-sql/date_functions#date
4153class Date(Func):
4154    arg_types = {"this": True, "zone": False}
4155
4156
4157class Day(Func):
4158    pass
4159
4160
4161class Decode(Func):
4162    arg_types = {"this": True, "charset": True, "replace": False}
4163
4164
4165class DiToDate(Func):
4166    pass
4167
4168
4169class Encode(Func):
4170    arg_types = {"this": True, "charset": True}
4171
4172
4173class Exp(Func):
4174    pass
4175
4176
4177class Explode(Func):
4178    pass
4179
4180
4181class Floor(Func):
4182    arg_types = {"this": True, "decimals": False}
4183
4184
4185class FromBase64(Func):
4186    pass
4187
4188
4189class ToBase64(Func):
4190    pass
4191
4192
4193class Greatest(Func):
4194    arg_types = {"this": True, "expressions": False}
4195    is_var_len_args = True
4196
4197
4198class GroupConcat(Func):
4199    arg_types = {"this": True, "separator": False}
4200
4201
4202class Hex(Func):
4203    pass
4204
4205
4206class If(Func):
4207    arg_types = {"this": True, "true": True, "false": False}
4208
4209
4210class Initcap(Func):
4211    arg_types = {"this": True, "expression": False}
4212
4213
4214class JSONKeyValue(Expression):
4215    arg_types = {"this": True, "expression": True}
4216
4217
4218class JSONObject(Func):
4219    arg_types = {
4220        "expressions": False,
4221        "null_handling": False,
4222        "unique_keys": False,
4223        "return_type": False,
4224        "format_json": False,
4225        "encoding": False,
4226    }
4227
4228
4229class OpenJSONColumnDef(Expression):
4230    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
4231
4232
4233class OpenJSON(Func):
4234    arg_types = {"this": True, "path": False, "expressions": False}
4235
4236
4237class JSONBContains(Binary):
4238    _sql_names = ["JSONB_CONTAINS"]
4239
4240
4241class JSONExtract(Binary, Func):
4242    _sql_names = ["JSON_EXTRACT"]
4243
4244
4245class JSONExtractScalar(JSONExtract):
4246    _sql_names = ["JSON_EXTRACT_SCALAR"]
4247
4248
4249class JSONBExtract(JSONExtract):
4250    _sql_names = ["JSONB_EXTRACT"]
4251
4252
4253class JSONBExtractScalar(JSONExtract):
4254    _sql_names = ["JSONB_EXTRACT_SCALAR"]
4255
4256
4257class JSONFormat(Func):
4258    arg_types = {"this": False, "options": False}
4259    _sql_names = ["JSON_FORMAT"]
4260
4261
4262# https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#operator_member-of
4263class JSONArrayContains(Binary, Predicate, Func):
4264    _sql_names = ["JSON_ARRAY_CONTAINS"]
4265
4266
4267class Least(Func):
4268    arg_types = {"this": True, "expressions": False}
4269    is_var_len_args = True
4270
4271
4272class Left(Func):
4273    arg_types = {"this": True, "expression": True}
4274
4275
4276class Right(Func):
4277    arg_types = {"this": True, "expression": True}
4278
4279
4280class Length(Func):
4281    _sql_names = ["LENGTH", "LEN"]
4282
4283
4284class Levenshtein(Func):
4285    arg_types = {
4286        "this": True,
4287        "expression": False,
4288        "ins_cost": False,
4289        "del_cost": False,
4290        "sub_cost": False,
4291    }
4292
4293
4294class Ln(Func):
4295    pass
4296
4297
4298class Log(Func):
4299    arg_types = {"this": True, "expression": False}
4300
4301
4302class Log2(Func):
4303    pass
4304
4305
4306class Log10(Func):
4307    pass
4308
4309
4310class LogicalOr(AggFunc):
4311    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
4312
4313
4314class LogicalAnd(AggFunc):
4315    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
4316
4317
4318class Lower(Func):
4319    _sql_names = ["LOWER", "LCASE"]
4320
4321
4322class Map(Func):
4323    arg_types = {"keys": False, "values": False}
4324
4325
4326class MapFromEntries(Func):
4327    pass
4328
4329
4330class StarMap(Func):
4331    pass
4332
4333
4334class VarMap(Func):
4335    arg_types = {"keys": True, "values": True}
4336    is_var_len_args = True
4337
4338    @property
4339    def keys(self) -> t.List[Expression]:
4340        return self.args["keys"].expressions
4341
4342    @property
4343    def values(self) -> t.List[Expression]:
4344        return self.args["values"].expressions
4345
4346
4347# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
4348class MatchAgainst(Func):
4349    arg_types = {"this": True, "expressions": True, "modifier": False}
4350
4351
4352class Max(AggFunc):
4353    arg_types = {"this": True, "expressions": False}
4354    is_var_len_args = True
4355
4356
4357class MD5(Func):
4358    _sql_names = ["MD5"]
4359
4360
4361# Represents the variant of the MD5 function that returns a binary value
4362class MD5Digest(Func):
4363    _sql_names = ["MD5_DIGEST"]
4364
4365
4366class Min(AggFunc):
4367    arg_types = {"this": True, "expressions": False}
4368    is_var_len_args = True
4369
4370
4371class Month(Func):
4372    pass
4373
4374
4375class Nvl2(Func):
4376    arg_types = {"this": True, "true": True, "false": False}
4377
4378
4379class Posexplode(Func):
4380    pass
4381
4382
4383class Pow(Binary, Func):
4384    _sql_names = ["POWER", "POW"]
4385
4386
4387class PercentileCont(AggFunc):
4388    arg_types = {"this": True, "expression": False}
4389
4390
4391class PercentileDisc(AggFunc):
4392    arg_types = {"this": True, "expression": False}
4393
4394
4395class Quantile(AggFunc):
4396    arg_types = {"this": True, "quantile": True}
4397
4398
4399class ApproxQuantile(Quantile):
4400    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
4401
4402
4403class RangeN(Func):
4404    arg_types = {"this": True, "expressions": True, "each": False}
4405
4406
4407class ReadCSV(Func):
4408    _sql_names = ["READ_CSV"]
4409    is_var_len_args = True
4410    arg_types = {"this": True, "expressions": False}
4411
4412
4413class Reduce(Func):
4414    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
4415
4416
4417class RegexpExtract(Func):
4418    arg_types = {
4419        "this": True,
4420        "expression": True,
4421        "position": False,
4422        "occurrence": False,
4423        "parameters": False,
4424        "group": False,
4425    }
4426
4427
4428class RegexpLike(Func):
4429    arg_types = {"this": True, "expression": True, "flag": False}
4430
4431
4432class RegexpILike(Func):
4433    arg_types = {"this": True, "expression": True, "flag": False}
4434
4435
4436# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
4437# limit is the number of times a pattern is applied
4438class RegexpSplit(Func):
4439    arg_types = {"this": True, "expression": True, "limit": False}
4440
4441
4442class Repeat(Func):
4443    arg_types = {"this": True, "times": True}
4444
4445
4446class Round(Func):
4447    arg_types = {"this": True, "decimals": False}
4448
4449
4450class RowNumber(Func):
4451    arg_types: t.Dict[str, t.Any] = {}
4452
4453
4454class SafeDivide(Func):
4455    arg_types = {"this": True, "expression": True}
4456
4457
4458class SetAgg(AggFunc):
4459    pass
4460
4461
4462class SHA(Func):
4463    _sql_names = ["SHA", "SHA1"]
4464
4465
4466class SHA2(Func):
4467    _sql_names = ["SHA2"]
4468    arg_types = {"this": True, "length": False}
4469
4470
4471class SortArray(Func):
4472    arg_types = {"this": True, "asc": False}
4473
4474
4475class Split(Func):
4476    arg_types = {"this": True, "expression": True, "limit": False}
4477
4478
4479# Start may be omitted in the case of postgres
4480# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
4481class Substring(Func):
4482    arg_types = {"this": True, "start": False, "length": False}
4483
4484
4485class StandardHash(Func):
4486    arg_types = {"this": True, "expression": False}
4487
4488
4489class StrPosition(Func):
4490    arg_types = {
4491        "this": True,
4492        "substr": True,
4493        "position": False,
4494        "instance": False,
4495    }
4496
4497
4498class StrToDate(Func):
4499    arg_types = {"this": True, "format": True}
4500
4501
4502class StrToTime(Func):
4503    arg_types = {"this": True, "format": True, "zone": False}
4504
4505
4506# Spark allows unix_timestamp()
4507# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
4508class StrToUnix(Func):
4509    arg_types = {"this": False, "format": False}
4510
4511
4512class NumberToStr(Func):
4513    arg_types = {"this": True, "format": True}
4514
4515
4516class FromBase(Func):
4517    arg_types = {"this": True, "expression": True}
4518
4519
4520class Struct(Func):
4521    arg_types = {"expressions": True}
4522    is_var_len_args = True
4523
4524
4525class StructExtract(Func):
4526    arg_types = {"this": True, "expression": True}
4527
4528
4529class Sum(AggFunc):
4530    pass
4531
4532
4533class Sqrt(Func):
4534    pass
4535
4536
4537class Stddev(AggFunc):
4538    pass
4539
4540
4541class StddevPop(AggFunc):
4542    pass
4543
4544
4545class StddevSamp(AggFunc):
4546    pass
4547
4548
4549class TimeToStr(Func):
4550    arg_types = {"this": True, "format": True}
4551
4552
4553class TimeToTimeStr(Func):
4554    pass
4555
4556
4557class TimeToUnix(Func):
4558    pass
4559
4560
4561class TimeStrToDate(Func):
4562    pass
4563
4564
4565class TimeStrToTime(Func):
4566    pass
4567
4568
4569class TimeStrToUnix(Func):
4570    pass
4571
4572
4573class Trim(Func):
4574    arg_types = {
4575        "this": True,
4576        "expression": False,
4577        "position": False,
4578        "collation": False,
4579    }
4580
4581
4582class TsOrDsAdd(Func, TimeUnit):
4583    arg_types = {"this": True, "expression": True, "unit": False}
4584
4585
4586class TsOrDsToDateStr(Func):
4587    pass
4588
4589
4590class TsOrDsToDate(Func):
4591    arg_types = {"this": True, "format": False}
4592
4593
4594class TsOrDiToDi(Func):
4595    pass
4596
4597
4598class Unhex(Func):
4599    pass
4600
4601
4602class UnixToStr(Func):
4603    arg_types = {"this": True, "format": False}
4604
4605
4606# https://prestodb.io/docs/current/functions/datetime.html
4607# presto has weird zone/hours/minutes
4608class UnixToTime(Func):
4609    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4610
4611    SECONDS = Literal.string("seconds")
4612    MILLIS = Literal.string("millis")
4613    MICROS = Literal.string("micros")
4614
4615
4616class UnixToTimeStr(Func):
4617    pass
4618
4619
4620class Upper(Func):
4621    _sql_names = ["UPPER", "UCASE"]
4622
4623
4624class Variance(AggFunc):
4625    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
4626
4627
4628class VariancePop(AggFunc):
4629    _sql_names = ["VARIANCE_POP", "VAR_POP"]
4630
4631
4632class Week(Func):
4633    arg_types = {"this": True, "mode": False}
4634
4635
4636class XMLTable(Func):
4637    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4638
4639
4640class Year(Func):
4641    pass
4642
4643
4644class Use(Expression):
4645    arg_types = {"this": True, "kind": False}
4646
4647
4648class Merge(Expression):
4649    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4650
4651
4652class When(Func):
4653    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4654
4655
4656# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html
4657# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16
4658class NextValueFor(Func):
4659    arg_types = {"this": True, "order": False}
4660
4661
4662def _norm_arg(arg):
4663    return arg.lower() if type(arg) is str else arg
4664
4665
4666ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4667
4668
4669# Helpers
4670@t.overload
4671def maybe_parse(
4672    sql_or_expression: ExpOrStr,
4673    *,
4674    into: t.Type[E],
4675    dialect: DialectType = None,
4676    prefix: t.Optional[str] = None,
4677    copy: bool = False,
4678    **opts,
4679) -> E:
4680    ...
4681
4682
4683@t.overload
4684def maybe_parse(
4685    sql_or_expression: str | E,
4686    *,
4687    into: t.Optional[IntoType] = None,
4688    dialect: DialectType = None,
4689    prefix: t.Optional[str] = None,
4690    copy: bool = False,
4691    **opts,
4692) -> E:
4693    ...
4694
4695
4696def maybe_parse(
4697    sql_or_expression: ExpOrStr,
4698    *,
4699    into: t.Optional[IntoType] = None,
4700    dialect: DialectType = None,
4701    prefix: t.Optional[str] = None,
4702    copy: bool = False,
4703    **opts,
4704) -> Expression:
4705    """Gracefully handle a possible string or expression.
4706
4707    Example:
4708        >>> maybe_parse("1")
4709        (LITERAL this: 1, is_string: False)
4710        >>> maybe_parse(to_identifier("x"))
4711        (IDENTIFIER this: x, quoted: False)
4712
4713    Args:
4714        sql_or_expression: the SQL code string or an expression
4715        into: the SQLGlot Expression to parse into
4716        dialect: the dialect used to parse the input expressions (in the case that an
4717            input expression is a SQL string).
4718        prefix: a string to prefix the sql with before it gets parsed
4719            (automatically includes a space)
4720        copy: whether or not to copy the expression.
4721        **opts: other options to use to parse the input expressions (again, in the case
4722            that an input expression is a SQL string).
4723
4724    Returns:
4725        Expression: the parsed or given expression.
4726    """
4727    if isinstance(sql_or_expression, Expression):
4728        if copy:
4729            return sql_or_expression.copy()
4730        return sql_or_expression
4731
4732    if sql_or_expression is None:
4733        raise ParseError(f"SQL cannot be None")
4734
4735    import sqlglot
4736
4737    sql = str(sql_or_expression)
4738    if prefix:
4739        sql = f"{prefix} {sql}"
4740
4741    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4742
4743
4744def _maybe_copy(instance: E, copy: bool = True) -> E:
4745    return instance.copy() if copy else instance
4746
4747
4748def _is_wrong_expression(expression, into):
4749    return isinstance(expression, Expression) and not isinstance(expression, into)
4750
4751
4752def _apply_builder(
4753    expression,
4754    instance,
4755    arg,
4756    copy=True,
4757    prefix=None,
4758    into=None,
4759    dialect=None,
4760    **opts,
4761):
4762    if _is_wrong_expression(expression, into):
4763        expression = into(this=expression)
4764    instance = _maybe_copy(instance, copy)
4765    expression = maybe_parse(
4766        sql_or_expression=expression,
4767        prefix=prefix,
4768        into=into,
4769        dialect=dialect,
4770        **opts,
4771    )
4772    instance.set(arg, expression)
4773    return instance
4774
4775
4776def _apply_child_list_builder(
4777    *expressions,
4778    instance,
4779    arg,
4780    append=True,
4781    copy=True,
4782    prefix=None,
4783    into=None,
4784    dialect=None,
4785    properties=None,
4786    **opts,
4787):
4788    instance = _maybe_copy(instance, copy)
4789    parsed = []
4790    for expression in expressions:
4791        if expression is not None:
4792            if _is_wrong_expression(expression, into):
4793                expression = into(expressions=[expression])
4794
4795            expression = maybe_parse(
4796                expression,
4797                into=into,
4798                dialect=dialect,
4799                prefix=prefix,
4800                **opts,
4801            )
4802            parsed.extend(expression.expressions)
4803
4804    existing = instance.args.get(arg)
4805    if append and existing:
4806        parsed = existing.expressions + parsed
4807
4808    child = into(expressions=parsed)
4809    for k, v in (properties or {}).items():
4810        child.set(k, v)
4811    instance.set(arg, child)
4812
4813    return instance
4814
4815
4816def _apply_list_builder(
4817    *expressions,
4818    instance,
4819    arg,
4820    append=True,
4821    copy=True,
4822    prefix=None,
4823    into=None,
4824    dialect=None,
4825    **opts,
4826):
4827    inst = _maybe_copy(instance, copy)
4828
4829    expressions = [
4830        maybe_parse(
4831            sql_or_expression=expression,
4832            into=into,
4833            prefix=prefix,
4834            dialect=dialect,
4835            **opts,
4836        )
4837        for expression in expressions
4838        if expression is not None
4839    ]
4840
4841    existing_expressions = inst.args.get(arg)
4842    if append and existing_expressions:
4843        expressions = existing_expressions + expressions
4844
4845    inst.set(arg, expressions)
4846    return inst
4847
4848
4849def _apply_conjunction_builder(
4850    *expressions,
4851    instance,
4852    arg,
4853    into=None,
4854    append=True,
4855    copy=True,
4856    dialect=None,
4857    **opts,
4858):
4859    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4860    if not expressions:
4861        return instance
4862
4863    inst = _maybe_copy(instance, copy)
4864
4865    existing = inst.args.get(arg)
4866    if append and existing is not None:
4867        expressions = [existing.this if into else existing] + list(expressions)
4868
4869    node = and_(*expressions, dialect=dialect, copy=copy, **opts)
4870
4871    inst.set(arg, into(this=node) if into else node)
4872    return inst
4873
4874
4875def _apply_cte_builder(
4876    instance: E,
4877    alias: ExpOrStr,
4878    as_: ExpOrStr,
4879    recursive: t.Optional[bool] = None,
4880    append: bool = True,
4881    dialect: DialectType = None,
4882    copy: bool = True,
4883    **opts,
4884) -> E:
4885    alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts)
4886    as_expression = maybe_parse(as_, dialect=dialect, **opts)
4887    cte = CTE(this=as_expression, alias=alias_expression)
4888    return _apply_child_list_builder(
4889        cte,
4890        instance=instance,
4891        arg="with",
4892        append=append,
4893        copy=copy,
4894        into=With,
4895        properties={"recursive": recursive or False},
4896    )
4897
4898
4899def _combine(
4900    expressions: t.Sequence[t.Optional[ExpOrStr]],
4901    operator: t.Type[Connector],
4902    dialect: DialectType = None,
4903    copy: bool = True,
4904    **opts,
4905) -> Expression:
4906    conditions = [
4907        condition(expression, dialect=dialect, copy=copy, **opts)
4908        for expression in expressions
4909        if expression is not None
4910    ]
4911
4912    this, *rest = conditions
4913    if rest:
4914        this = _wrap(this, Connector)
4915    for expression in rest:
4916        this = operator(this=this, expression=_wrap(expression, Connector))
4917
4918    return this
4919
4920
4921def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:
4922    return Paren(this=expression) if isinstance(expression, kind) else expression
4923
4924
4925def union(
4926    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4927) -> Union:
4928    """
4929    Initializes a syntax tree from one UNION expression.
4930
4931    Example:
4932        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4933        'SELECT * FROM foo UNION SELECT * FROM bla'
4934
4935    Args:
4936        left: the SQL code string corresponding to the left-hand side.
4937            If an `Expression` instance is passed, it will be used as-is.
4938        right: the SQL code string corresponding to the right-hand side.
4939            If an `Expression` instance is passed, it will be used as-is.
4940        distinct: set the DISTINCT flag if and only if this is true.
4941        dialect: the dialect used to parse the input expression.
4942        opts: other options to use to parse the input expressions.
4943
4944    Returns:
4945        The new Union instance.
4946    """
4947    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4948    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4949
4950    return Union(this=left, expression=right, distinct=distinct)
4951
4952
4953def intersect(
4954    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4955) -> Intersect:
4956    """
4957    Initializes a syntax tree from one INTERSECT expression.
4958
4959    Example:
4960        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4961        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4962
4963    Args:
4964        left: the SQL code string corresponding to the left-hand side.
4965            If an `Expression` instance is passed, it will be used as-is.
4966        right: the SQL code string corresponding to the right-hand side.
4967            If an `Expression` instance is passed, it will be used as-is.
4968        distinct: set the DISTINCT flag if and only if this is true.
4969        dialect: the dialect used to parse the input expression.
4970        opts: other options to use to parse the input expressions.
4971
4972    Returns:
4973        The new Intersect instance.
4974    """
4975    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4976    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4977
4978    return Intersect(this=left, expression=right, distinct=distinct)
4979
4980
4981def except_(
4982    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4983) -> Except:
4984    """
4985    Initializes a syntax tree from one EXCEPT expression.
4986
4987    Example:
4988        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4989        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4990
4991    Args:
4992        left: the SQL code string corresponding to the left-hand side.
4993            If an `Expression` instance is passed, it will be used as-is.
4994        right: the SQL code string corresponding to the right-hand side.
4995            If an `Expression` instance is passed, it will be used as-is.
4996        distinct: set the DISTINCT flag if and only if this is true.
4997        dialect: the dialect used to parse the input expression.
4998        opts: other options to use to parse the input expressions.
4999
5000    Returns:
5001        The new Except instance.
5002    """
5003    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5004    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5005
5006    return Except(this=left, expression=right, distinct=distinct)
5007
5008
5009def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5010    """
5011    Initializes a syntax tree from one or multiple SELECT expressions.
5012
5013    Example:
5014        >>> select("col1", "col2").from_("tbl").sql()
5015        'SELECT col1, col2 FROM tbl'
5016
5017    Args:
5018        *expressions: the SQL code string to parse as the expressions of a
5019            SELECT statement. If an Expression instance is passed, this is used as-is.
5020        dialect: the dialect used to parse the input expressions (in the case that an
5021            input expression is a SQL string).
5022        **opts: other options to use to parse the input expressions (again, in the case
5023            that an input expression is a SQL string).
5024
5025    Returns:
5026        Select: the syntax tree for the SELECT statement.
5027    """
5028    return Select().select(*expressions, dialect=dialect, **opts)
5029
5030
5031def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5032    """
5033    Initializes a syntax tree from a FROM expression.
5034
5035    Example:
5036        >>> from_("tbl").select("col1", "col2").sql()
5037        'SELECT col1, col2 FROM tbl'
5038
5039    Args:
5040        *expression: the SQL code string to parse as the FROM expressions of a
5041            SELECT statement. If an Expression instance is passed, this is used as-is.
5042        dialect: the dialect used to parse the input expression (in the case that the
5043            input expression is a SQL string).
5044        **opts: other options to use to parse the input expressions (again, in the case
5045            that the input expression is a SQL string).
5046
5047    Returns:
5048        Select: the syntax tree for the SELECT statement.
5049    """
5050    return Select().from_(expression, dialect=dialect, **opts)
5051
5052
5053def update(
5054    table: str | Table,
5055    properties: dict,
5056    where: t.Optional[ExpOrStr] = None,
5057    from_: t.Optional[ExpOrStr] = None,
5058    dialect: DialectType = None,
5059    **opts,
5060) -> Update:
5061    """
5062    Creates an update statement.
5063
5064    Example:
5065        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5066        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5067
5068    Args:
5069        *properties: dictionary of properties to set which are
5070            auto converted to sql objects eg None -> NULL
5071        where: sql conditional parsed into a WHERE statement
5072        from_: sql statement parsed into a FROM statement
5073        dialect: the dialect used to parse the input expressions.
5074        **opts: other options to use to parse the input expressions.
5075
5076    Returns:
5077        Update: the syntax tree for the UPDATE statement.
5078    """
5079    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5080    update_expr.set(
5081        "expressions",
5082        [
5083            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5084            for k, v in properties.items()
5085        ],
5086    )
5087    if from_:
5088        update_expr.set(
5089            "from",
5090            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5091        )
5092    if isinstance(where, Condition):
5093        where = Where(this=where)
5094    if where:
5095        update_expr.set(
5096            "where",
5097            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5098        )
5099    return update_expr
5100
5101
5102def delete(
5103    table: ExpOrStr,
5104    where: t.Optional[ExpOrStr] = None,
5105    returning: t.Optional[ExpOrStr] = None,
5106    dialect: DialectType = None,
5107    **opts,
5108) -> Delete:
5109    """
5110    Builds a delete statement.
5111
5112    Example:
5113        >>> delete("my_table", where="id > 1").sql()
5114        'DELETE FROM my_table WHERE id > 1'
5115
5116    Args:
5117        where: sql conditional parsed into a WHERE statement
5118        returning: sql conditional parsed into a RETURNING statement
5119        dialect: the dialect used to parse the input expressions.
5120        **opts: other options to use to parse the input expressions.
5121
5122    Returns:
5123        Delete: the syntax tree for the DELETE statement.
5124    """
5125    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5126    if where:
5127        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5128    if returning:
5129        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5130    return delete_expr
5131
5132
5133def insert(
5134    expression: ExpOrStr,
5135    into: ExpOrStr,
5136    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5137    overwrite: t.Optional[bool] = None,
5138    dialect: DialectType = None,
5139    copy: bool = True,
5140    **opts,
5141) -> Insert:
5142    """
5143    Builds an INSERT statement.
5144
5145    Example:
5146        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5147        'INSERT INTO tbl VALUES (1, 2, 3)'
5148
5149    Args:
5150        expression: the sql string or expression of the INSERT statement
5151        into: the tbl to insert data to.
5152        columns: optionally the table's column names.
5153        overwrite: whether to INSERT OVERWRITE or not.
5154        dialect: the dialect used to parse the input expressions.
5155        copy: whether or not to copy the expression.
5156        **opts: other options to use to parse the input expressions.
5157
5158    Returns:
5159        Insert: the syntax tree for the INSERT statement.
5160    """
5161    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5162    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5163
5164    if columns:
5165        this = _apply_list_builder(
5166            *columns,
5167            instance=Schema(this=this),
5168            arg="expressions",
5169            into=Identifier,
5170            copy=False,
5171            dialect=dialect,
5172            **opts,
5173        )
5174
5175    return Insert(this=this, expression=expr, overwrite=overwrite)
5176
5177
5178def condition(
5179    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5180) -> Condition:
5181    """
5182    Initialize a logical condition expression.
5183
5184    Example:
5185        >>> condition("x=1").sql()
5186        'x = 1'
5187
5188        This is helpful for composing larger logical syntax trees:
5189        >>> where = condition("x=1")
5190        >>> where = where.and_("y=1")
5191        >>> Select().from_("tbl").select("*").where(where).sql()
5192        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5193
5194    Args:
5195        *expression: the SQL code string to parse.
5196            If an Expression instance is passed, this is used as-is.
5197        dialect: the dialect used to parse the input expression (in the case that the
5198            input expression is a SQL string).
5199        copy: Whether or not to copy `expression` (only applies to expressions).
5200        **opts: other options to use to parse the input expressions (again, in the case
5201            that the input expression is a SQL string).
5202
5203    Returns:
5204        The new Condition instance
5205    """
5206    return maybe_parse(
5207        expression,
5208        into=Condition,
5209        dialect=dialect,
5210        copy=copy,
5211        **opts,
5212    )
5213
5214
5215def and_(
5216    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5217) -> Condition:
5218    """
5219    Combine multiple conditions with an AND logical operator.
5220
5221    Example:
5222        >>> and_("x=1", and_("y=1", "z=1")).sql()
5223        'x = 1 AND (y = 1 AND z = 1)'
5224
5225    Args:
5226        *expressions: the SQL code strings to parse.
5227            If an Expression instance is passed, this is used as-is.
5228        dialect: the dialect used to parse the input expression.
5229        copy: whether or not to copy `expressions` (only applies to Expressions).
5230        **opts: other options to use to parse the input expressions.
5231
5232    Returns:
5233        And: the new condition
5234    """
5235    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))
5236
5237
5238def or_(
5239    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5240) -> Condition:
5241    """
5242    Combine multiple conditions with an OR logical operator.
5243
5244    Example:
5245        >>> or_("x=1", or_("y=1", "z=1")).sql()
5246        'x = 1 OR (y = 1 OR z = 1)'
5247
5248    Args:
5249        *expressions: the SQL code strings to parse.
5250            If an Expression instance is passed, this is used as-is.
5251        dialect: the dialect used to parse the input expression.
5252        copy: whether or not to copy `expressions` (only applies to Expressions).
5253        **opts: other options to use to parse the input expressions.
5254
5255    Returns:
5256        Or: the new condition
5257    """
5258    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))
5259
5260
5261def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5262    """
5263    Wrap a condition with a NOT operator.
5264
5265    Example:
5266        >>> not_("this_suit='black'").sql()
5267        "NOT this_suit = 'black'"
5268
5269    Args:
5270        expression: the SQL code string to parse.
5271            If an Expression instance is passed, this is used as-is.
5272        dialect: the dialect used to parse the input expression.
5273        copy: whether to copy the expression or not.
5274        **opts: other options to use to parse the input expressions.
5275
5276    Returns:
5277        The new condition.
5278    """
5279    this = condition(
5280        expression,
5281        dialect=dialect,
5282        copy=copy,
5283        **opts,
5284    )
5285    return Not(this=_wrap(this, Connector))
5286
5287
5288def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5289    """
5290    Wrap an expression in parentheses.
5291
5292    Example:
5293        >>> paren("5 + 3").sql()
5294        '(5 + 3)'
5295
5296    Args:
5297        expression: the SQL code string to parse.
5298            If an Expression instance is passed, this is used as-is.
5299        copy: whether to copy the expression or not.
5300
5301    Returns:
5302        The wrapped expression.
5303    """
5304    return Paren(this=maybe_parse(expression, copy=copy))
5305
5306
5307SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
5308
5309
5310@t.overload
5311def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None:
5312    ...
5313
5314
5315@t.overload
5316def to_identifier(
5317    name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True
5318) -> Identifier:
5319    ...
5320
5321
5322def to_identifier(name, quoted=None, copy=True):
5323    """Builds an identifier.
5324
5325    Args:
5326        name: The name to turn into an identifier.
5327        quoted: Whether or not force quote the identifier.
5328        copy: Whether or not to copy a passed in Identefier node.
5329
5330    Returns:
5331        The identifier ast node.
5332    """
5333
5334    if name is None:
5335        return None
5336
5337    if isinstance(name, Identifier):
5338        identifier = _maybe_copy(name, copy)
5339    elif isinstance(name, str):
5340        identifier = Identifier(
5341            this=name,
5342            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5343        )
5344    else:
5345        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5346    return identifier
5347
5348
5349INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
5350
5351
5352def to_interval(interval: str | Literal) -> Interval:
5353    """Builds an interval expression from a string like '1 day' or '5 months'."""
5354    if isinstance(interval, Literal):
5355        if not interval.is_string:
5356            raise ValueError("Invalid interval string.")
5357
5358        interval = interval.this
5359
5360    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5361
5362    if not interval_parts:
5363        raise ValueError("Invalid interval string.")
5364
5365    return Interval(
5366        this=Literal.string(interval_parts.group(1)),
5367        unit=Var(this=interval_parts.group(2)),
5368    )
5369
5370
5371@t.overload
5372def to_table(sql_path: str | Table, **kwargs) -> Table:
5373    ...
5374
5375
5376@t.overload
5377def to_table(sql_path: None, **kwargs) -> None:
5378    ...
5379
5380
5381def to_table(
5382    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5383) -> t.Optional[Table]:
5384    """
5385    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5386    If a table is passed in then that table is returned.
5387
5388    Args:
5389        sql_path: a `[catalog].[schema].[table]` string.
5390        dialect: the source dialect according to which the table name will be parsed.
5391        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5392
5393    Returns:
5394        A table expression.
5395    """
5396    if sql_path is None or isinstance(sql_path, Table):
5397        return sql_path
5398    if not isinstance(sql_path, str):
5399        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5400
5401    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5402    if table:
5403        for k, v in kwargs.items():
5404            table.set(k, v)
5405
5406    return table
5407
5408
5409def to_column(sql_path: str | Column, **kwargs) -> Column:
5410    """
5411    Create a column from a `[table].[column]` sql path. Schema is optional.
5412
5413    If a column is passed in then that column is returned.
5414
5415    Args:
5416        sql_path: `[table].[column]` string
5417    Returns:
5418        Table: A column expression
5419    """
5420    if sql_path is None or isinstance(sql_path, Column):
5421        return sql_path
5422    if not isinstance(sql_path, str):
5423        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5424    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
5425
5426
5427def alias_(
5428    expression: ExpOrStr,
5429    alias: str | Identifier,
5430    table: bool | t.Sequence[str | Identifier] = False,
5431    quoted: t.Optional[bool] = None,
5432    dialect: DialectType = None,
5433    copy: bool = True,
5434    **opts,
5435):
5436    """Create an Alias expression.
5437
5438    Example:
5439        >>> alias_('foo', 'bar').sql()
5440        'foo AS bar'
5441
5442        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5443        '(SELECT 1, 2) AS bar(a, b)'
5444
5445    Args:
5446        expression: the SQL code strings to parse.
5447            If an Expression instance is passed, this is used as-is.
5448        alias: the alias name to use. If the name has
5449            special characters it is quoted.
5450        table: Whether or not to create a table alias, can also be a list of columns.
5451        quoted: whether or not to quote the alias
5452        dialect: the dialect used to parse the input expression.
5453        copy: Whether or not to copy the expression.
5454        **opts: other options to use to parse the input expressions.
5455
5456    Returns:
5457        Alias: the aliased expression
5458    """
5459    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5460    alias = to_identifier(alias, quoted=quoted)
5461
5462    if table:
5463        table_alias = TableAlias(this=alias)
5464        exp.set("alias", table_alias)
5465
5466        if not isinstance(table, bool):
5467            for column in table:
5468                table_alias.append("columns", to_identifier(column, quoted=quoted))
5469
5470        return exp
5471
5472    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5473    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5474    # for the complete Window expression.
5475    #
5476    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5477
5478    if "alias" in exp.arg_types and not isinstance(exp, Window):
5479        exp.set("alias", alias)
5480        return exp
5481    return Alias(this=exp, alias=alias)
5482
5483
5484def subquery(
5485    expression: ExpOrStr,
5486    alias: t.Optional[Identifier | str] = None,
5487    dialect: DialectType = None,
5488    **opts,
5489) -> Select:
5490    """
5491    Build a subquery expression.
5492
5493    Example:
5494        >>> subquery('select x from tbl', 'bar').select('x').sql()
5495        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5496
5497    Args:
5498        expression: the SQL code strings to parse.
5499            If an Expression instance is passed, this is used as-is.
5500        alias: the alias name to use.
5501        dialect: the dialect used to parse the input expression.
5502        **opts: other options to use to parse the input expressions.
5503
5504    Returns:
5505        A new Select instance with the subquery expression included.
5506    """
5507
5508    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5509    return Select().from_(expression, dialect=dialect, **opts)
5510
5511
5512def column(
5513    col: str | Identifier,
5514    table: t.Optional[str | Identifier] = None,
5515    db: t.Optional[str | Identifier] = None,
5516    catalog: t.Optional[str | Identifier] = None,
5517    quoted: t.Optional[bool] = None,
5518) -> Column:
5519    """
5520    Build a Column.
5521
5522    Args:
5523        col: Column name.
5524        table: Table name.
5525        db: Database name.
5526        catalog: Catalog name.
5527        quoted: Whether to force quotes on the column's identifiers.
5528
5529    Returns:
5530        The new Column instance.
5531    """
5532    return Column(
5533        this=to_identifier(col, quoted=quoted),
5534        table=to_identifier(table, quoted=quoted),
5535        db=to_identifier(db, quoted=quoted),
5536        catalog=to_identifier(catalog, quoted=quoted),
5537    )
5538
5539
5540def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5541    """Cast an expression to a data type.
5542
5543    Example:
5544        >>> cast('x + 1', 'int').sql()
5545        'CAST(x + 1 AS INT)'
5546
5547    Args:
5548        expression: The expression to cast.
5549        to: The datatype to cast to.
5550
5551    Returns:
5552        The new Cast instance.
5553    """
5554    expression = maybe_parse(expression, **opts)
5555    return Cast(this=expression, to=DataType.build(to, **opts))
5556
5557
5558def table_(
5559    table: Identifier | str,
5560    db: t.Optional[Identifier | str] = None,
5561    catalog: t.Optional[Identifier | str] = None,
5562    quoted: t.Optional[bool] = None,
5563    alias: t.Optional[Identifier | str] = None,
5564) -> Table:
5565    """Build a Table.
5566
5567    Args:
5568        table: Table name.
5569        db: Database name.
5570        catalog: Catalog name.
5571        quote: Whether to force quotes on the table's identifiers.
5572        alias: Table's alias.
5573
5574    Returns:
5575        The new Table instance.
5576    """
5577    return Table(
5578        this=to_identifier(table, quoted=quoted),
5579        db=to_identifier(db, quoted=quoted),
5580        catalog=to_identifier(catalog, quoted=quoted),
5581        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5582    )
5583
5584
5585def values(
5586    values: t.Iterable[t.Tuple[t.Any, ...]],
5587    alias: t.Optional[str] = None,
5588    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5589) -> Values:
5590    """Build VALUES statement.
5591
5592    Example:
5593        >>> values([(1, '2')]).sql()
5594        "VALUES (1, '2')"
5595
5596    Args:
5597        values: values statements that will be converted to SQL
5598        alias: optional alias
5599        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5600         If either are provided then an alias is also required.
5601
5602    Returns:
5603        Values: the Values expression object
5604    """
5605    if columns and not alias:
5606        raise ValueError("Alias is required when providing columns")
5607
5608    return Values(
5609        expressions=[convert(tup) for tup in values],
5610        alias=(
5611            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5612            if columns
5613            else (TableAlias(this=to_identifier(alias)) if alias else None)
5614        ),
5615    )
5616
5617
5618def var(name: t.Optional[ExpOrStr]) -> Var:
5619    """Build a SQL variable.
5620
5621    Example:
5622        >>> repr(var('x'))
5623        '(VAR this: x)'
5624
5625        >>> repr(var(column('x', table='y')))
5626        '(VAR this: x)'
5627
5628    Args:
5629        name: The name of the var or an expression who's name will become the var.
5630
5631    Returns:
5632        The new variable node.
5633    """
5634    if not name:
5635        raise ValueError("Cannot convert empty name into var.")
5636
5637    if isinstance(name, Expression):
5638        name = name.name
5639    return Var(this=name)
5640
5641
5642def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5643    """Build ALTER TABLE... RENAME... expression
5644
5645    Args:
5646        old_name: The old name of the table
5647        new_name: The new name of the table
5648
5649    Returns:
5650        Alter table expression
5651    """
5652    old_table = to_table(old_name)
5653    new_table = to_table(new_name)
5654    return AlterTable(
5655        this=old_table,
5656        actions=[
5657            RenameTable(this=new_table),
5658        ],
5659    )
5660
5661
5662def convert(value: t.Any, copy: bool = False) -> Expression:
5663    """Convert a python value into an expression object.
5664
5665    Raises an error if a conversion is not possible.
5666
5667    Args:
5668        value: A python object.
5669        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5670
5671    Returns:
5672        Expression: the equivalent expression object.
5673    """
5674    if isinstance(value, Expression):
5675        return _maybe_copy(value, copy)
5676    if isinstance(value, str):
5677        return Literal.string(value)
5678    if isinstance(value, bool):
5679        return Boolean(this=value)
5680    if value is None or (isinstance(value, float) and math.isnan(value)):
5681        return NULL
5682    if isinstance(value, numbers.Number):
5683        return Literal.number(value)
5684    if isinstance(value, datetime.datetime):
5685        datetime_literal = Literal.string(
5686            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5687        )
5688        return TimeStrToTime(this=datetime_literal)
5689    if isinstance(value, datetime.date):
5690        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5691        return DateStrToDate(this=date_literal)
5692    if isinstance(value, tuple):
5693        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5694    if isinstance(value, list):
5695        return Array(expressions=[convert(v, copy=copy) for v in value])
5696    if isinstance(value, dict):
5697        return Map(
5698            keys=[convert(k, copy=copy) for k in value],
5699            values=[convert(v, copy=copy) for v in value.values()],
5700        )
5701    raise ValueError(f"Cannot convert {value}")
5702
5703
5704def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5705    """
5706    Replace children of an expression with the result of a lambda fun(child) -> exp.
5707    """
5708    for k, v in expression.args.items():
5709        is_list_arg = type(v) is list
5710
5711        child_nodes = v if is_list_arg else [v]
5712        new_child_nodes = []
5713
5714        for cn in child_nodes:
5715            if isinstance(cn, Expression):
5716                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5717                    new_child_nodes.append(child_node)
5718                    child_node.parent = expression
5719                    child_node.arg_key = k
5720            else:
5721                new_child_nodes.append(cn)
5722
5723        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
5724
5725
5726def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5727    """
5728    Return all table names referenced through columns in an expression.
5729
5730    Example:
5731        >>> import sqlglot
5732        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5733        ['a', 'c']
5734
5735    Args:
5736        expression: expression to find table names.
5737        exclude: a table name to exclude
5738
5739    Returns:
5740        A list of unique names.
5741    """
5742    return {
5743        table
5744        for table in (column.table for column in expression.find_all(Column))
5745        if table and table != exclude
5746    }
5747
5748
5749def table_name(table: Table | str, dialect: DialectType = None) -> str:
5750    """Get the full name of a table as a string.
5751
5752    Args:
5753        table: Table expression node or string.
5754        dialect: The dialect to generate the table name for.
5755
5756    Examples:
5757        >>> from sqlglot import exp, parse_one
5758        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5759        'a.b.c'
5760
5761    Returns:
5762        The table name.
5763    """
5764
5765    table = maybe_parse(table, into=Table)
5766
5767    if not table:
5768        raise ValueError(f"Cannot parse {table}")
5769
5770    return ".".join(
5771        part.sql(dialect=dialect, identify=True)
5772        if not SAFE_IDENTIFIER_RE.match(part.name)
5773        else part.name
5774        for part in table.parts
5775    )
5776
5777
5778def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5779    """Replace all tables in expression according to the mapping.
5780
5781    Args:
5782        expression: expression node to be transformed and replaced.
5783        mapping: mapping of table names.
5784        copy: whether or not to copy the expression.
5785
5786    Examples:
5787        >>> from sqlglot import exp, parse_one
5788        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5789        'SELECT * FROM c'
5790
5791    Returns:
5792        The mapped expression.
5793    """
5794
5795    def _replace_tables(node: Expression) -> Expression:
5796        if isinstance(node, Table):
5797            new_name = mapping.get(table_name(node))
5798            if new_name:
5799                return to_table(
5800                    new_name,
5801                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5802                )
5803        return node
5804
5805    return expression.transform(_replace_tables, copy=copy)
5806
5807
5808def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5809    """Replace placeholders in an expression.
5810
5811    Args:
5812        expression: expression node to be transformed and replaced.
5813        args: positional names that will substitute unnamed placeholders in the given order.
5814        kwargs: keyword arguments that will substitute named placeholders.
5815
5816    Examples:
5817        >>> from sqlglot import exp, parse_one
5818        >>> replace_placeholders(
5819        ...     parse_one("select * from :tbl where ? = ?"),
5820        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5821        ... ).sql()
5822        "SELECT * FROM foo WHERE str_col = 'b'"
5823
5824    Returns:
5825        The mapped expression.
5826    """
5827
5828    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5829        if isinstance(node, Placeholder):
5830            if node.name:
5831                new_name = kwargs.get(node.name)
5832                if new_name:
5833                    return convert(new_name)
5834            else:
5835                try:
5836                    return convert(next(args))
5837                except StopIteration:
5838                    pass
5839        return node
5840
5841    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5842
5843
5844def expand(
5845    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5846) -> Expression:
5847    """Transforms an expression by expanding all referenced sources into subqueries.
5848
5849    Examples:
5850        >>> from sqlglot import parse_one
5851        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5852        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5853
5854        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5855        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5856
5857    Args:
5858        expression: The expression to expand.
5859        sources: A dictionary of name to Subqueryables.
5860        copy: Whether or not to copy the expression during transformation. Defaults to True.
5861
5862    Returns:
5863        The transformed expression.
5864    """
5865
5866    def _expand(node: Expression):
5867        if isinstance(node, Table):
5868            name = table_name(node)
5869            source = sources.get(name)
5870            if source:
5871                subquery = source.subquery(node.alias or name)
5872                subquery.comments = [f"source: {name}"]
5873                return subquery.transform(_expand, copy=False)
5874        return node
5875
5876    return expression.transform(_expand, copy=copy)
5877
5878
5879def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5880    """
5881    Returns a Func expression.
5882
5883    Examples:
5884        >>> func("abs", 5).sql()
5885        'ABS(5)'
5886
5887        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5888        'CAST(5 AS DOUBLE)'
5889
5890    Args:
5891        name: the name of the function to build.
5892        args: the args used to instantiate the function of interest.
5893        dialect: the source dialect.
5894        kwargs: the kwargs used to instantiate the function of interest.
5895
5896    Note:
5897        The arguments `args` and `kwargs` are mutually exclusive.
5898
5899    Returns:
5900        An instance of the function of interest, or an anonymous function, if `name` doesn't
5901        correspond to an existing `sqlglot.expressions.Func` class.
5902    """
5903    if args and kwargs:
5904        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5905
5906    from sqlglot.dialects.dialect import Dialect
5907
5908    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5909    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5910
5911    parser = Dialect.get_or_raise(dialect)().parser()
5912    from_args_list = parser.FUNCTIONS.get(name.upper())
5913
5914    if from_args_list:
5915        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5916    else:
5917        kwargs = kwargs or {"expressions": converted}
5918        function = Anonymous(this=name, **kwargs)
5919
5920    for error_message in function.error_messages(converted):
5921        raise ValueError(error_message)
5922
5923    return function
5924
5925
5926def true() -> Boolean:
5927    """
5928    Returns a true Boolean expression.
5929    """
5930    return Boolean(this=True)
5931
5932
5933def false() -> Boolean:
5934    """
5935    Returns a false Boolean expression.
5936    """
5937    return Boolean(this=False)
5938
5939
5940def null() -> Null:
5941    """
5942    Returns a Null expression.
5943    """
5944    return Null()
5945
5946
5947# TODO: deprecate this
5948TRUE = Boolean(this=True)
5949FALSE = Boolean(this=False)
5950NULL = 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        return [
2314            t.cast(Identifier, self.args[part])
2315            for part in ("catalog", "db", "this")
2316            if self.args.get(part)
2317        ]
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):
2321class SystemTime(Expression):
2322    arg_types = {
2323        "this": False,
2324        "expression": False,
2325        "kind": True,
2326    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2329class Union(Subqueryable):
2330    arg_types = {
2331        "with": False,
2332        "this": True,
2333        "expression": True,
2334        "distinct": False,
2335        **QUERY_MODIFIERS,
2336    }
2337
2338    def limit(
2339        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2340    ) -> Select:
2341        """
2342        Set the LIMIT expression.
2343
2344        Example:
2345            >>> select("1").union(select("1")).limit(1).sql()
2346            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2347
2348        Args:
2349            expression: the SQL code string to parse.
2350                This can also be an integer.
2351                If a `Limit` instance is passed, this is used as-is.
2352                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2353            dialect: the dialect used to parse the input expression.
2354            copy: if `False`, modify this expression instance in-place.
2355            opts: other options to use to parse the input expressions.
2356
2357        Returns:
2358            The limited subqueryable.
2359        """
2360        return (
2361            select("*")
2362            .from_(self.subquery(alias="_l_0", copy=copy))
2363            .limit(expression, dialect=dialect, copy=False, **opts)
2364        )
2365
2366    def select(
2367        self,
2368        *expressions: t.Optional[ExpOrStr],
2369        append: bool = True,
2370        dialect: DialectType = None,
2371        copy: bool = True,
2372        **opts,
2373    ) -> Union:
2374        """Append to or set the SELECT of the union recursively.
2375
2376        Example:
2377            >>> from sqlglot import parse_one
2378            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2379            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2380
2381        Args:
2382            *expressions: the SQL code strings to parse.
2383                If an `Expression` instance is passed, it will be used as-is.
2384            append: if `True`, add to any existing expressions.
2385                Otherwise, this resets the expressions.
2386            dialect: the dialect used to parse the input expressions.
2387            copy: if `False`, modify this expression instance in-place.
2388            opts: other options to use to parse the input expressions.
2389
2390        Returns:
2391            Union: the modified expression.
2392        """
2393        this = self.copy() if copy else self
2394        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2395        this.expression.unnest().select(
2396            *expressions, append=append, dialect=dialect, copy=False, **opts
2397        )
2398        return this
2399
2400    @property
2401    def named_selects(self) -> t.List[str]:
2402        return self.this.unnest().named_selects
2403
2404    @property
2405    def is_star(self) -> bool:
2406        return self.this.is_star or self.expression.is_star
2407
2408    @property
2409    def selects(self) -> t.List[Expression]:
2410        return self.this.unnest().selects
2411
2412    @property
2413    def left(self):
2414        return self.this
2415
2416    @property
2417    def right(self):
2418        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:
2338    def limit(
2339        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2340    ) -> Select:
2341        """
2342        Set the LIMIT expression.
2343
2344        Example:
2345            >>> select("1").union(select("1")).limit(1).sql()
2346            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2347
2348        Args:
2349            expression: the SQL code string to parse.
2350                This can also be an integer.
2351                If a `Limit` instance is passed, this is used as-is.
2352                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2353            dialect: the dialect used to parse the input expression.
2354            copy: if `False`, modify this expression instance in-place.
2355            opts: other options to use to parse the input expressions.
2356
2357        Returns:
2358            The limited subqueryable.
2359        """
2360        return (
2361            select("*")
2362            .from_(self.subquery(alias="_l_0", copy=copy))
2363            .limit(expression, dialect=dialect, copy=False, **opts)
2364        )

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

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

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

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

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

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

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

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

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:
2783    def lateral(
2784        self,
2785        *expressions: t.Optional[ExpOrStr],
2786        append: bool = True,
2787        dialect: DialectType = None,
2788        copy: bool = True,
2789        **opts,
2790    ) -> Select:
2791        """
2792        Append to or set the LATERAL expressions.
2793
2794        Example:
2795            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2796            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2797
2798        Args:
2799            *expressions: the SQL code strings to parse.
2800                If an `Expression` instance is passed, it will be used as-is.
2801            append: if `True`, add to any existing expressions.
2802                Otherwise, this resets the expressions.
2803            dialect: the dialect used to parse the input expressions.
2804            copy: if `False`, modify this expression instance in-place.
2805            opts: other options to use to parse the input expressions.
2806
2807        Returns:
2808            The modified Select expression.
2809        """
2810        return _apply_list_builder(
2811            *expressions,
2812            instance=self,
2813            arg="laterals",
2814            append=append,
2815            into=Lateral,
2816            prefix="LATERAL VIEW",
2817            dialect=dialect,
2818            copy=copy,
2819            **opts,
2820        )

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

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

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

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

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

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3215class Pivot(Expression):
3216    arg_types = {
3217        "this": False,
3218        "alias": False,
3219        "expressions": True,
3220        "field": False,
3221        "unpivot": False,
3222        "using": False,
3223        "group": False,
3224        "columns": False,
3225    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3228class Window(Expression):
3229    arg_types = {
3230        "this": True,
3231        "partition_by": False,
3232        "order": False,
3233        "spec": False,
3234        "alias": False,
3235        "over": False,
3236        "first": False,
3237    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3240class WindowSpec(Expression):
3241    arg_types = {
3242        "kind": False,
3243        "start": False,
3244        "start_side": False,
3245        "end": False,
3246        "end_side": False,
3247    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3250class Where(Expression):
3251    pass
key = 'where'
class Star(Expression):
3254class Star(Expression):
3255    arg_types = {"except": False, "replace": False}
3256
3257    @property
3258    def name(self) -> str:
3259        return "*"
3260
3261    @property
3262    def output_name(self) -> str:
3263        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):
3266class Parameter(Condition):
3267    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3270class SessionParameter(Condition):
3271    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3274class Placeholder(Condition):
3275    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3278class Null(Condition):
3279    arg_types: t.Dict[str, t.Any] = {}
3280
3281    @property
3282    def name(self) -> str:
3283        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3286class Boolean(Condition):
3287    pass
key = 'boolean'
class DataTypeSize(Expression):
3290class DataTypeSize(Expression):
3291    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3294class DataType(Expression):
3295    arg_types = {
3296        "this": True,
3297        "expressions": False,
3298        "nested": False,
3299        "values": False,
3300        "prefix": False,
3301    }
3302
3303    class Type(AutoName):
3304        ARRAY = auto()
3305        BIGDECIMAL = auto()
3306        BIGINT = auto()
3307        BIGSERIAL = auto()
3308        BINARY = auto()
3309        BIT = auto()
3310        BOOLEAN = auto()
3311        CHAR = auto()
3312        DATE = auto()
3313        DATETIME = auto()
3314        DATETIME64 = auto()
3315        ENUM = auto()
3316        INT4RANGE = auto()
3317        INT4MULTIRANGE = auto()
3318        INT8RANGE = auto()
3319        INT8MULTIRANGE = auto()
3320        NUMRANGE = auto()
3321        NUMMULTIRANGE = auto()
3322        TSRANGE = auto()
3323        TSMULTIRANGE = auto()
3324        TSTZRANGE = auto()
3325        TSTZMULTIRANGE = auto()
3326        DATERANGE = auto()
3327        DATEMULTIRANGE = auto()
3328        DECIMAL = auto()
3329        DOUBLE = auto()
3330        FLOAT = auto()
3331        GEOGRAPHY = auto()
3332        GEOMETRY = auto()
3333        HLLSKETCH = auto()
3334        HSTORE = auto()
3335        IMAGE = auto()
3336        INET = auto()
3337        INT = auto()
3338        INT128 = auto()
3339        INT256 = auto()
3340        INTERVAL = auto()
3341        JSON = auto()
3342        JSONB = auto()
3343        LONGBLOB = auto()
3344        LONGTEXT = auto()
3345        MAP = auto()
3346        MEDIUMBLOB = auto()
3347        MEDIUMTEXT = auto()
3348        MONEY = auto()
3349        NCHAR = auto()
3350        NULL = auto()
3351        NULLABLE = auto()
3352        NVARCHAR = auto()
3353        OBJECT = auto()
3354        ROWVERSION = auto()
3355        SERIAL = auto()
3356        SET = auto()
3357        SMALLINT = auto()
3358        SMALLMONEY = auto()
3359        SMALLSERIAL = auto()
3360        STRUCT = auto()
3361        SUPER = auto()
3362        TEXT = auto()
3363        TIME = auto()
3364        TIMESTAMP = auto()
3365        TIMESTAMPTZ = auto()
3366        TIMESTAMPLTZ = auto()
3367        TINYINT = auto()
3368        UBIGINT = auto()
3369        UINT = auto()
3370        USMALLINT = auto()
3371        UTINYINT = auto()
3372        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3373        UINT128 = auto()
3374        UINT256 = auto()
3375        UNIQUEIDENTIFIER = auto()
3376        USERDEFINED = "USER-DEFINED"
3377        UUID = auto()
3378        VARBINARY = auto()
3379        VARCHAR = auto()
3380        VARIANT = auto()
3381        XML = auto()
3382
3383    TEXT_TYPES = {
3384        Type.CHAR,
3385        Type.NCHAR,
3386        Type.VARCHAR,
3387        Type.NVARCHAR,
3388        Type.TEXT,
3389    }
3390
3391    INTEGER_TYPES = {
3392        Type.INT,
3393        Type.TINYINT,
3394        Type.SMALLINT,
3395        Type.BIGINT,
3396        Type.INT128,
3397        Type.INT256,
3398    }
3399
3400    FLOAT_TYPES = {
3401        Type.FLOAT,
3402        Type.DOUBLE,
3403    }
3404
3405    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3406
3407    TEMPORAL_TYPES = {
3408        Type.TIME,
3409        Type.TIMESTAMP,
3410        Type.TIMESTAMPTZ,
3411        Type.TIMESTAMPLTZ,
3412        Type.DATE,
3413        Type.DATETIME,
3414        Type.DATETIME64,
3415    }
3416
3417    META_TYPES = {"UNKNOWN", "NULL"}
3418
3419    @classmethod
3420    def build(
3421        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3422    ) -> DataType:
3423        from sqlglot import parse_one
3424
3425        if isinstance(dtype, str):
3426            upper = dtype.upper()
3427            if upper in DataType.META_TYPES:
3428                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3429            else:
3430                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3431
3432            if data_type_exp is None:
3433                raise ValueError(f"Unparsable data type value: {dtype}")
3434        elif isinstance(dtype, DataType.Type):
3435            data_type_exp = DataType(this=dtype)
3436        elif isinstance(dtype, DataType):
3437            return dtype
3438        else:
3439            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3440
3441        return DataType(**{**data_type_exp.args, **kwargs})
3442
3443    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3444        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.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.TEXT: 'TEXT'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>}
INTEGER_TYPES = {<Type.INT128: 'INT128'>, <Type.INT: 'INT'>, <Type.INT256: 'INT256'>, <Type.TINYINT: 'TINYINT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.BIGINT: 'BIGINT'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.FLOAT: 'FLOAT'>, <Type.INT: 'INT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT256: 'INT256'>, <Type.TINYINT: 'TINYINT'>, <Type.DOUBLE: 'DOUBLE'>}
TEMPORAL_TYPES = {<Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIME: 'TIME'>, <Type.DATETIME: 'DATETIME'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATE: 'DATE'>, <Type.DATETIME64: 'DATETIME64'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>}
META_TYPES = {'NULL', 'UNKNOWN'}
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
3419    @classmethod
3420    def build(
3421        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3422    ) -> DataType:
3423        from sqlglot import parse_one
3424
3425        if isinstance(dtype, str):
3426            upper = dtype.upper()
3427            if upper in DataType.META_TYPES:
3428                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3429            else:
3430                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3431
3432            if data_type_exp is None:
3433                raise ValueError(f"Unparsable data type value: {dtype}")
3434        elif isinstance(dtype, DataType.Type):
3435            data_type_exp = DataType(this=dtype)
3436        elif isinstance(dtype, DataType):
3437            return dtype
3438        else:
3439            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3440
3441        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3443    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3444        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3303    class Type(AutoName):
3304        ARRAY = auto()
3305        BIGDECIMAL = auto()
3306        BIGINT = auto()
3307        BIGSERIAL = auto()
3308        BINARY = auto()
3309        BIT = auto()
3310        BOOLEAN = auto()
3311        CHAR = auto()
3312        DATE = auto()
3313        DATETIME = auto()
3314        DATETIME64 = auto()
3315        ENUM = auto()
3316        INT4RANGE = auto()
3317        INT4MULTIRANGE = auto()
3318        INT8RANGE = auto()
3319        INT8MULTIRANGE = auto()
3320        NUMRANGE = auto()
3321        NUMMULTIRANGE = auto()
3322        TSRANGE = auto()
3323        TSMULTIRANGE = auto()
3324        TSTZRANGE = auto()
3325        TSTZMULTIRANGE = auto()
3326        DATERANGE = auto()
3327        DATEMULTIRANGE = auto()
3328        DECIMAL = auto()
3329        DOUBLE = auto()
3330        FLOAT = auto()
3331        GEOGRAPHY = auto()
3332        GEOMETRY = auto()
3333        HLLSKETCH = auto()
3334        HSTORE = auto()
3335        IMAGE = auto()
3336        INET = auto()
3337        INT = auto()
3338        INT128 = auto()
3339        INT256 = auto()
3340        INTERVAL = auto()
3341        JSON = auto()
3342        JSONB = auto()
3343        LONGBLOB = auto()
3344        LONGTEXT = auto()
3345        MAP = auto()
3346        MEDIUMBLOB = auto()
3347        MEDIUMTEXT = auto()
3348        MONEY = auto()
3349        NCHAR = auto()
3350        NULL = auto()
3351        NULLABLE = auto()
3352        NVARCHAR = auto()
3353        OBJECT = auto()
3354        ROWVERSION = auto()
3355        SERIAL = auto()
3356        SET = auto()
3357        SMALLINT = auto()
3358        SMALLMONEY = auto()
3359        SMALLSERIAL = auto()
3360        STRUCT = auto()
3361        SUPER = auto()
3362        TEXT = auto()
3363        TIME = auto()
3364        TIMESTAMP = auto()
3365        TIMESTAMPTZ = auto()
3366        TIMESTAMPLTZ = auto()
3367        TINYINT = auto()
3368        UBIGINT = auto()
3369        UINT = auto()
3370        USMALLINT = auto()
3371        UTINYINT = auto()
3372        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3373        UINT128 = auto()
3374        UINT256 = auto()
3375        UNIQUEIDENTIFIER = auto()
3376        USERDEFINED = "USER-DEFINED"
3377        UUID = auto()
3378        VARBINARY = auto()
3379        VARCHAR = auto()
3380        VARIANT = auto()
3381        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):
3448class PseudoType(Expression):
3449    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3453class SubqueryPredicate(Predicate):
3454    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3457class All(SubqueryPredicate):
3458    pass
key = 'all'
class Any(SubqueryPredicate):
3461class Any(SubqueryPredicate):
3462    pass
key = 'any'
class Exists(SubqueryPredicate):
3465class Exists(SubqueryPredicate):
3466    pass
key = 'exists'
class Command(Expression):
3471class Command(Expression):
3472    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3475class Transaction(Expression):
3476    arg_types = {"this": False, "modes": False}
arg_types = {'this': False, 'modes': False}
key = 'transaction'
class Commit(Expression):
3479class Commit(Expression):
3480    arg_types = {"chain": False}
arg_types = {'chain': False}
key = 'commit'
class Rollback(Expression):
3483class Rollback(Expression):
3484    arg_types = {"savepoint": False}
arg_types = {'savepoint': False}
key = 'rollback'
class AlterTable(Expression):
3487class AlterTable(Expression):
3488    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3491class AddConstraint(Expression):
3492    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3495class DropPartition(Expression):
3496    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3500class Binary(Condition):
3501    arg_types = {"this": True, "expression": True}
3502
3503    @property
3504    def left(self):
3505        return self.this
3506
3507    @property
3508    def right(self):
3509        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3512class Add(Binary):
3513    pass
key = 'add'
class Connector(Binary):
3516class Connector(Binary):
3517    pass
key = 'connector'
class And(Connector):
3520class And(Connector):
3521    pass
key = 'and'
class Or(Connector):
3524class Or(Connector):
3525    pass
key = 'or'
class Xor(Connector):
3528class Xor(Connector):
3529    pass
key = 'xor'
class BitwiseAnd(Binary):
3532class BitwiseAnd(Binary):
3533    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3536class BitwiseLeftShift(Binary):
3537    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3540class BitwiseOr(Binary):
3541    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3544class BitwiseRightShift(Binary):
3545    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3548class BitwiseXor(Binary):
3549    pass
key = 'bitwisexor'
class Div(Binary):
3552class Div(Binary):
3553    pass
key = 'div'
class Overlaps(Binary):
3556class Overlaps(Binary):
3557    pass
key = 'overlaps'
class Dot(Binary):
3560class Dot(Binary):
3561    @property
3562    def name(self) -> str:
3563        return self.expression.name
3564
3565    @property
3566    def output_name(self) -> str:
3567        return self.name
3568
3569    @classmethod
3570    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3571        """Build a Dot object with a sequence of expressions."""
3572        if len(expressions) < 2:
3573            raise ValueError(f"Dot requires >= 2 expressions.")
3574
3575        a, b, *expressions = expressions
3576        dot = Dot(this=a, expression=b)
3577
3578        for expression in expressions:
3579            dot = Dot(this=dot, expression=expression)
3580
3581        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:
3569    @classmethod
3570    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3571        """Build a Dot object with a sequence of expressions."""
3572        if len(expressions) < 2:
3573            raise ValueError(f"Dot requires >= 2 expressions.")
3574
3575        a, b, *expressions = expressions
3576        dot = Dot(this=a, expression=b)
3577
3578        for expression in expressions:
3579            dot = Dot(this=dot, expression=expression)
3580
3581        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3584class DPipe(Binary):
3585    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3588class SafeDPipe(DPipe):
3589    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3592class EQ(Binary, Predicate):
3593    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3596class NullSafeEQ(Binary, Predicate):
3597    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3600class NullSafeNEQ(Binary, Predicate):
3601    pass
key = 'nullsafeneq'
class Distance(Binary):
3604class Distance(Binary):
3605    pass
key = 'distance'
class Escape(Binary):
3608class Escape(Binary):
3609    pass
key = 'escape'
class Glob(Binary, Predicate):
3612class Glob(Binary, Predicate):
3613    pass
key = 'glob'
class GT(Binary, Predicate):
3616class GT(Binary, Predicate):
3617    pass
key = 'gt'
class GTE(Binary, Predicate):
3620class GTE(Binary, Predicate):
3621    pass
key = 'gte'
class ILike(Binary, Predicate):
3624class ILike(Binary, Predicate):
3625    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3628class ILikeAny(Binary, Predicate):
3629    pass
key = 'ilikeany'
class IntDiv(Binary):
3632class IntDiv(Binary):
3633    pass
key = 'intdiv'
class Is(Binary, Predicate):
3636class Is(Binary, Predicate):
3637    pass
key = 'is'
class Kwarg(Binary):
3640class Kwarg(Binary):
3641    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3644class Like(Binary, Predicate):
3645    pass
key = 'like'
class LikeAny(Binary, Predicate):
3648class LikeAny(Binary, Predicate):
3649    pass
key = 'likeany'
class LT(Binary, Predicate):
3652class LT(Binary, Predicate):
3653    pass
key = 'lt'
class LTE(Binary, Predicate):
3656class LTE(Binary, Predicate):
3657    pass
key = 'lte'
class Mod(Binary):
3660class Mod(Binary):
3661    pass
key = 'mod'
class Mul(Binary):
3664class Mul(Binary):
3665    pass
key = 'mul'
class NEQ(Binary, Predicate):
3668class NEQ(Binary, Predicate):
3669    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3672class SimilarTo(Binary, Predicate):
3673    pass
key = 'similarto'
class Slice(Binary):
3676class Slice(Binary):
3677    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3680class Sub(Binary):
3681    pass
key = 'sub'
class ArrayOverlaps(Binary):
3684class ArrayOverlaps(Binary):
3685    pass
key = 'arrayoverlaps'
class Unary(Condition):
3690class Unary(Condition):
3691    pass
key = 'unary'
class BitwiseNot(Unary):
3694class BitwiseNot(Unary):
3695    pass
key = 'bitwisenot'
class Not(Unary):
3698class Not(Unary):
3699    pass
key = 'not'
class Paren(Unary):
3702class Paren(Unary):
3703    arg_types = {"this": True, "with": False}
3704
3705    @property
3706    def output_name(self) -> str:
3707        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):
3710class Neg(Unary):
3711    pass
key = 'neg'
class Alias(Expression):
3714class Alias(Expression):
3715    arg_types = {"this": True, "alias": False}
3716
3717    @property
3718    def output_name(self) -> str:
3719        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):
3722class Aliases(Expression):
3723    arg_types = {"this": True, "expressions": True}
3724
3725    @property
3726    def aliases(self):
3727        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3730class AtTimeZone(Expression):
3731    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3734class Between(Predicate):
3735    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3738class Bracket(Condition):
3739    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3742class SafeBracket(Bracket):
3743    """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):
3746class Distinct(Expression):
3747    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3750class In(Predicate):
3751    arg_types = {
3752        "this": True,
3753        "expressions": False,
3754        "query": False,
3755        "unnest": False,
3756        "field": False,
3757        "is_global": False,
3758    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3761class TimeUnit(Expression):
3762    """Automatically converts unit arg into a var."""
3763
3764    arg_types = {"unit": False}
3765
3766    def __init__(self, **args):
3767        unit = args.get("unit")
3768        if isinstance(unit, (Column, Literal)):
3769            args["unit"] = Var(this=unit.name)
3770        elif isinstance(unit, Week):
3771            unit.set("this", Var(this=unit.this.name))
3772
3773        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3766    def __init__(self, **args):
3767        unit = args.get("unit")
3768        if isinstance(unit, (Column, Literal)):
3769            args["unit"] = Var(this=unit.name)
3770        elif isinstance(unit, Week):
3771            unit.set("this", Var(this=unit.this.name))
3772
3773        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3776class Interval(TimeUnit):
3777    arg_types = {"this": False, "unit": False}
3778
3779    @property
3780    def unit(self) -> t.Optional[Var]:
3781        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3784class IgnoreNulls(Expression):
3785    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3788class RespectNulls(Expression):
3789    pass
key = 'respectnulls'
class Func(Condition):
3793class Func(Condition):
3794    """
3795    The base class for all function expressions.
3796
3797    Attributes:
3798        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3799            treated as a variable length argument and the argument's value will be stored as a list.
3800        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3801            for this function expression. These values are used to map this node to a name during parsing
3802            as well as to provide the function's name during SQL string generation. By default the SQL
3803            name is set to the expression's class name transformed to snake case.
3804    """
3805
3806    is_var_len_args = False
3807
3808    @classmethod
3809    def from_arg_list(cls, args):
3810        if cls.is_var_len_args:
3811            all_arg_keys = list(cls.arg_types)
3812            # If this function supports variable length argument treat the last argument as such.
3813            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3814            num_non_var = len(non_var_len_arg_keys)
3815
3816            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3817            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3818        else:
3819            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3820
3821        return cls(**args_dict)
3822
3823    @classmethod
3824    def sql_names(cls):
3825        if cls is Func:
3826            raise NotImplementedError(
3827                "SQL name is only supported by concrete function implementations"
3828            )
3829        if "_sql_names" not in cls.__dict__:
3830            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3831        return cls._sql_names
3832
3833    @classmethod
3834    def sql_name(cls):
3835        return cls.sql_names()[0]
3836
3837    @classmethod
3838    def default_parser_mappings(cls):
3839        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):
3808    @classmethod
3809    def from_arg_list(cls, args):
3810        if cls.is_var_len_args:
3811            all_arg_keys = list(cls.arg_types)
3812            # If this function supports variable length argument treat the last argument as such.
3813            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3814            num_non_var = len(non_var_len_arg_keys)
3815
3816            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3817            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3818        else:
3819            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3820
3821        return cls(**args_dict)
@classmethod
def sql_names(cls):
3823    @classmethod
3824    def sql_names(cls):
3825        if cls is Func:
3826            raise NotImplementedError(
3827                "SQL name is only supported by concrete function implementations"
3828            )
3829        if "_sql_names" not in cls.__dict__:
3830            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3831        return cls._sql_names
@classmethod
def sql_name(cls):
3833    @classmethod
3834    def sql_name(cls):
3835        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3837    @classmethod
3838    def default_parser_mappings(cls):
3839        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3842class AggFunc(Func):
3843    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3846class ParameterizedAgg(AggFunc):
3847    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3850class Abs(Func):
3851    pass
key = 'abs'
class Anonymous(Func):
3854class Anonymous(Func):
3855    arg_types = {"this": True, "expressions": False}
3856    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3861class Hll(AggFunc):
3862    arg_types = {"this": True, "expressions": False}
3863    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3866class ApproxDistinct(AggFunc):
3867    arg_types = {"this": True, "accuracy": False}
3868    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3871class Array(Func):
3872    arg_types = {"expressions": False}
3873    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3877class ToChar(Func):
3878    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3881class GenerateSeries(Func):
3882    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3885class ArrayAgg(AggFunc):
3886    pass
key = 'arrayagg'
class ArrayAll(Func):
3889class ArrayAll(Func):
3890    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3893class ArrayAny(Func):
3894    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3897class ArrayConcat(Func):
3898    arg_types = {"this": True, "expressions": False}
3899    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3902class ArrayContains(Binary, Func):
3903    pass
key = 'arraycontains'
class ArrayContained(Binary):
3906class ArrayContained(Binary):
3907    pass
key = 'arraycontained'
class ArrayFilter(Func):
3910class ArrayFilter(Func):
3911    arg_types = {"this": True, "expression": True}
3912    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3915class ArrayJoin(Func):
3916    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3919class ArraySize(Func):
3920    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3923class ArraySort(Func):
3924    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3927class ArraySum(Func):
3928    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3931class ArrayUnionAgg(AggFunc):
3932    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3935class Avg(AggFunc):
3936    pass
key = 'avg'
class AnyValue(AggFunc):
3939class AnyValue(AggFunc):
3940    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
3943class Case(Func):
3944    arg_types = {"this": False, "ifs": True, "default": False}
3945
3946    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3947        instance = _maybe_copy(self, copy)
3948        instance.append(
3949            "ifs",
3950            If(
3951                this=maybe_parse(condition, copy=copy, **opts),
3952                true=maybe_parse(then, copy=copy, **opts),
3953            ),
3954        )
3955        return instance
3956
3957    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3958        instance = _maybe_copy(self, copy)
3959        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3960        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:
3946    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3947        instance = _maybe_copy(self, copy)
3948        instance.append(
3949            "ifs",
3950            If(
3951                this=maybe_parse(condition, copy=copy, **opts),
3952                true=maybe_parse(then, copy=copy, **opts),
3953            ),
3954        )
3955        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3957    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3958        instance = _maybe_copy(self, copy)
3959        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3960        return instance
key = 'case'
class Cast(Func):
3963class Cast(Func):
3964    arg_types = {"this": True, "to": True, "format": False}
3965
3966    @property
3967    def name(self) -> str:
3968        return self.this.name
3969
3970    @property
3971    def to(self) -> DataType:
3972        return self.args["to"]
3973
3974    @property
3975    def output_name(self) -> str:
3976        return self.name
3977
3978    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3979        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:
3978    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3979        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
3982class CastToStrType(Func):
3983    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
3986class Collate(Binary):
3987    pass
key = 'collate'
class TryCast(Cast):
3990class TryCast(Cast):
3991    pass
key = 'trycast'
class Ceil(Func):
3994class Ceil(Func):
3995    arg_types = {"this": True, "decimals": False}
3996    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
3999class Coalesce(Func):
4000    arg_types = {"this": True, "expressions": False}
4001    is_var_len_args = True
4002    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4005class Concat(Func):
4006    arg_types = {"expressions": True}
4007    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4010class SafeConcat(Concat):
4011    pass
key = 'safeconcat'
class ConcatWs(Concat):
4014class ConcatWs(Concat):
4015    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4018class Count(AggFunc):
4019    arg_types = {"this": False, "expressions": False}
4020    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4023class CountIf(AggFunc):
4024    pass
key = 'countif'
class CurrentDate(Func):
4027class CurrentDate(Func):
4028    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4031class CurrentDatetime(Func):
4032    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4035class CurrentTime(Func):
4036    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4039class CurrentTimestamp(Func):
4040    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4043class CurrentUser(Func):
4044    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4047class DateAdd(Func, TimeUnit):
4048    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4051class DateSub(Func, TimeUnit):
4052    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4055class DateDiff(Func, TimeUnit):
4056    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4057    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4060class DateTrunc(Func):
4061    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4064class DatetimeAdd(Func, TimeUnit):
4065    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4068class DatetimeSub(Func, TimeUnit):
4069    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4072class DatetimeDiff(Func, TimeUnit):
4073    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4076class DatetimeTrunc(Func, TimeUnit):
4077    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4080class DayOfWeek(Func):
4081    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4084class DayOfMonth(Func):
4085    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4088class DayOfYear(Func):
4089    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4092class WeekOfYear(Func):
4093    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class LastDateOfMonth(Func):
4096class LastDateOfMonth(Func):
4097    pass
key = 'lastdateofmonth'
class Extract(Func):
4100class Extract(Func):
4101    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4104class TimestampAdd(Func, TimeUnit):
4105    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4108class TimestampSub(Func, TimeUnit):
4109    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4112class TimestampDiff(Func, TimeUnit):
4113    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4116class TimestampTrunc(Func, TimeUnit):
4117    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4120class TimeAdd(Func, TimeUnit):
4121    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4124class TimeSub(Func, TimeUnit):
4125    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4128class TimeDiff(Func, TimeUnit):
4129    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4132class TimeTrunc(Func, TimeUnit):
4133    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4136class DateFromParts(Func):
4137    _sql_names = ["DATEFROMPARTS"]
4138    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4141class DateStrToDate(Func):
4142    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4145class DateToDateStr(Func):
4146    pass
key = 'datetodatestr'
class DateToDi(Func):
4149class DateToDi(Func):
4150    pass
key = 'datetodi'
class Date(Func):
4154class Date(Func):
4155    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4158class Day(Func):
4159    pass
key = 'day'
class Decode(Func):
4162class Decode(Func):
4163    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4166class DiToDate(Func):
4167    pass
key = 'ditodate'
class Encode(Func):
4170class Encode(Func):
4171    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4174class Exp(Func):
4175    pass
key = 'exp'
class Explode(Func):
4178class Explode(Func):
4179    pass
key = 'explode'
class Floor(Func):
4182class Floor(Func):
4183    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4186class FromBase64(Func):
4187    pass
key = 'frombase64'
class ToBase64(Func):
4190class ToBase64(Func):
4191    pass
key = 'tobase64'
class Greatest(Func):
4194class Greatest(Func):
4195    arg_types = {"this": True, "expressions": False}
4196    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4199class GroupConcat(Func):
4200    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4203class Hex(Func):
4204    pass
key = 'hex'
class If(Func):
4207class If(Func):
4208    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4211class Initcap(Func):
4212    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4215class JSONKeyValue(Expression):
4216    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4219class JSONObject(Func):
4220    arg_types = {
4221        "expressions": False,
4222        "null_handling": False,
4223        "unique_keys": False,
4224        "return_type": False,
4225        "format_json": False,
4226        "encoding": False,
4227    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4230class OpenJSONColumnDef(Expression):
4231    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):
4234class OpenJSON(Func):
4235    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4238class JSONBContains(Binary):
4239    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4242class JSONExtract(Binary, Func):
4243    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4246class JSONExtractScalar(JSONExtract):
4247    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4250class JSONBExtract(JSONExtract):
4251    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4254class JSONBExtractScalar(JSONExtract):
4255    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4258class JSONFormat(Func):
4259    arg_types = {"this": False, "options": False}
4260    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4264class JSONArrayContains(Binary, Predicate, Func):
4265    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4268class Least(Func):
4269    arg_types = {"this": True, "expressions": False}
4270    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4273class Left(Func):
4274    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4281class Length(Func):
4282    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4285class Levenshtein(Func):
4286    arg_types = {
4287        "this": True,
4288        "expression": False,
4289        "ins_cost": False,
4290        "del_cost": False,
4291        "sub_cost": False,
4292    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4295class Ln(Func):
4296    pass
key = 'ln'
class Log(Func):
4299class Log(Func):
4300    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4303class Log2(Func):
4304    pass
key = 'log2'
class Log10(Func):
4307class Log10(Func):
4308    pass
key = 'log10'
class LogicalOr(AggFunc):
4311class LogicalOr(AggFunc):
4312    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4315class LogicalAnd(AggFunc):
4316    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4319class Lower(Func):
4320    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4323class Map(Func):
4324    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4327class MapFromEntries(Func):
4328    pass
key = 'mapfromentries'
class StarMap(Func):
4331class StarMap(Func):
4332    pass
key = 'starmap'
class VarMap(Func):
4335class VarMap(Func):
4336    arg_types = {"keys": True, "values": True}
4337    is_var_len_args = True
4338
4339    @property
4340    def keys(self) -> t.List[Expression]:
4341        return self.args["keys"].expressions
4342
4343    @property
4344    def values(self) -> t.List[Expression]:
4345        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4349class MatchAgainst(Func):
4350    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4353class Max(AggFunc):
4354    arg_types = {"this": True, "expressions": False}
4355    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4358class MD5(Func):
4359    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4363class MD5Digest(Func):
4364    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4367class Min(AggFunc):
4368    arg_types = {"this": True, "expressions": False}
4369    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4372class Month(Func):
4373    pass
key = 'month'
class Nvl2(Func):
4376class Nvl2(Func):
4377    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4380class Posexplode(Func):
4381    pass
key = 'posexplode'
class Pow(Binary, Func):
4384class Pow(Binary, Func):
4385    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4388class PercentileCont(AggFunc):
4389    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4392class PercentileDisc(AggFunc):
4393    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4396class Quantile(AggFunc):
4397    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4400class ApproxQuantile(Quantile):
4401    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):
4404class RangeN(Func):
4405    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4408class ReadCSV(Func):
4409    _sql_names = ["READ_CSV"]
4410    is_var_len_args = True
4411    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4414class Reduce(Func):
4415    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):
4418class RegexpExtract(Func):
4419    arg_types = {
4420        "this": True,
4421        "expression": True,
4422        "position": False,
4423        "occurrence": False,
4424        "parameters": False,
4425        "group": False,
4426    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpLike(Func):
4429class RegexpLike(Func):
4430    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4433class RegexpILike(Func):
4434    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4439class RegexpSplit(Func):
4440    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4443class Repeat(Func):
4444    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4447class Round(Func):
4448    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4451class RowNumber(Func):
4452    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4455class SafeDivide(Func):
4456    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4459class SetAgg(AggFunc):
4460    pass
key = 'setagg'
class SHA(Func):
4463class SHA(Func):
4464    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4467class SHA2(Func):
4468    _sql_names = ["SHA2"]
4469    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4472class SortArray(Func):
4473    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4476class Split(Func):
4477    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4482class Substring(Func):
4483    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4486class StandardHash(Func):
4487    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4490class StrPosition(Func):
4491    arg_types = {
4492        "this": True,
4493        "substr": True,
4494        "position": False,
4495        "instance": False,
4496    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4499class StrToDate(Func):
4500    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4503class StrToTime(Func):
4504    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4509class StrToUnix(Func):
4510    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4513class NumberToStr(Func):
4514    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4517class FromBase(Func):
4518    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4521class Struct(Func):
4522    arg_types = {"expressions": True}
4523    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4526class StructExtract(Func):
4527    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4530class Sum(AggFunc):
4531    pass
key = 'sum'
class Sqrt(Func):
4534class Sqrt(Func):
4535    pass
key = 'sqrt'
class Stddev(AggFunc):
4538class Stddev(AggFunc):
4539    pass
key = 'stddev'
class StddevPop(AggFunc):
4542class StddevPop(AggFunc):
4543    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4546class StddevSamp(AggFunc):
4547    pass
key = 'stddevsamp'
class TimeToStr(Func):
4550class TimeToStr(Func):
4551    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4554class TimeToTimeStr(Func):
4555    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4558class TimeToUnix(Func):
4559    pass
key = 'timetounix'
class TimeStrToDate(Func):
4562class TimeStrToDate(Func):
4563    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4566class TimeStrToTime(Func):
4567    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4570class TimeStrToUnix(Func):
4571    pass
key = 'timestrtounix'
class Trim(Func):
4574class Trim(Func):
4575    arg_types = {
4576        "this": True,
4577        "expression": False,
4578        "position": False,
4579        "collation": False,
4580    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4583class TsOrDsAdd(Func, TimeUnit):
4584    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4587class TsOrDsToDateStr(Func):
4588    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4591class TsOrDsToDate(Func):
4592    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4595class TsOrDiToDi(Func):
4596    pass
key = 'tsorditodi'
class Unhex(Func):
4599class Unhex(Func):
4600    pass
key = 'unhex'
class UnixToStr(Func):
4603class UnixToStr(Func):
4604    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4609class UnixToTime(Func):
4610    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4611
4612    SECONDS = Literal.string("seconds")
4613    MILLIS = Literal.string("millis")
4614    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):
4617class UnixToTimeStr(Func):
4618    pass
key = 'unixtotimestr'
class Upper(Func):
4621class Upper(Func):
4622    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4625class Variance(AggFunc):
4626    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4629class VariancePop(AggFunc):
4630    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4633class Week(Func):
4634    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4637class XMLTable(Func):
4638    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):
4641class Year(Func):
4642    pass
key = 'year'
class Use(Expression):
4645class Use(Expression):
4646    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4649class Merge(Expression):
4650    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):
4653class When(Func):
4654    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):
4659class NextValueFor(Func):
4660    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:
4697def maybe_parse(
4698    sql_or_expression: ExpOrStr,
4699    *,
4700    into: t.Optional[IntoType] = None,
4701    dialect: DialectType = None,
4702    prefix: t.Optional[str] = None,
4703    copy: bool = False,
4704    **opts,
4705) -> Expression:
4706    """Gracefully handle a possible string or expression.
4707
4708    Example:
4709        >>> maybe_parse("1")
4710        (LITERAL this: 1, is_string: False)
4711        >>> maybe_parse(to_identifier("x"))
4712        (IDENTIFIER this: x, quoted: False)
4713
4714    Args:
4715        sql_or_expression: the SQL code string or an expression
4716        into: the SQLGlot Expression to parse into
4717        dialect: the dialect used to parse the input expressions (in the case that an
4718            input expression is a SQL string).
4719        prefix: a string to prefix the sql with before it gets parsed
4720            (automatically includes a space)
4721        copy: whether or not to copy the expression.
4722        **opts: other options to use to parse the input expressions (again, in the case
4723            that an input expression is a SQL string).
4724
4725    Returns:
4726        Expression: the parsed or given expression.
4727    """
4728    if isinstance(sql_or_expression, Expression):
4729        if copy:
4730            return sql_or_expression.copy()
4731        return sql_or_expression
4732
4733    if sql_or_expression is None:
4734        raise ParseError(f"SQL cannot be None")
4735
4736    import sqlglot
4737
4738    sql = str(sql_or_expression)
4739    if prefix:
4740        sql = f"{prefix} {sql}"
4741
4742    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:
4926def union(
4927    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4928) -> Union:
4929    """
4930    Initializes a syntax tree from one UNION expression.
4931
4932    Example:
4933        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4934        'SELECT * FROM foo UNION SELECT * FROM bla'
4935
4936    Args:
4937        left: the SQL code string corresponding to the left-hand side.
4938            If an `Expression` instance is passed, it will be used as-is.
4939        right: the SQL code string corresponding to the right-hand side.
4940            If an `Expression` instance is passed, it will be used as-is.
4941        distinct: set the DISTINCT flag if and only if this is true.
4942        dialect: the dialect used to parse the input expression.
4943        opts: other options to use to parse the input expressions.
4944
4945    Returns:
4946        The new Union instance.
4947    """
4948    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4949    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4950
4951    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:
4954def intersect(
4955    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4956) -> Intersect:
4957    """
4958    Initializes a syntax tree from one INTERSECT expression.
4959
4960    Example:
4961        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4962        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4963
4964    Args:
4965        left: the SQL code string corresponding to the left-hand side.
4966            If an `Expression` instance is passed, it will be used as-is.
4967        right: the SQL code string corresponding to the right-hand side.
4968            If an `Expression` instance is passed, it will be used as-is.
4969        distinct: set the DISTINCT flag if and only if this is true.
4970        dialect: the dialect used to parse the input expression.
4971        opts: other options to use to parse the input expressions.
4972
4973    Returns:
4974        The new Intersect instance.
4975    """
4976    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4977    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4978
4979    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:
4982def except_(
4983    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4984) -> Except:
4985    """
4986    Initializes a syntax tree from one EXCEPT expression.
4987
4988    Example:
4989        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4990        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4991
4992    Args:
4993        left: the SQL code string corresponding to the left-hand side.
4994            If an `Expression` instance is passed, it will be used as-is.
4995        right: the SQL code string corresponding to the right-hand side.
4996            If an `Expression` instance is passed, it will be used as-is.
4997        distinct: set the DISTINCT flag if and only if this is true.
4998        dialect: the dialect used to parse the input expression.
4999        opts: other options to use to parse the input expressions.
5000
5001    Returns:
5002        The new Except instance.
5003    """
5004    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5005    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5006
5007    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:
5010def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5011    """
5012    Initializes a syntax tree from one or multiple SELECT expressions.
5013
5014    Example:
5015        >>> select("col1", "col2").from_("tbl").sql()
5016        'SELECT col1, col2 FROM tbl'
5017
5018    Args:
5019        *expressions: the SQL code string to parse as the expressions of a
5020            SELECT statement. If an Expression instance is passed, this is used as-is.
5021        dialect: the dialect used to parse the input expressions (in the case that an
5022            input expression is a SQL string).
5023        **opts: other options to use to parse the input expressions (again, in the case
5024            that an input expression is a SQL string).
5025
5026    Returns:
5027        Select: the syntax tree for the SELECT statement.
5028    """
5029    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:
5032def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5033    """
5034    Initializes a syntax tree from a FROM expression.
5035
5036    Example:
5037        >>> from_("tbl").select("col1", "col2").sql()
5038        'SELECT col1, col2 FROM tbl'
5039
5040    Args:
5041        *expression: the SQL code string to parse as the FROM expressions of a
5042            SELECT statement. If an Expression instance is passed, this is used as-is.
5043        dialect: the dialect used to parse the input expression (in the case that the
5044            input expression is a SQL string).
5045        **opts: other options to use to parse the input expressions (again, in the case
5046            that the input expression is a SQL string).
5047
5048    Returns:
5049        Select: the syntax tree for the SELECT statement.
5050    """
5051    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:
5054def update(
5055    table: str | Table,
5056    properties: dict,
5057    where: t.Optional[ExpOrStr] = None,
5058    from_: t.Optional[ExpOrStr] = None,
5059    dialect: DialectType = None,
5060    **opts,
5061) -> Update:
5062    """
5063    Creates an update statement.
5064
5065    Example:
5066        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5067        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5068
5069    Args:
5070        *properties: dictionary of properties to set which are
5071            auto converted to sql objects eg None -> NULL
5072        where: sql conditional parsed into a WHERE statement
5073        from_: sql statement parsed into a FROM statement
5074        dialect: the dialect used to parse the input expressions.
5075        **opts: other options to use to parse the input expressions.
5076
5077    Returns:
5078        Update: the syntax tree for the UPDATE statement.
5079    """
5080    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5081    update_expr.set(
5082        "expressions",
5083        [
5084            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5085            for k, v in properties.items()
5086        ],
5087    )
5088    if from_:
5089        update_expr.set(
5090            "from",
5091            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5092        )
5093    if isinstance(where, Condition):
5094        where = Where(this=where)
5095    if where:
5096        update_expr.set(
5097            "where",
5098            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5099        )
5100    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:
5103def delete(
5104    table: ExpOrStr,
5105    where: t.Optional[ExpOrStr] = None,
5106    returning: t.Optional[ExpOrStr] = None,
5107    dialect: DialectType = None,
5108    **opts,
5109) -> Delete:
5110    """
5111    Builds a delete statement.
5112
5113    Example:
5114        >>> delete("my_table", where="id > 1").sql()
5115        'DELETE FROM my_table WHERE id > 1'
5116
5117    Args:
5118        where: sql conditional parsed into a WHERE statement
5119        returning: sql conditional parsed into a RETURNING statement
5120        dialect: the dialect used to parse the input expressions.
5121        **opts: other options to use to parse the input expressions.
5122
5123    Returns:
5124        Delete: the syntax tree for the DELETE statement.
5125    """
5126    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5127    if where:
5128        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5129    if returning:
5130        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5131    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:
5134def insert(
5135    expression: ExpOrStr,
5136    into: ExpOrStr,
5137    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5138    overwrite: t.Optional[bool] = None,
5139    dialect: DialectType = None,
5140    copy: bool = True,
5141    **opts,
5142) -> Insert:
5143    """
5144    Builds an INSERT statement.
5145
5146    Example:
5147        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5148        'INSERT INTO tbl VALUES (1, 2, 3)'
5149
5150    Args:
5151        expression: the sql string or expression of the INSERT statement
5152        into: the tbl to insert data to.
5153        columns: optionally the table's column names.
5154        overwrite: whether to INSERT OVERWRITE or not.
5155        dialect: the dialect used to parse the input expressions.
5156        copy: whether or not to copy the expression.
5157        **opts: other options to use to parse the input expressions.
5158
5159    Returns:
5160        Insert: the syntax tree for the INSERT statement.
5161    """
5162    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5163    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5164
5165    if columns:
5166        this = _apply_list_builder(
5167            *columns,
5168            instance=Schema(this=this),
5169            arg="expressions",
5170            into=Identifier,
5171            copy=False,
5172            dialect=dialect,
5173            **opts,
5174        )
5175
5176    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:
5179def condition(
5180    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5181) -> Condition:
5182    """
5183    Initialize a logical condition expression.
5184
5185    Example:
5186        >>> condition("x=1").sql()
5187        'x = 1'
5188
5189        This is helpful for composing larger logical syntax trees:
5190        >>> where = condition("x=1")
5191        >>> where = where.and_("y=1")
5192        >>> Select().from_("tbl").select("*").where(where).sql()
5193        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5194
5195    Args:
5196        *expression: the SQL code string to parse.
5197            If an Expression instance is passed, this is used as-is.
5198        dialect: the dialect used to parse the input expression (in the case that the
5199            input expression is a SQL string).
5200        copy: Whether or not to copy `expression` (only applies to expressions).
5201        **opts: other options to use to parse the input expressions (again, in the case
5202            that the input expression is a SQL string).
5203
5204    Returns:
5205        The new Condition instance
5206    """
5207    return maybe_parse(
5208        expression,
5209        into=Condition,
5210        dialect=dialect,
5211        copy=copy,
5212        **opts,
5213    )

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

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

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

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

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

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

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

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

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5934def false() -> Boolean:
5935    """
5936    Returns a false Boolean expression.
5937    """
5938    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5941def null() -> Null:
5942    """
5943    Returns a Null expression.
5944    """
5945    return Null()

Returns a Null expression.

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