Edit on GitHub

Expressions

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

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


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

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

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

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

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

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

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

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

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

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

name: str
alias_or_name: str
output_name: str

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

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

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

Returns a deep copy of the expression.

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

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

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

Sets arg_key to value.

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

Returns the depth of this tree.

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

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

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

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

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

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

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

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

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

The generator object.

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

Returns a nearest parent matching expression_types.

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

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

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

Returns the root expression of this tree.

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

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

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

the generator object.

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

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

Returns:

The generator object.

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

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

Returns:

The generator object.

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

Returns the first non parenthesis child or self.

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

Returns the inner expression if this is an Alias.

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

Returns unnested operands as a tuple.

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

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

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

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

Returns SQL string representation of this tree.

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

The SQL string.

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

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

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

The transformed tree.

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

Swap out this expression with a new expression.

For example::

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

The new expression or expressions.

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

Remove this expression from its AST.

Returns:

The popped expression.

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

Assert that this Expression is an instance of type_.

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

Examples:

This is useful for type security in chained expressions:

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

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

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

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

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

Dump this Expression to a JSON-serializable dict.

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

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

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

AND this condition with one or multiple expressions.

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

The new And condition.

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

OR this condition with one or multiple expressions.

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

The new Or condition.

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

Wrap this condition with NOT.

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

The new Not instance.

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

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

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

Builds a UNION expression.

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

The new Union expression.

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

Builds an INTERSECT expression.

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

The new Intersect expression.

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

Builds an EXCEPT expression.

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

The new Except expression.

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

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

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

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

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

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

Converts the column into a dot expression.

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

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

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

Delete: the modified expression.

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

Append to or set the WHERE expressions.

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

Delete: the modified expression.

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

Set the RETURNING expression. Not supported by all dialects.

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

Delete: the modified expression.

key = 'delete'
class Drop(Expression):
1432class Drop(Expression):
1433    arg_types = {
1434        "this": False,
1435        "kind": False,
1436        "exists": False,
1437        "temporary": False,
1438        "materialized": False,
1439        "cascade": False,
1440        "constraints": False,
1441        "purge": False,
1442    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1445class Filter(Expression):
1446    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1449class Check(Expression):
1450    pass
key = 'check'
class Directory(Expression):
1453class Directory(Expression):
1454    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1455    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1458class ForeignKey(Expression):
1459    arg_types = {
1460        "expressions": True,
1461        "reference": False,
1462        "delete": False,
1463        "update": False,
1464    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1467class PrimaryKey(Expression):
1468    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1473class Into(Expression):
1474    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1477class From(Expression):
1478    @property
1479    def name(self) -> str:
1480        return self.this.name
1481
1482    @property
1483    def alias_or_name(self) -> str:
1484        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1487class Having(Expression):
1488    pass
key = 'having'
class Hint(Expression):
1491class Hint(Expression):
1492    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1495class JoinHint(Expression):
1496    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1499class Identifier(Expression):
1500    arg_types = {"this": True, "quoted": False}
1501
1502    @property
1503    def quoted(self) -> bool:
1504        return bool(self.args.get("quoted"))
1505
1506    @property
1507    def hashable_args(self) -> t.Any:
1508        return (self.this, self.quoted)
1509
1510    @property
1511    def output_name(self) -> str:
1512        return self.name
arg_types = {'this': True, 'quoted': False}
quoted: bool
hashable_args: Any
output_name: str

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

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

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

Append to or set the common table expressions.

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

The modified expression.

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

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

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

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

Append to or set the ON expressions.

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

The modified Join expression.

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

Append to or set the USING expressions.

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

The modified Join expression.

key = 'join'
class Lateral(UDTF):
1789class Lateral(UDTF):
1790    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
arg_types = {'this': True, 'view': False, 'outer': False, 'alias': False}
key = 'lateral'
class MatchRecognize(Expression):
1793class MatchRecognize(Expression):
1794    arg_types = {
1795        "partition_by": False,
1796        "order": False,
1797        "measures": False,
1798        "rows": False,
1799        "after": False,
1800        "pattern": False,
1801        "define": False,
1802        "alias": False,
1803    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1808class Final(Expression):
1809    pass
key = 'final'
class Offset(Expression):
1812class Offset(Expression):
1813    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1816class Order(Expression):
1817    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1822class Cluster(Order):
1823    pass
key = 'cluster'
class Distribute(Order):
1826class Distribute(Order):
1827    pass
key = 'distribute'
class Sort(Order):
1830class Sort(Order):
1831    pass
key = 'sort'
class Ordered(Expression):
1834class Ordered(Expression):
1835    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1838class Property(Expression):
1839    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1842class AlgorithmProperty(Property):
1843    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1846class AutoIncrementProperty(Property):
1847    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1850class BlockCompressionProperty(Property):
1851    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
arg_types = {'autotemp': False, 'always': False, 'default': True, 'manual': True, 'never': True}
key = 'blockcompressionproperty'
class CharacterSetProperty(Property):
1854class CharacterSetProperty(Property):
1855    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1858class ChecksumProperty(Property):
1859    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1862class CollateProperty(Property):
1863    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1866class CopyGrantsProperty(Property):
1867    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1870class DataBlocksizeProperty(Property):
1871    arg_types = {
1872        "size": False,
1873        "units": False,
1874        "minimum": False,
1875        "maximum": False,
1876        "default": False,
1877    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1880class DefinerProperty(Property):
1881    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1884class DistKeyProperty(Property):
1885    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1888class DistStyleProperty(Property):
1889    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1892class EngineProperty(Property):
1893    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1896class ToTableProperty(Property):
1897    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1900class ExecuteAsProperty(Property):
1901    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1904class ExternalProperty(Property):
1905    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1908class FallbackProperty(Property):
1909    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1912class FileFormatProperty(Property):
1913    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1916class FreespaceProperty(Property):
1917    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1920class InputOutputFormat(Expression):
1921    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1924class IsolatedLoadingProperty(Property):
1925    arg_types = {
1926        "no": True,
1927        "concurrent": True,
1928        "for_all": True,
1929        "for_insert": True,
1930        "for_none": True,
1931    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1934class JournalProperty(Property):
1935    arg_types = {
1936        "no": False,
1937        "dual": False,
1938        "before": False,
1939        "local": False,
1940        "after": False,
1941    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1944class LanguageProperty(Property):
1945    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1949class ClusteredByProperty(Property):
1950    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1953class DictProperty(Property):
1954    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1957class DictSubProperty(Property):
1958    pass
key = 'dictsubproperty'
class DictRange(Property):
1961class DictRange(Property):
1962    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1967class OnCluster(Property):
1968    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1971class LikeProperty(Property):
1972    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1975class LocationProperty(Property):
1976    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
1979class LockingProperty(Property):
1980    arg_types = {
1981        "this": False,
1982        "kind": True,
1983        "for_or_in": True,
1984        "lock_type": True,
1985        "override": False,
1986    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
1989class LogProperty(Property):
1990    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
1993class MaterializedProperty(Property):
1994    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
1997class MergeBlockRatioProperty(Property):
1998    arg_types = {"this": False, "no": False, "default": False, "percent": False}
arg_types = {'this': False, 'no': False, 'default': False, 'percent': False}
key = 'mergeblockratioproperty'
class NoPrimaryIndexProperty(Property):
2001class NoPrimaryIndexProperty(Property):
2002    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
2005class OnCommitProperty(Property):
2006    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2009class PartitionedByProperty(Property):
2010    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2013class ReturnsProperty(Property):
2014    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2017class RowFormatProperty(Property):
2018    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2021class RowFormatDelimitedProperty(Property):
2022    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2023    arg_types = {
2024        "fields": False,
2025        "escaped": False,
2026        "collection_items": False,
2027        "map_keys": False,
2028        "lines": False,
2029        "null": False,
2030        "serde": False,
2031    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2034class RowFormatSerdeProperty(Property):
2035    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatserdeproperty'
class SchemaCommentProperty(Property):
2038class SchemaCommentProperty(Property):
2039    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2042class SerdeProperties(Property):
2043    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2046class SetProperty(Property):
2047    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2050class SettingsProperty(Property):
2051    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2054class SortKeyProperty(Property):
2055    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2058class SqlSecurityProperty(Property):
2059    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2062class StabilityProperty(Property):
2063    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2066class TemporaryProperty(Property):
2067    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2070class TransientProperty(Property):
2071    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2074class VolatileProperty(Property):
2075    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2078class WithDataProperty(Property):
2079    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2082class WithJournalTableProperty(Property):
2083    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2086class Properties(Expression):
2087    arg_types = {"expressions": True}
2088
2089    NAME_TO_PROPERTY = {
2090        "ALGORITHM": AlgorithmProperty,
2091        "AUTO_INCREMENT": AutoIncrementProperty,
2092        "CHARACTER SET": CharacterSetProperty,
2093        "CLUSTERED_BY": ClusteredByProperty,
2094        "COLLATE": CollateProperty,
2095        "COMMENT": SchemaCommentProperty,
2096        "DEFINER": DefinerProperty,
2097        "DISTKEY": DistKeyProperty,
2098        "DISTSTYLE": DistStyleProperty,
2099        "ENGINE": EngineProperty,
2100        "EXECUTE AS": ExecuteAsProperty,
2101        "FORMAT": FileFormatProperty,
2102        "LANGUAGE": LanguageProperty,
2103        "LOCATION": LocationProperty,
2104        "PARTITIONED_BY": PartitionedByProperty,
2105        "RETURNS": ReturnsProperty,
2106        "ROW_FORMAT": RowFormatProperty,
2107        "SORTKEY": SortKeyProperty,
2108    }
2109
2110    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2111
2112    # CREATE property locations
2113    # Form: schema specified
2114    #   create [POST_CREATE]
2115    #     table a [POST_NAME]
2116    #     (b int) [POST_SCHEMA]
2117    #     with ([POST_WITH])
2118    #     index (b) [POST_INDEX]
2119    #
2120    # Form: alias selection
2121    #   create [POST_CREATE]
2122    #     table a [POST_NAME]
2123    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2124    #     index (c) [POST_INDEX]
2125    class Location(AutoName):
2126        POST_CREATE = auto()
2127        POST_NAME = auto()
2128        POST_SCHEMA = auto()
2129        POST_WITH = auto()
2130        POST_ALIAS = auto()
2131        POST_EXPRESSION = auto()
2132        POST_INDEX = auto()
2133        UNSUPPORTED = auto()
2134
2135    @classmethod
2136    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2137        expressions = []
2138        for key, value in properties_dict.items():
2139            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2140            if property_cls:
2141                expressions.append(property_cls(this=convert(value)))
2142            else:
2143                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2144
2145        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:
2135    @classmethod
2136    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2137        expressions = []
2138        for key, value in properties_dict.items():
2139            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2140            if property_cls:
2141                expressions.append(property_cls(this=convert(value)))
2142            else:
2143                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2144
2145        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2125    class Location(AutoName):
2126        POST_CREATE = auto()
2127        POST_NAME = auto()
2128        POST_SCHEMA = auto()
2129        POST_WITH = auto()
2130        POST_ALIAS = auto()
2131        POST_EXPRESSION = auto()
2132        POST_INDEX = auto()
2133        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):
2148class Qualify(Expression):
2149    pass
key = 'qualify'
class Return(Expression):
2153class Return(Expression):
2154    pass
key = 'return'
class Reference(Expression):
2157class Reference(Expression):
2158    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2161class Tuple(Expression):
2162    arg_types = {"expressions": False}
2163
2164    def isin(
2165        self,
2166        *expressions: t.Any,
2167        query: t.Optional[ExpOrStr] = None,
2168        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2169        copy: bool = True,
2170        **opts,
2171    ) -> In:
2172        return In(
2173            this=_maybe_copy(self, copy),
2174            expressions=[convert(e, copy=copy) for e in expressions],
2175            query=maybe_parse(query, copy=copy, **opts) if query else None,
2176            unnest=Unnest(
2177                expressions=[
2178                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2179                ]
2180            )
2181            if unnest
2182            else None,
2183        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, unnest: Union[str, sqlglot.expressions.Expression, NoneType, Collection[Union[str, sqlglot.expressions.Expression]]] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2164    def isin(
2165        self,
2166        *expressions: t.Any,
2167        query: t.Optional[ExpOrStr] = None,
2168        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2169        copy: bool = True,
2170        **opts,
2171    ) -> In:
2172        return In(
2173            this=_maybe_copy(self, copy),
2174            expressions=[convert(e, copy=copy) for e in expressions],
2175            query=maybe_parse(query, copy=copy, **opts) if query else None,
2176            unnest=Unnest(
2177                expressions=[
2178                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2179                ]
2180            )
2181            if unnest
2182            else None,
2183        )
key = 'tuple'
class Subqueryable(Unionable):
2186class Subqueryable(Unionable):
2187    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2188        """
2189        Convert this expression to an aliased expression that can be used as a Subquery.
2190
2191        Example:
2192            >>> subquery = Select().select("x").from_("tbl").subquery()
2193            >>> Select().select("x").from_(subquery).sql()
2194            'SELECT x FROM (SELECT x FROM tbl)'
2195
2196        Args:
2197            alias (str | Identifier): an optional alias for the subquery
2198            copy (bool): if `False`, modify this expression instance in-place.
2199
2200        Returns:
2201            Alias: the subquery
2202        """
2203        instance = _maybe_copy(self, copy)
2204        if not isinstance(alias, Expression):
2205            alias = TableAlias(this=to_identifier(alias)) if alias else None
2206
2207        return Subquery(this=instance, alias=alias)
2208
2209    def limit(
2210        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2211    ) -> Select:
2212        raise NotImplementedError
2213
2214    @property
2215    def ctes(self):
2216        with_ = self.args.get("with")
2217        if not with_:
2218            return []
2219        return with_.expressions
2220
2221    @property
2222    def selects(self) -> t.List[Expression]:
2223        raise NotImplementedError("Subqueryable objects must implement `selects`")
2224
2225    @property
2226    def named_selects(self) -> t.List[str]:
2227        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2228
2229    def with_(
2230        self,
2231        alias: ExpOrStr,
2232        as_: ExpOrStr,
2233        recursive: t.Optional[bool] = None,
2234        append: bool = True,
2235        dialect: DialectType = None,
2236        copy: bool = True,
2237        **opts,
2238    ) -> Subqueryable:
2239        """
2240        Append to or set the common table expressions.
2241
2242        Example:
2243            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2244            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2245
2246        Args:
2247            alias: the SQL code string to parse as the table name.
2248                If an `Expression` instance is passed, this is used as-is.
2249            as_: the SQL code string to parse as the table expression.
2250                If an `Expression` instance is passed, it will be used as-is.
2251            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2252            append: if `True`, add to any existing expressions.
2253                Otherwise, this resets the expressions.
2254            dialect: the dialect used to parse the input expression.
2255            copy: if `False`, modify this expression instance in-place.
2256            opts: other options to use to parse the input expressions.
2257
2258        Returns:
2259            The modified expression.
2260        """
2261        return _apply_cte_builder(
2262            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2263        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2187    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2188        """
2189        Convert this expression to an aliased expression that can be used as a Subquery.
2190
2191        Example:
2192            >>> subquery = Select().select("x").from_("tbl").subquery()
2193            >>> Select().select("x").from_(subquery).sql()
2194            'SELECT x FROM (SELECT x FROM tbl)'
2195
2196        Args:
2197            alias (str | Identifier): an optional alias for the subquery
2198            copy (bool): if `False`, modify this expression instance in-place.
2199
2200        Returns:
2201            Alias: the subquery
2202        """
2203        instance = _maybe_copy(self, copy)
2204        if not isinstance(alias, Expression):
2205            alias = TableAlias(this=to_identifier(alias)) if alias else None
2206
2207        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:
2209    def limit(
2210        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2211    ) -> Select:
2212        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:
2229    def with_(
2230        self,
2231        alias: ExpOrStr,
2232        as_: ExpOrStr,
2233        recursive: t.Optional[bool] = None,
2234        append: bool = True,
2235        dialect: DialectType = None,
2236        copy: bool = True,
2237        **opts,
2238    ) -> Subqueryable:
2239        """
2240        Append to or set the common table expressions.
2241
2242        Example:
2243            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2244            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2245
2246        Args:
2247            alias: the SQL code string to parse as the table name.
2248                If an `Expression` instance is passed, this is used as-is.
2249            as_: the SQL code string to parse as the table expression.
2250                If an `Expression` instance is passed, it will be used as-is.
2251            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2252            append: if `True`, add to any existing expressions.
2253                Otherwise, this resets the expressions.
2254            dialect: the dialect used to parse the input expression.
2255            copy: if `False`, modify this expression instance in-place.
2256            opts: other options to use to parse the input expressions.
2257
2258        Returns:
2259            The modified expression.
2260        """
2261        return _apply_cte_builder(
2262            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2263        )

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):
2290class WithTableHint(Expression):
2291    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2295class IndexTableHint(Expression):
2296    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2299class Table(Expression):
2300    arg_types = {
2301        "this": True,
2302        "alias": False,
2303        "db": False,
2304        "catalog": False,
2305        "laterals": False,
2306        "joins": False,
2307        "pivots": False,
2308        "hints": False,
2309        "system_time": False,
2310    }
2311
2312    @property
2313    def name(self) -> str:
2314        if isinstance(self.this, Func):
2315            return ""
2316        return self.this.name
2317
2318    @property
2319    def db(self) -> str:
2320        return self.text("db")
2321
2322    @property
2323    def catalog(self) -> str:
2324        return self.text("catalog")
2325
2326    @property
2327    def selects(self) -> t.List[Expression]:
2328        return []
2329
2330    @property
2331    def named_selects(self) -> t.List[str]:
2332        return []
2333
2334    @property
2335    def parts(self) -> t.List[Identifier]:
2336        """Return the parts of a table in order catalog, db, table."""
2337        parts: t.List[Identifier] = []
2338
2339        for arg in ("catalog", "db", "this"):
2340            part = self.args.get(arg)
2341
2342            if isinstance(part, Identifier):
2343                parts.append(part)
2344            elif isinstance(part, Dot):
2345                parts.extend(part.flatten())
2346
2347        return parts
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False}
name: str
db: str
catalog: str
named_selects: List[str]

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

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

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

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:
2546    def group_by(
2547        self,
2548        *expressions: t.Optional[ExpOrStr],
2549        append: bool = True,
2550        dialect: DialectType = None,
2551        copy: bool = True,
2552        **opts,
2553    ) -> Select:
2554        """
2555        Set the GROUP BY expression.
2556
2557        Example:
2558            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2559            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2560
2561        Args:
2562            *expressions: the SQL code strings to parse.
2563                If a `Group` instance is passed, this is used as-is.
2564                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2565                If nothing is passed in then a group by is not applied to the expression
2566            append: if `True`, add to any existing expressions.
2567                Otherwise, this flattens all the `Group` expression into a single expression.
2568            dialect: the dialect used to parse the input expression.
2569            copy: if `False`, modify this expression instance in-place.
2570            opts: other options to use to parse the input expressions.
2571
2572        Returns:
2573            The modified Select expression.
2574        """
2575        if not expressions:
2576            return self if not copy else self.copy()
2577
2578        return _apply_child_list_builder(
2579            *expressions,
2580            instance=self,
2581            arg="group",
2582            append=append,
2583            copy=copy,
2584            prefix="GROUP BY",
2585            into=Group,
2586            dialect=dialect,
2587            **opts,
2588        )

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

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

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

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

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

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:
2776    def select(
2777        self,
2778        *expressions: t.Optional[ExpOrStr],
2779        append: bool = True,
2780        dialect: DialectType = None,
2781        copy: bool = True,
2782        **opts,
2783    ) -> Select:
2784        """
2785        Append to or set the SELECT expressions.
2786
2787        Example:
2788            >>> Select().select("x", "y").sql()
2789            'SELECT x, y'
2790
2791        Args:
2792            *expressions: the SQL code strings to parse.
2793                If an `Expression` instance is passed, it will be used as-is.
2794            append: if `True`, add to any existing expressions.
2795                Otherwise, this resets the expressions.
2796            dialect: the dialect used to parse the input expressions.
2797            copy: if `False`, modify this expression instance in-place.
2798            opts: other options to use to parse the input expressions.
2799
2800        Returns:
2801            The modified Select expression.
2802        """
2803        return _apply_list_builder(
2804            *expressions,
2805            instance=self,
2806            arg="expressions",
2807            append=append,
2808            dialect=dialect,
2809            copy=copy,
2810            **opts,
2811        )

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

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

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

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

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

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:
3132    def lock(self, update: bool = True, copy: bool = True) -> Select:
3133        """
3134        Set the locking read mode for this expression.
3135
3136        Examples:
3137            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3138            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3139
3140            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3141            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3142
3143        Args:
3144            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3145            copy: if `False`, modify this expression instance in-place.
3146
3147        Returns:
3148            The modified expression.
3149        """
3150        inst = _maybe_copy(self, copy)
3151        inst.set("locks", [Lock(update=update)])
3152
3153        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:
3155    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3156        """
3157        Set hints for this expression.
3158
3159        Examples:
3160            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3161            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3162
3163        Args:
3164            hints: The SQL code strings to parse as the hints.
3165                If an `Expression` instance is passed, it will be used as-is.
3166            dialect: The dialect used to parse the hints.
3167            copy: If `False`, modify this expression instance in-place.
3168
3169        Returns:
3170            The modified expression.
3171        """
3172        inst = _maybe_copy(self, copy)
3173        inst.set(
3174            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3175        )
3176
3177        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):
3192class Subquery(DerivedTable, Unionable):
3193    arg_types = {
3194        "this": True,
3195        "alias": False,
3196        "with": False,
3197        **QUERY_MODIFIERS,
3198    }
3199
3200    def unnest(self):
3201        """
3202        Returns the first non subquery.
3203        """
3204        expression = self
3205        while isinstance(expression, Subquery):
3206            expression = expression.this
3207        return expression
3208
3209    @property
3210    def is_star(self) -> bool:
3211        return self.this.is_star
3212
3213    @property
3214    def output_name(self) -> str:
3215        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):
3200    def unnest(self):
3201        """
3202        Returns the first non subquery.
3203        """
3204        expression = self
3205        while isinstance(expression, Subquery):
3206            expression = expression.this
3207        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):
3218class TableSample(Expression):
3219    arg_types = {
3220        "this": False,
3221        "method": False,
3222        "bucket_numerator": False,
3223        "bucket_denominator": False,
3224        "bucket_field": False,
3225        "percent": False,
3226        "rows": False,
3227        "size": False,
3228        "seed": False,
3229        "kind": False,
3230    }
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):
3233class Tag(Expression):
3234    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3235
3236    arg_types = {
3237        "this": False,
3238        "prefix": False,
3239        "postfix": False,
3240    }

Tags are used for generating arbitrary sql like SELECT x.

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

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3614class DPipe(Binary):
3615    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3618class SafeDPipe(DPipe):
3619    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3622class EQ(Binary, Predicate):
3623    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3626class NullSafeEQ(Binary, Predicate):
3627    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3630class NullSafeNEQ(Binary, Predicate):
3631    pass
key = 'nullsafeneq'
class Distance(Binary):
3634class Distance(Binary):
3635    pass
key = 'distance'
class Escape(Binary):
3638class Escape(Binary):
3639    pass
key = 'escape'
class Glob(Binary, Predicate):
3642class Glob(Binary, Predicate):
3643    pass
key = 'glob'
class GT(Binary, Predicate):
3646class GT(Binary, Predicate):
3647    pass
key = 'gt'
class GTE(Binary, Predicate):
3650class GTE(Binary, Predicate):
3651    pass
key = 'gte'
class ILike(Binary, Predicate):
3654class ILike(Binary, Predicate):
3655    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3658class ILikeAny(Binary, Predicate):
3659    pass
key = 'ilikeany'
class IntDiv(Binary):
3662class IntDiv(Binary):
3663    pass
key = 'intdiv'
class Is(Binary, Predicate):
3666class Is(Binary, Predicate):
3667    pass
key = 'is'
class Kwarg(Binary):
3670class Kwarg(Binary):
3671    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3674class Like(Binary, Predicate):
3675    pass
key = 'like'
class LikeAny(Binary, Predicate):
3678class LikeAny(Binary, Predicate):
3679    pass
key = 'likeany'
class LT(Binary, Predicate):
3682class LT(Binary, Predicate):
3683    pass
key = 'lt'
class LTE(Binary, Predicate):
3686class LTE(Binary, Predicate):
3687    pass
key = 'lte'
class Mod(Binary):
3690class Mod(Binary):
3691    pass
key = 'mod'
class Mul(Binary):
3694class Mul(Binary):
3695    pass
key = 'mul'
class NEQ(Binary, Predicate):
3698class NEQ(Binary, Predicate):
3699    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3702class SimilarTo(Binary, Predicate):
3703    pass
key = 'similarto'
class Slice(Binary):
3706class Slice(Binary):
3707    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3710class Sub(Binary):
3711    pass
key = 'sub'
class ArrayOverlaps(Binary):
3714class ArrayOverlaps(Binary):
3715    pass
key = 'arrayoverlaps'
class Unary(Condition):
3720class Unary(Condition):
3721    pass
key = 'unary'
class BitwiseNot(Unary):
3724class BitwiseNot(Unary):
3725    pass
key = 'bitwisenot'
class Not(Unary):
3728class Not(Unary):
3729    pass
key = 'not'
class Paren(Unary):
3732class Paren(Unary):
3733    arg_types = {"this": True, "with": False}
3734
3735    @property
3736    def output_name(self) -> str:
3737        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):
3740class Neg(Unary):
3741    pass
key = 'neg'
class Alias(Expression):
3744class Alias(Expression):
3745    arg_types = {"this": True, "alias": False}
3746
3747    @property
3748    def output_name(self) -> str:
3749        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):
3752class Aliases(Expression):
3753    arg_types = {"this": True, "expressions": True}
3754
3755    @property
3756    def aliases(self):
3757        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3760class AtTimeZone(Expression):
3761    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3764class Between(Predicate):
3765    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3768class Bracket(Condition):
3769    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3772class SafeBracket(Bracket):
3773    """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):
3776class Distinct(Expression):
3777    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3780class In(Predicate):
3781    arg_types = {
3782        "this": True,
3783        "expressions": False,
3784        "query": False,
3785        "unnest": False,
3786        "field": False,
3787        "is_global": False,
3788    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3791class TimeUnit(Expression):
3792    """Automatically converts unit arg into a var."""
3793
3794    arg_types = {"unit": False}
3795
3796    def __init__(self, **args):
3797        unit = args.get("unit")
3798        if isinstance(unit, (Column, Literal)):
3799            args["unit"] = Var(this=unit.name)
3800        elif isinstance(unit, Week):
3801            unit.set("this", Var(this=unit.this.name))
3802
3803        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3796    def __init__(self, **args):
3797        unit = args.get("unit")
3798        if isinstance(unit, (Column, Literal)):
3799            args["unit"] = Var(this=unit.name)
3800        elif isinstance(unit, Week):
3801            unit.set("this", Var(this=unit.this.name))
3802
3803        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3806class Interval(TimeUnit):
3807    arg_types = {"this": False, "unit": False}
3808
3809    @property
3810    def unit(self) -> t.Optional[Var]:
3811        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3814class IgnoreNulls(Expression):
3815    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3818class RespectNulls(Expression):
3819    pass
key = 'respectnulls'
class Func(Condition):
3823class Func(Condition):
3824    """
3825    The base class for all function expressions.
3826
3827    Attributes:
3828        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3829            treated as a variable length argument and the argument's value will be stored as a list.
3830        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3831            for this function expression. These values are used to map this node to a name during parsing
3832            as well as to provide the function's name during SQL string generation. By default the SQL
3833            name is set to the expression's class name transformed to snake case.
3834    """
3835
3836    is_var_len_args = False
3837
3838    @classmethod
3839    def from_arg_list(cls, args):
3840        if cls.is_var_len_args:
3841            all_arg_keys = list(cls.arg_types)
3842            # If this function supports variable length argument treat the last argument as such.
3843            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3844            num_non_var = len(non_var_len_arg_keys)
3845
3846            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3847            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3848        else:
3849            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3850
3851        return cls(**args_dict)
3852
3853    @classmethod
3854    def sql_names(cls):
3855        if cls is Func:
3856            raise NotImplementedError(
3857                "SQL name is only supported by concrete function implementations"
3858            )
3859        if "_sql_names" not in cls.__dict__:
3860            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3861        return cls._sql_names
3862
3863    @classmethod
3864    def sql_name(cls):
3865        return cls.sql_names()[0]
3866
3867    @classmethod
3868    def default_parser_mappings(cls):
3869        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):
3838    @classmethod
3839    def from_arg_list(cls, args):
3840        if cls.is_var_len_args:
3841            all_arg_keys = list(cls.arg_types)
3842            # If this function supports variable length argument treat the last argument as such.
3843            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3844            num_non_var = len(non_var_len_arg_keys)
3845
3846            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3847            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3848        else:
3849            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3850
3851        return cls(**args_dict)
@classmethod
def sql_names(cls):
3853    @classmethod
3854    def sql_names(cls):
3855        if cls is Func:
3856            raise NotImplementedError(
3857                "SQL name is only supported by concrete function implementations"
3858            )
3859        if "_sql_names" not in cls.__dict__:
3860            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3861        return cls._sql_names
@classmethod
def sql_name(cls):
3863    @classmethod
3864    def sql_name(cls):
3865        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3867    @classmethod
3868    def default_parser_mappings(cls):
3869        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3872class AggFunc(Func):
3873    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3876class ParameterizedAgg(AggFunc):
3877    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3880class Abs(Func):
3881    pass
key = 'abs'
class Anonymous(Func):
3884class Anonymous(Func):
3885    arg_types = {"this": True, "expressions": False}
3886    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3891class Hll(AggFunc):
3892    arg_types = {"this": True, "expressions": False}
3893    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3896class ApproxDistinct(AggFunc):
3897    arg_types = {"this": True, "accuracy": False}
3898    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3901class Array(Func):
3902    arg_types = {"expressions": False}
3903    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3907class ToChar(Func):
3908    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3911class GenerateSeries(Func):
3912    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3915class ArrayAgg(AggFunc):
3916    pass
key = 'arrayagg'
class ArrayAll(Func):
3919class ArrayAll(Func):
3920    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3923class ArrayAny(Func):
3924    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3927class ArrayConcat(Func):
3928    arg_types = {"this": True, "expressions": False}
3929    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3932class ArrayContains(Binary, Func):
3933    pass
key = 'arraycontains'
class ArrayContained(Binary):
3936class ArrayContained(Binary):
3937    pass
key = 'arraycontained'
class ArrayFilter(Func):
3940class ArrayFilter(Func):
3941    arg_types = {"this": True, "expression": True}
3942    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3945class ArrayJoin(Func):
3946    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3949class ArraySize(Func):
3950    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3953class ArraySort(Func):
3954    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3957class ArraySum(Func):
3958    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3961class ArrayUnionAgg(AggFunc):
3962    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3965class Avg(AggFunc):
3966    pass
key = 'avg'
class AnyValue(AggFunc):
3969class AnyValue(AggFunc):
3970    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
3973class Case(Func):
3974    arg_types = {"this": False, "ifs": True, "default": False}
3975
3976    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3977        instance = _maybe_copy(self, copy)
3978        instance.append(
3979            "ifs",
3980            If(
3981                this=maybe_parse(condition, copy=copy, **opts),
3982                true=maybe_parse(then, copy=copy, **opts),
3983            ),
3984        )
3985        return instance
3986
3987    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3988        instance = _maybe_copy(self, copy)
3989        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3990        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:
3976    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3977        instance = _maybe_copy(self, copy)
3978        instance.append(
3979            "ifs",
3980            If(
3981                this=maybe_parse(condition, copy=copy, **opts),
3982                true=maybe_parse(then, copy=copy, **opts),
3983            ),
3984        )
3985        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3987    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3988        instance = _maybe_copy(self, copy)
3989        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3990        return instance
key = 'case'
class Cast(Func):
3993class Cast(Func):
3994    arg_types = {"this": True, "to": True, "format": False}
3995
3996    @property
3997    def name(self) -> str:
3998        return self.this.name
3999
4000    @property
4001    def to(self) -> DataType:
4002        return self.args["to"]
4003
4004    @property
4005    def output_name(self) -> str:
4006        return self.name
4007
4008    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4009        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:
4008    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4009        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
4012class CastToStrType(Func):
4013    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
4016class Collate(Binary):
4017    pass
key = 'collate'
class TryCast(Cast):
4020class TryCast(Cast):
4021    pass
key = 'trycast'
class Ceil(Func):
4024class Ceil(Func):
4025    arg_types = {"this": True, "decimals": False}
4026    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4029class Coalesce(Func):
4030    arg_types = {"this": True, "expressions": False}
4031    is_var_len_args = True
4032    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4035class Concat(Func):
4036    arg_types = {"expressions": True}
4037    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4040class SafeConcat(Concat):
4041    pass
key = 'safeconcat'
class ConcatWs(Concat):
4044class ConcatWs(Concat):
4045    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4048class Count(AggFunc):
4049    arg_types = {"this": False, "expressions": False}
4050    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4053class CountIf(AggFunc):
4054    pass
key = 'countif'
class CurrentDate(Func):
4057class CurrentDate(Func):
4058    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4061class CurrentDatetime(Func):
4062    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4065class CurrentTime(Func):
4066    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4069class CurrentTimestamp(Func):
4070    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4073class CurrentUser(Func):
4074    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4077class DateAdd(Func, TimeUnit):
4078    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4081class DateSub(Func, TimeUnit):
4082    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4085class DateDiff(Func, TimeUnit):
4086    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4087    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4090class DateTrunc(Func):
4091    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4094class DatetimeAdd(Func, TimeUnit):
4095    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4098class DatetimeSub(Func, TimeUnit):
4099    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4102class DatetimeDiff(Func, TimeUnit):
4103    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4106class DatetimeTrunc(Func, TimeUnit):
4107    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4110class DayOfWeek(Func):
4111    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4114class DayOfMonth(Func):
4115    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4118class DayOfYear(Func):
4119    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4122class WeekOfYear(Func):
4123    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4126class MonthsBetween(Func):
4127    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4130class LastDateOfMonth(Func):
4131    pass
key = 'lastdateofmonth'
class Extract(Func):
4134class Extract(Func):
4135    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4138class TimestampAdd(Func, TimeUnit):
4139    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4142class TimestampSub(Func, TimeUnit):
4143    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4146class TimestampDiff(Func, TimeUnit):
4147    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4150class TimestampTrunc(Func, TimeUnit):
4151    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4154class TimeAdd(Func, TimeUnit):
4155    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4158class TimeSub(Func, TimeUnit):
4159    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4162class TimeDiff(Func, TimeUnit):
4163    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4166class TimeTrunc(Func, TimeUnit):
4167    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4170class DateFromParts(Func):
4171    _sql_names = ["DATEFROMPARTS"]
4172    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4175class DateStrToDate(Func):
4176    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4179class DateToDateStr(Func):
4180    pass
key = 'datetodatestr'
class DateToDi(Func):
4183class DateToDi(Func):
4184    pass
key = 'datetodi'
class Date(Func):
4188class Date(Func):
4189    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4192class Day(Func):
4193    pass
key = 'day'
class Decode(Func):
4196class Decode(Func):
4197    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4200class DiToDate(Func):
4201    pass
key = 'ditodate'
class Encode(Func):
4204class Encode(Func):
4205    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4208class Exp(Func):
4209    pass
key = 'exp'
class Explode(Func):
4212class Explode(Func):
4213    pass
key = 'explode'
class Floor(Func):
4216class Floor(Func):
4217    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4220class FromBase64(Func):
4221    pass
key = 'frombase64'
class ToBase64(Func):
4224class ToBase64(Func):
4225    pass
key = 'tobase64'
class Greatest(Func):
4228class Greatest(Func):
4229    arg_types = {"this": True, "expressions": False}
4230    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4233class GroupConcat(Func):
4234    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4237class Hex(Func):
4238    pass
key = 'hex'
class If(Func):
4241class If(Func):
4242    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4245class Initcap(Func):
4246    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4249class JSONKeyValue(Expression):
4250    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4253class JSONObject(Func):
4254    arg_types = {
4255        "expressions": False,
4256        "null_handling": False,
4257        "unique_keys": False,
4258        "return_type": False,
4259        "format_json": False,
4260        "encoding": False,
4261    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4264class OpenJSONColumnDef(Expression):
4265    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):
4268class OpenJSON(Func):
4269    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4272class JSONBContains(Binary):
4273    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4276class JSONExtract(Binary, Func):
4277    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4280class JSONExtractScalar(JSONExtract):
4281    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4284class JSONBExtract(JSONExtract):
4285    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4288class JSONBExtractScalar(JSONExtract):
4289    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4292class JSONFormat(Func):
4293    arg_types = {"this": False, "options": False}
4294    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4298class JSONArrayContains(Binary, Predicate, Func):
4299    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4302class Least(Func):
4303    arg_types = {"this": True, "expressions": False}
4304    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4307class Left(Func):
4308    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4315class Length(Func):
4316    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4319class Levenshtein(Func):
4320    arg_types = {
4321        "this": True,
4322        "expression": False,
4323        "ins_cost": False,
4324        "del_cost": False,
4325        "sub_cost": False,
4326    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4329class Ln(Func):
4330    pass
key = 'ln'
class Log(Func):
4333class Log(Func):
4334    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4337class Log2(Func):
4338    pass
key = 'log2'
class Log10(Func):
4341class Log10(Func):
4342    pass
key = 'log10'
class LogicalOr(AggFunc):
4345class LogicalOr(AggFunc):
4346    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4349class LogicalAnd(AggFunc):
4350    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4353class Lower(Func):
4354    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4357class Map(Func):
4358    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4361class MapFromEntries(Func):
4362    pass
key = 'mapfromentries'
class StarMap(Func):
4365class StarMap(Func):
4366    pass
key = 'starmap'
class VarMap(Func):
4369class VarMap(Func):
4370    arg_types = {"keys": True, "values": True}
4371    is_var_len_args = True
4372
4373    @property
4374    def keys(self) -> t.List[Expression]:
4375        return self.args["keys"].expressions
4376
4377    @property
4378    def values(self) -> t.List[Expression]:
4379        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4383class MatchAgainst(Func):
4384    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4387class Max(AggFunc):
4388    arg_types = {"this": True, "expressions": False}
4389    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4392class MD5(Func):
4393    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4397class MD5Digest(Func):
4398    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4401class Min(AggFunc):
4402    arg_types = {"this": True, "expressions": False}
4403    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4406class Month(Func):
4407    pass
key = 'month'
class Nvl2(Func):
4410class Nvl2(Func):
4411    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4414class Posexplode(Func):
4415    pass
key = 'posexplode'
class Pow(Binary, Func):
4418class Pow(Binary, Func):
4419    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4422class PercentileCont(AggFunc):
4423    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4426class PercentileDisc(AggFunc):
4427    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4430class Quantile(AggFunc):
4431    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4434class ApproxQuantile(Quantile):
4435    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):
4438class RangeN(Func):
4439    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4442class ReadCSV(Func):
4443    _sql_names = ["READ_CSV"]
4444    is_var_len_args = True
4445    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4448class Reduce(Func):
4449    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):
4452class RegexpExtract(Func):
4453    arg_types = {
4454        "this": True,
4455        "expression": True,
4456        "position": False,
4457        "occurrence": False,
4458        "parameters": False,
4459        "group": False,
4460    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4463class RegexpReplace(Func):
4464    arg_types = {
4465        "this": True,
4466        "expression": True,
4467        "replacement": True,
4468        "position": False,
4469        "occurrence": False,
4470        "parameters": False,
4471    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Func):
4474class RegexpLike(Func):
4475    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4478class RegexpILike(Func):
4479    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4484class RegexpSplit(Func):
4485    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4488class Repeat(Func):
4489    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4492class Round(Func):
4493    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4496class RowNumber(Func):
4497    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4500class SafeDivide(Func):
4501    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4504class SetAgg(AggFunc):
4505    pass
key = 'setagg'
class SHA(Func):
4508class SHA(Func):
4509    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4512class SHA2(Func):
4513    _sql_names = ["SHA2"]
4514    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4517class SortArray(Func):
4518    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4521class Split(Func):
4522    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4527class Substring(Func):
4528    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4531class StandardHash(Func):
4532    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4535class StrPosition(Func):
4536    arg_types = {
4537        "this": True,
4538        "substr": True,
4539        "position": False,
4540        "instance": False,
4541    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4544class StrToDate(Func):
4545    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4548class StrToTime(Func):
4549    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4554class StrToUnix(Func):
4555    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4558class NumberToStr(Func):
4559    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4562class FromBase(Func):
4563    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4566class Struct(Func):
4567    arg_types = {"expressions": True}
4568    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4571class StructExtract(Func):
4572    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4575class Sum(AggFunc):
4576    pass
key = 'sum'
class Sqrt(Func):
4579class Sqrt(Func):
4580    pass
key = 'sqrt'
class Stddev(AggFunc):
4583class Stddev(AggFunc):
4584    pass
key = 'stddev'
class StddevPop(AggFunc):
4587class StddevPop(AggFunc):
4588    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4591class StddevSamp(AggFunc):
4592    pass
key = 'stddevsamp'
class TimeToStr(Func):
4595class TimeToStr(Func):
4596    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4599class TimeToTimeStr(Func):
4600    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4603class TimeToUnix(Func):
4604    pass
key = 'timetounix'
class TimeStrToDate(Func):
4607class TimeStrToDate(Func):
4608    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4611class TimeStrToTime(Func):
4612    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4615class TimeStrToUnix(Func):
4616    pass
key = 'timestrtounix'
class Trim(Func):
4619class Trim(Func):
4620    arg_types = {
4621        "this": True,
4622        "expression": False,
4623        "position": False,
4624        "collation": False,
4625    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4628class TsOrDsAdd(Func, TimeUnit):
4629    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4632class TsOrDsToDateStr(Func):
4633    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4636class TsOrDsToDate(Func):
4637    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4640class TsOrDiToDi(Func):
4641    pass
key = 'tsorditodi'
class Unhex(Func):
4644class Unhex(Func):
4645    pass
key = 'unhex'
class UnixToStr(Func):
4648class UnixToStr(Func):
4649    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4654class UnixToTime(Func):
4655    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4656
4657    SECONDS = Literal.string("seconds")
4658    MILLIS = Literal.string("millis")
4659    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):
4662class UnixToTimeStr(Func):
4663    pass
key = 'unixtotimestr'
class Upper(Func):
4666class Upper(Func):
4667    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4670class Variance(AggFunc):
4671    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4674class VariancePop(AggFunc):
4675    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4678class Week(Func):
4679    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4682class XMLTable(Func):
4683    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):
4686class Year(Func):
4687    pass
key = 'year'
class Use(Expression):
4690class Use(Expression):
4691    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4694class Merge(Expression):
4695    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):
4698class When(Func):
4699    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):
4704class NextValueFor(Func):
4705    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.JSONArrayContains'>, <class 'sqlglot.expressions.JSONBExtract'>, <class 'sqlglot.expressions.JSONBExtractScalar'>, <class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.JSONExtractScalar'>, <class 'sqlglot.expressions.JSONFormat'>, <class 'sqlglot.expressions.JSONObject'>, <class 'sqlglot.expressions.LastDateOfMonth'>, <class 'sqlglot.expressions.Least'>, <class 'sqlglot.expressions.Left'>, <class 'sqlglot.expressions.Length'>, <class 'sqlglot.expressions.Levenshtein'>, <class 'sqlglot.expressions.Ln'>, <class 'sqlglot.expressions.Log'>, <class 'sqlglot.expressions.Log10'>, <class 'sqlglot.expressions.Log2'>, <class 'sqlglot.expressions.LogicalAnd'>, <class 'sqlglot.expressions.LogicalOr'>, <class 'sqlglot.expressions.Lower'>, <class 'sqlglot.expressions.MD5'>, <class 'sqlglot.expressions.MD5Digest'>, <class 'sqlglot.expressions.Map'>, <class 'sqlglot.expressions.MapFromEntries'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <class 'sqlglot.expressions.MonthsBetween'>, <class 'sqlglot.expressions.NextValueFor'>, <class 'sqlglot.expressions.NumberToStr'>, <class 'sqlglot.expressions.Nvl2'>, <class 'sqlglot.expressions.OpenJSON'>, <class 'sqlglot.expressions.ParameterizedAgg'>, <class 'sqlglot.expressions.PercentileCont'>, <class 'sqlglot.expressions.PercentileDisc'>, <class 'sqlglot.expressions.Posexplode'>, <class 'sqlglot.expressions.Pow'>, <class 'sqlglot.expressions.Quantile'>, <class 'sqlglot.expressions.RangeN'>, <class 'sqlglot.expressions.ReadCSV'>, <class 'sqlglot.expressions.Reduce'>, <class 'sqlglot.expressions.RegexpExtract'>, <class 'sqlglot.expressions.RegexpILike'>, <class 'sqlglot.expressions.RegexpLike'>, <class 'sqlglot.expressions.RegexpReplace'>, <class 'sqlglot.expressions.RegexpSplit'>, <class 'sqlglot.expressions.Repeat'>, <class 'sqlglot.expressions.Right'>, <class 'sqlglot.expressions.Round'>, <class 'sqlglot.expressions.RowNumber'>, <class 'sqlglot.expressions.SHA'>, <class 'sqlglot.expressions.SHA2'>, <class 'sqlglot.expressions.SafeConcat'>, <class 'sqlglot.expressions.SafeDivide'>, <class 'sqlglot.expressions.SetAgg'>, <class 'sqlglot.expressions.SortArray'>, <class 'sqlglot.expressions.Split'>, <class 'sqlglot.expressions.Sqrt'>, <class 'sqlglot.expressions.StandardHash'>, <class 'sqlglot.expressions.StarMap'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.Trim'>, <class 'sqlglot.expressions.TryCast'>, <class 'sqlglot.expressions.TsOrDiToDi'>, <class 'sqlglot.expressions.TsOrDsAdd'>, <class 'sqlglot.expressions.TsOrDsToDate'>, <class 'sqlglot.expressions.TsOrDsToDateStr'>, <class 'sqlglot.expressions.Unhex'>, <class 'sqlglot.expressions.UnixToStr'>, <class 'sqlglot.expressions.UnixToTime'>, <class 'sqlglot.expressions.UnixToTimeStr'>, <class 'sqlglot.expressions.Upper'>, <class 'sqlglot.expressions.VarMap'>, <class 'sqlglot.expressions.Variance'>, <class 'sqlglot.expressions.VariancePop'>, <class 'sqlglot.expressions.Week'>, <class 'sqlglot.expressions.WeekOfYear'>, <class 'sqlglot.expressions.When'>, <class 'sqlglot.expressions.XMLTable'>, <class 'sqlglot.expressions.Year'>]
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4742def maybe_parse(
4743    sql_or_expression: ExpOrStr,
4744    *,
4745    into: t.Optional[IntoType] = None,
4746    dialect: DialectType = None,
4747    prefix: t.Optional[str] = None,
4748    copy: bool = False,
4749    **opts,
4750) -> Expression:
4751    """Gracefully handle a possible string or expression.
4752
4753    Example:
4754        >>> maybe_parse("1")
4755        (LITERAL this: 1, is_string: False)
4756        >>> maybe_parse(to_identifier("x"))
4757        (IDENTIFIER this: x, quoted: False)
4758
4759    Args:
4760        sql_or_expression: the SQL code string or an expression
4761        into: the SQLGlot Expression to parse into
4762        dialect: the dialect used to parse the input expressions (in the case that an
4763            input expression is a SQL string).
4764        prefix: a string to prefix the sql with before it gets parsed
4765            (automatically includes a space)
4766        copy: whether or not to copy the expression.
4767        **opts: other options to use to parse the input expressions (again, in the case
4768            that an input expression is a SQL string).
4769
4770    Returns:
4771        Expression: the parsed or given expression.
4772    """
4773    if isinstance(sql_or_expression, Expression):
4774        if copy:
4775            return sql_or_expression.copy()
4776        return sql_or_expression
4777
4778    if sql_or_expression is None:
4779        raise ParseError(f"SQL cannot be None")
4780
4781    import sqlglot
4782
4783    sql = str(sql_or_expression)
4784    if prefix:
4785        sql = f"{prefix} {sql}"
4786
4787    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:
4971def union(
4972    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4973) -> Union:
4974    """
4975    Initializes a syntax tree from one UNION expression.
4976
4977    Example:
4978        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4979        'SELECT * FROM foo UNION SELECT * FROM bla'
4980
4981    Args:
4982        left: the SQL code string corresponding to the left-hand side.
4983            If an `Expression` instance is passed, it will be used as-is.
4984        right: the SQL code string corresponding to the right-hand side.
4985            If an `Expression` instance is passed, it will be used as-is.
4986        distinct: set the DISTINCT flag if and only if this is true.
4987        dialect: the dialect used to parse the input expression.
4988        opts: other options to use to parse the input expressions.
4989
4990    Returns:
4991        The new Union instance.
4992    """
4993    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4994    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4995
4996    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:
4999def intersect(
5000    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5001) -> Intersect:
5002    """
5003    Initializes a syntax tree from one INTERSECT expression.
5004
5005    Example:
5006        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5007        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5008
5009    Args:
5010        left: the SQL code string corresponding to the left-hand side.
5011            If an `Expression` instance is passed, it will be used as-is.
5012        right: the SQL code string corresponding to the right-hand side.
5013            If an `Expression` instance is passed, it will be used as-is.
5014        distinct: set the DISTINCT flag if and only if this is true.
5015        dialect: the dialect used to parse the input expression.
5016        opts: other options to use to parse the input expressions.
5017
5018    Returns:
5019        The new Intersect instance.
5020    """
5021    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5022    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5023
5024    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:
5027def except_(
5028    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5029) -> Except:
5030    """
5031    Initializes a syntax tree from one EXCEPT expression.
5032
5033    Example:
5034        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5035        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5036
5037    Args:
5038        left: the SQL code string corresponding to the left-hand side.
5039            If an `Expression` instance is passed, it will be used as-is.
5040        right: the SQL code string corresponding to the right-hand side.
5041            If an `Expression` instance is passed, it will be used as-is.
5042        distinct: set the DISTINCT flag if and only if this is true.
5043        dialect: the dialect used to parse the input expression.
5044        opts: other options to use to parse the input expressions.
5045
5046    Returns:
5047        The new Except instance.
5048    """
5049    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5050    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5051
5052    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:
5055def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5056    """
5057    Initializes a syntax tree from one or multiple SELECT expressions.
5058
5059    Example:
5060        >>> select("col1", "col2").from_("tbl").sql()
5061        'SELECT col1, col2 FROM tbl'
5062
5063    Args:
5064        *expressions: the SQL code string to parse as the expressions of a
5065            SELECT statement. If an Expression instance is passed, this is used as-is.
5066        dialect: the dialect used to parse the input expressions (in the case that an
5067            input expression is a SQL string).
5068        **opts: other options to use to parse the input expressions (again, in the case
5069            that an input expression is a SQL string).
5070
5071    Returns:
5072        Select: the syntax tree for the SELECT statement.
5073    """
5074    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:
5077def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5078    """
5079    Initializes a syntax tree from a FROM expression.
5080
5081    Example:
5082        >>> from_("tbl").select("col1", "col2").sql()
5083        'SELECT col1, col2 FROM tbl'
5084
5085    Args:
5086        *expression: the SQL code string to parse as the FROM expressions of a
5087            SELECT statement. If an Expression instance is passed, this is used as-is.
5088        dialect: the dialect used to parse the input expression (in the case that the
5089            input expression is a SQL string).
5090        **opts: other options to use to parse the input expressions (again, in the case
5091            that the input expression is a SQL string).
5092
5093    Returns:
5094        Select: the syntax tree for the SELECT statement.
5095    """
5096    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:
5099def update(
5100    table: str | Table,
5101    properties: dict,
5102    where: t.Optional[ExpOrStr] = None,
5103    from_: t.Optional[ExpOrStr] = None,
5104    dialect: DialectType = None,
5105    **opts,
5106) -> Update:
5107    """
5108    Creates an update statement.
5109
5110    Example:
5111        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5112        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5113
5114    Args:
5115        *properties: dictionary of properties to set which are
5116            auto converted to sql objects eg None -> NULL
5117        where: sql conditional parsed into a WHERE statement
5118        from_: sql statement parsed into a FROM 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        Update: the syntax tree for the UPDATE statement.
5124    """
5125    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5126    update_expr.set(
5127        "expressions",
5128        [
5129            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5130            for k, v in properties.items()
5131        ],
5132    )
5133    if from_:
5134        update_expr.set(
5135            "from",
5136            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5137        )
5138    if isinstance(where, Condition):
5139        where = Where(this=where)
5140    if where:
5141        update_expr.set(
5142            "where",
5143            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5144        )
5145    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:
5148def delete(
5149    table: ExpOrStr,
5150    where: t.Optional[ExpOrStr] = None,
5151    returning: t.Optional[ExpOrStr] = None,
5152    dialect: DialectType = None,
5153    **opts,
5154) -> Delete:
5155    """
5156    Builds a delete statement.
5157
5158    Example:
5159        >>> delete("my_table", where="id > 1").sql()
5160        'DELETE FROM my_table WHERE id > 1'
5161
5162    Args:
5163        where: sql conditional parsed into a WHERE statement
5164        returning: sql conditional parsed into a RETURNING statement
5165        dialect: the dialect used to parse the input expressions.
5166        **opts: other options to use to parse the input expressions.
5167
5168    Returns:
5169        Delete: the syntax tree for the DELETE statement.
5170    """
5171    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5172    if where:
5173        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5174    if returning:
5175        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5176    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:
5179def insert(
5180    expression: ExpOrStr,
5181    into: ExpOrStr,
5182    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5183    overwrite: t.Optional[bool] = None,
5184    dialect: DialectType = None,
5185    copy: bool = True,
5186    **opts,
5187) -> Insert:
5188    """
5189    Builds an INSERT statement.
5190
5191    Example:
5192        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5193        'INSERT INTO tbl VALUES (1, 2, 3)'
5194
5195    Args:
5196        expression: the sql string or expression of the INSERT statement
5197        into: the tbl to insert data to.
5198        columns: optionally the table's column names.
5199        overwrite: whether to INSERT OVERWRITE or not.
5200        dialect: the dialect used to parse the input expressions.
5201        copy: whether or not to copy the expression.
5202        **opts: other options to use to parse the input expressions.
5203
5204    Returns:
5205        Insert: the syntax tree for the INSERT statement.
5206    """
5207    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5208    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5209
5210    if columns:
5211        this = _apply_list_builder(
5212            *columns,
5213            instance=Schema(this=this),
5214            arg="expressions",
5215            into=Identifier,
5216            copy=False,
5217            dialect=dialect,
5218            **opts,
5219        )
5220
5221    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:
5224def condition(
5225    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5226) -> Condition:
5227    """
5228    Initialize a logical condition expression.
5229
5230    Example:
5231        >>> condition("x=1").sql()
5232        'x = 1'
5233
5234        This is helpful for composing larger logical syntax trees:
5235        >>> where = condition("x=1")
5236        >>> where = where.and_("y=1")
5237        >>> Select().from_("tbl").select("*").where(where).sql()
5238        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5239
5240    Args:
5241        *expression: the SQL code string to parse.
5242            If an Expression instance is passed, this is used as-is.
5243        dialect: the dialect used to parse the input expression (in the case that the
5244            input expression is a SQL string).
5245        copy: Whether or not to copy `expression` (only applies to expressions).
5246        **opts: other options to use to parse the input expressions (again, in the case
5247            that the input expression is a SQL string).
5248
5249    Returns:
5250        The new Condition instance
5251    """
5252    return maybe_parse(
5253        expression,
5254        into=Condition,
5255        dialect=dialect,
5256        copy=copy,
5257        **opts,
5258    )

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:
5261def and_(
5262    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5263) -> Condition:
5264    """
5265    Combine multiple conditions with an AND logical operator.
5266
5267    Example:
5268        >>> and_("x=1", and_("y=1", "z=1")).sql()
5269        'x = 1 AND (y = 1 AND z = 1)'
5270
5271    Args:
5272        *expressions: the SQL code strings to parse.
5273            If an Expression instance is passed, this is used as-is.
5274        dialect: the dialect used to parse the input expression.
5275        copy: whether or not to copy `expressions` (only applies to Expressions).
5276        **opts: other options to use to parse the input expressions.
5277
5278    Returns:
5279        And: the new condition
5280    """
5281    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:
5284def or_(
5285    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5286) -> Condition:
5287    """
5288    Combine multiple conditions with an OR logical operator.
5289
5290    Example:
5291        >>> or_("x=1", or_("y=1", "z=1")).sql()
5292        'x = 1 OR (y = 1 OR z = 1)'
5293
5294    Args:
5295        *expressions: the SQL code strings to parse.
5296            If an Expression instance is passed, this is used as-is.
5297        dialect: the dialect used to parse the input expression.
5298        copy: whether or not to copy `expressions` (only applies to Expressions).
5299        **opts: other options to use to parse the input expressions.
5300
5301    Returns:
5302        Or: the new condition
5303    """
5304    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:
5307def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5308    """
5309    Wrap a condition with a NOT operator.
5310
5311    Example:
5312        >>> not_("this_suit='black'").sql()
5313        "NOT this_suit = 'black'"
5314
5315    Args:
5316        expression: the SQL code string to parse.
5317            If an Expression instance is passed, this is used as-is.
5318        dialect: the dialect used to parse the input expression.
5319        copy: whether to copy the expression or not.
5320        **opts: other options to use to parse the input expressions.
5321
5322    Returns:
5323        The new condition.
5324    """
5325    this = condition(
5326        expression,
5327        dialect=dialect,
5328        copy=copy,
5329        **opts,
5330    )
5331    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:
5334def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5335    """
5336    Wrap an expression in parentheses.
5337
5338    Example:
5339        >>> paren("5 + 3").sql()
5340        '(5 + 3)'
5341
5342    Args:
5343        expression: the SQL code string to parse.
5344            If an Expression instance is passed, this is used as-is.
5345        copy: whether to copy the expression or not.
5346
5347    Returns:
5348        The wrapped expression.
5349    """
5350    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):
5368def to_identifier(name, quoted=None, copy=True):
5369    """Builds an identifier.
5370
5371    Args:
5372        name: The name to turn into an identifier.
5373        quoted: Whether or not force quote the identifier.
5374        copy: Whether or not to copy a passed in Identefier node.
5375
5376    Returns:
5377        The identifier ast node.
5378    """
5379
5380    if name is None:
5381        return None
5382
5383    if isinstance(name, Identifier):
5384        identifier = _maybe_copy(name, copy)
5385    elif isinstance(name, str):
5386        identifier = Identifier(
5387            this=name,
5388            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5389        )
5390    else:
5391        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5392    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:
5398def to_interval(interval: str | Literal) -> Interval:
5399    """Builds an interval expression from a string like '1 day' or '5 months'."""
5400    if isinstance(interval, Literal):
5401        if not interval.is_string:
5402            raise ValueError("Invalid interval string.")
5403
5404        interval = interval.this
5405
5406    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5407
5408    if not interval_parts:
5409        raise ValueError("Invalid interval string.")
5410
5411    return Interval(
5412        this=Literal.string(interval_parts.group(1)),
5413        unit=Var(this=interval_parts.group(2)),
5414    )

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

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:
5586def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5587    """Cast an expression to a data type.
5588
5589    Example:
5590        >>> cast('x + 1', 'int').sql()
5591        'CAST(x + 1 AS INT)'
5592
5593    Args:
5594        expression: The expression to cast.
5595        to: The datatype to cast to.
5596
5597    Returns:
5598        The new Cast instance.
5599    """
5600    expression = maybe_parse(expression, **opts)
5601    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:
5604def table_(
5605    table: Identifier | str,
5606    db: t.Optional[Identifier | str] = None,
5607    catalog: t.Optional[Identifier | str] = None,
5608    quoted: t.Optional[bool] = None,
5609    alias: t.Optional[Identifier | str] = None,
5610) -> Table:
5611    """Build a Table.
5612
5613    Args:
5614        table: Table name.
5615        db: Database name.
5616        catalog: Catalog name.
5617        quote: Whether to force quotes on the table's identifiers.
5618        alias: Table's alias.
5619
5620    Returns:
5621        The new Table instance.
5622    """
5623    return Table(
5624        this=to_identifier(table, quoted=quoted),
5625        db=to_identifier(db, quoted=quoted),
5626        catalog=to_identifier(catalog, quoted=quoted),
5627        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5628    )

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:
5631def values(
5632    values: t.Iterable[t.Tuple[t.Any, ...]],
5633    alias: t.Optional[str] = None,
5634    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5635) -> Values:
5636    """Build VALUES statement.
5637
5638    Example:
5639        >>> values([(1, '2')]).sql()
5640        "VALUES (1, '2')"
5641
5642    Args:
5643        values: values statements that will be converted to SQL
5644        alias: optional alias
5645        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5646         If either are provided then an alias is also required.
5647
5648    Returns:
5649        Values: the Values expression object
5650    """
5651    if columns and not alias:
5652        raise ValueError("Alias is required when providing columns")
5653
5654    return Values(
5655        expressions=[convert(tup) for tup in values],
5656        alias=(
5657            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5658            if columns
5659            else (TableAlias(this=to_identifier(alias)) if alias else None)
5660        ),
5661    )

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:
5664def var(name: t.Optional[ExpOrStr]) -> Var:
5665    """Build a SQL variable.
5666
5667    Example:
5668        >>> repr(var('x'))
5669        '(VAR this: x)'
5670
5671        >>> repr(var(column('x', table='y')))
5672        '(VAR this: x)'
5673
5674    Args:
5675        name: The name of the var or an expression who's name will become the var.
5676
5677    Returns:
5678        The new variable node.
5679    """
5680    if not name:
5681        raise ValueError("Cannot convert empty name into var.")
5682
5683    if isinstance(name, Expression):
5684        name = name.name
5685    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:
5688def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5689    """Build ALTER TABLE... RENAME... expression
5690
5691    Args:
5692        old_name: The old name of the table
5693        new_name: The new name of the table
5694
5695    Returns:
5696        Alter table expression
5697    """
5698    old_table = to_table(old_name)
5699    new_table = to_table(new_name)
5700    return AlterTable(
5701        this=old_table,
5702        actions=[
5703            RenameTable(this=new_table),
5704        ],
5705    )

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

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:
5795def table_name(table: Table | str, dialect: DialectType = None) -> str:
5796    """Get the full name of a table as a string.
5797
5798    Args:
5799        table: Table expression node or string.
5800        dialect: The dialect to generate the table name for.
5801
5802    Examples:
5803        >>> from sqlglot import exp, parse_one
5804        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5805        'a.b.c'
5806
5807    Returns:
5808        The table name.
5809    """
5810
5811    table = maybe_parse(table, into=Table)
5812
5813    if not table:
5814        raise ValueError(f"Cannot parse {table}")
5815
5816    return ".".join(
5817        part.sql(dialect=dialect, identify=True)
5818        if not SAFE_IDENTIFIER_RE.match(part.name)
5819        else part.name
5820        for part in table.parts
5821    )

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

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5979def false() -> Boolean:
5980    """
5981    Returns a false Boolean expression.
5982    """
5983    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5986def null() -> Null:
5987    """
5988    Returns a Null expression.
5989    """
5990    return Null()

Returns a Null expression.

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