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

alias_column_names: List[str]
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):
257    def copy(self):
258        """
259        Returns a deep copy of the expression.
260        """
261        new = deepcopy(self)
262        new.parent = self.parent
263        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
265    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
266        if self.comments is None:
267            self.comments = []
268        if comments:
269            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
271    def append(self, arg_key: str, value: t.Any) -> None:
272        """
273        Appends value to arg_key if it's a list or sets it as a new list.
274
275        Args:
276            arg_key (str): name of the list expression arg
277            value (Any): value to append to the list
278        """
279        if not isinstance(self.args.get(arg_key), list):
280            self.args[arg_key] = []
281        self.args[arg_key].append(value)
282        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:
284    def set(self, arg_key: str, value: t.Any) -> None:
285        """
286        Sets arg_key to value.
287
288        Args:
289            arg_key: name of the expression arg.
290            value: value to set the arg to.
291        """
292        if value is None:
293            self.args.pop(arg_key, None)
294            return
295
296        self.args[arg_key] = value
297        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]]:
318    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
319        """Yields the key and expression for all arguments, exploding list args."""
320        for k, vs in self.args.items():
321            if type(vs) is list:
322                for v in vs:
323                    if hasattr(v, "parent"):
324                        yield k, v
325            else:
326                if hasattr(vs, "parent"):
327                    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]:
329    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
330        """
331        Returns the first node in this tree which matches at least one of
332        the specified types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
337
338        Returns:
339            The node which matches the criteria or None if no such node was found.
340        """
341        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]:
343    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
344        """
345        Returns a generator object which visits all nodes in this tree and only
346        yields those that match at least one of the specified expression types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
351
352        Returns:
353            The generator object.
354        """
355        for expression, *_ in self.walk(bfs=bfs):
356            if isinstance(expression, expression_types):
357                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]:
359    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
360        """
361        Returns a nearest parent matching expression_types.
362
363        Args:
364            expression_types: the expression type(s) to match.
365
366        Returns:
367            The parent node.
368        """
369        ancestor = self.parent
370        while ancestor and not isinstance(ancestor, expression_types):
371            ancestor = ancestor.parent
372        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:
386    def root(self) -> Expression:
387        """
388        Returns the root expression of this tree.
389        """
390        expression = self
391        while expression.parent:
392            expression = expression.parent
393        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
395    def walk(self, bfs=True, prune=None):
396        """
397        Returns a generator object which visits all nodes in this tree.
398
399        Args:
400            bfs (bool): if set to True the BFS traversal order will be applied,
401                otherwise the DFS traversal will be used instead.
402            prune ((node, parent, arg_key) -> bool): callable that returns True if
403                the generator should stop traversing this branch of the tree.
404
405        Returns:
406            the generator object.
407        """
408        if bfs:
409            yield from self.bfs(prune=prune)
410        else:
411            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):
413    def dfs(self, parent=None, key=None, prune=None):
414        """
415        Returns a generator object which visits all nodes in this tree in
416        the DFS (Depth-first) order.
417
418        Returns:
419            The generator object.
420        """
421        parent = parent or self.parent
422        yield self, parent, key
423        if prune and prune(self, parent, key):
424            return
425
426        for k, v in self.iter_expressions():
427            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):
429    def bfs(self, prune=None):
430        """
431        Returns a generator object which visits all nodes in this tree in
432        the BFS (Breadth-first) order.
433
434        Returns:
435            The generator object.
436        """
437        queue = deque([(self, self.parent, None)])
438
439        while queue:
440            item, parent, key = queue.popleft()
441
442            yield item, parent, key
443            if prune and prune(item, parent, key):
444                continue
445
446            for k, v in item.iter_expressions():
447                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):
449    def unnest(self):
450        """
451        Returns the first non parenthesis child or self.
452        """
453        expression = self
454        while type(expression) is Paren:
455            expression = expression.this
456        return expression

Returns the first non parenthesis child or self.

def unalias(self):
458    def unalias(self):
459        """
460        Returns the inner expression if this is an Alias.
461        """
462        if isinstance(self, Alias):
463            return self.this
464        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
466    def unnest_operands(self):
467        """
468        Returns unnested operands as a tuple.
469        """
470        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
472    def flatten(self, unnest=True):
473        """
474        Returns a generator which yields child nodes who's parents are the same class.
475
476        A AND B AND C -> [A, B, C]
477        """
478        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
479            if not type(node) is self.__class__:
480                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:
488    def sql(self, dialect: DialectType = None, **opts) -> str:
489        """
490        Returns SQL string representation of this tree.
491
492        Args:
493            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
494            opts: other `sqlglot.generator.Generator` options.
495
496        Returns:
497            The SQL string.
498        """
499        from sqlglot.dialects import Dialect
500
501        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):
527    def transform(self, fun, *args, copy=True, **kwargs):
528        """
529        Recursively visits all tree nodes (excluding already transformed ones)
530        and applies the given transformation function to each node.
531
532        Args:
533            fun (function): a function which takes a node as an argument and returns a
534                new transformed node or the same node without modifications. If the function
535                returns None, then the corresponding node will be removed from the syntax tree.
536            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
537                modified in place.
538
539        Returns:
540            The transformed tree.
541        """
542        node = self.copy() if copy else self
543        new_node = fun(node, *args, **kwargs)
544
545        if new_node is None or not isinstance(new_node, Expression):
546            return new_node
547        if new_node is not node:
548            new_node.parent = node.parent
549            return new_node
550
551        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
552        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):
562    def replace(self, expression):
563        """
564        Swap out this expression with a new expression.
565
566        For example::
567
568            >>> tree = Select().select("x").from_("tbl")
569            >>> tree.find(Column).replace(Column(this="y"))
570            (COLUMN this: y)
571            >>> tree.sql()
572            'SELECT y FROM tbl'
573
574        Args:
575            expression: new node
576
577        Returns:
578            The new expression or expressions.
579        """
580        if not self.parent:
581            return expression
582
583        parent = self.parent
584        self.parent = None
585
586        replace_children(parent, lambda child: expression if child is self else child)
587        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:
589    def pop(self: E) -> E:
590        """
591        Remove this expression from its AST.
592
593        Returns:
594            The popped expression.
595        """
596        self.replace(None)
597        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_: Type[~E]) -> ~E:
599    def assert_is(self, type_: t.Type[E]) -> E:
600        """
601        Assert that this `Expression` is an instance of `type_`.
602
603        If it is NOT an instance of `type_`, this raises an assertion error.
604        Otherwise, this returns this expression.
605
606        Examples:
607            This is useful for type security in chained expressions:
608
609            >>> import sqlglot
610            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
611            'SELECT x, z FROM y'
612        """
613        assert isinstance(self, type_)
614        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]:
616    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
617        """
618        Checks if this expression is valid (e.g. all mandatory args are set).
619
620        Args:
621            args: a sequence of values that were used to instantiate a Func expression. This is used
622                to check that the provided arguments don't exceed the function argument limit.
623
624        Returns:
625            A list of error messages for all possible errors that were found.
626        """
627        errors: t.List[str] = []
628
629        for k in self.args:
630            if k not in self.arg_types:
631                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
632        for k, mandatory in self.arg_types.items():
633            v = self.args.get(k)
634            if mandatory and (v is None or (isinstance(v, list) and not v)):
635                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
636
637        if (
638            args
639            and isinstance(self, Func)
640            and len(args) > len(self.arg_types)
641            and not self.is_var_len_args
642        ):
643            errors.append(
644                f"The number of provided arguments ({len(args)}) is greater than "
645                f"the maximum number of supported arguments ({len(self.arg_types)})"
646            )
647
648        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):
650    def dump(self):
651        """
652        Dump this Expression to a JSON-serializable dict.
653        """
654        from sqlglot.serde import dump
655
656        return dump(self)

Dump this Expression to a JSON-serializable dict.

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

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

key = 'predicate'
class DerivedTable(Expression):
893class DerivedTable(Expression):
894    @property
895    def selects(self) -> t.List[Expression]:
896        return self.this.selects if isinstance(self.this, Subqueryable) else []
897
898    @property
899    def named_selects(self) -> t.List[str]:
900        return [select.output_name for select in self.selects]
named_selects: List[str]
key = 'derivedtable'
class Unionable(Expression):
903class Unionable(Expression):
904    def union(
905        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
906    ) -> Unionable:
907        """
908        Builds a UNION expression.
909
910        Example:
911            >>> import sqlglot
912            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
913            'SELECT * FROM foo UNION SELECT * FROM bla'
914
915        Args:
916            expression: the SQL code string.
917                If an `Expression` instance is passed, it will be used as-is.
918            distinct: set the DISTINCT flag if and only if this is true.
919            dialect: the dialect used to parse the input expression.
920            opts: other options to use to parse the input expressions.
921
922        Returns:
923            The new Union expression.
924        """
925        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
926
927    def intersect(
928        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
929    ) -> Unionable:
930        """
931        Builds an INTERSECT expression.
932
933        Example:
934            >>> import sqlglot
935            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
936            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
937
938        Args:
939            expression: the SQL code string.
940                If an `Expression` instance is passed, it will be used as-is.
941            distinct: set the DISTINCT flag if and only if this is true.
942            dialect: the dialect used to parse the input expression.
943            opts: other options to use to parse the input expressions.
944
945        Returns:
946            The new Intersect expression.
947        """
948        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
949
950    def except_(
951        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
952    ) -> Unionable:
953        """
954        Builds an EXCEPT expression.
955
956        Example:
957            >>> import sqlglot
958            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
959            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
960
961        Args:
962            expression: the SQL code string.
963                If an `Expression` instance is passed, it will be used as-is.
964            distinct: set the DISTINCT flag if and only if this is true.
965            dialect: the dialect used to parse the input expression.
966            opts: other options to use to parse the input expressions.
967
968        Returns:
969            The new Except expression.
970        """
971        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:
904    def union(
905        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
906    ) -> Unionable:
907        """
908        Builds a UNION expression.
909
910        Example:
911            >>> import sqlglot
912            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
913            'SELECT * FROM foo UNION SELECT * FROM bla'
914
915        Args:
916            expression: the SQL code string.
917                If an `Expression` instance is passed, it will be used as-is.
918            distinct: set the DISTINCT flag if and only if this is true.
919            dialect: the dialect used to parse the input expression.
920            opts: other options to use to parse the input expressions.
921
922        Returns:
923            The new Union expression.
924        """
925        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:
927    def intersect(
928        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
929    ) -> Unionable:
930        """
931        Builds an INTERSECT expression.
932
933        Example:
934            >>> import sqlglot
935            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
936            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
937
938        Args:
939            expression: the SQL code string.
940                If an `Expression` instance is passed, it will be used as-is.
941            distinct: set the DISTINCT flag if and only if this is true.
942            dialect: the dialect used to parse the input expression.
943            opts: other options to use to parse the input expressions.
944
945        Returns:
946            The new Intersect expression.
947        """
948        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:
950    def except_(
951        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
952    ) -> Unionable:
953        """
954        Builds an EXCEPT expression.
955
956        Example:
957            >>> import sqlglot
958            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
959            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
960
961        Args:
962            expression: the SQL code string.
963                If an `Expression` instance is passed, it will be used as-is.
964            distinct: set the DISTINCT flag if and only if this is true.
965            dialect: the dialect used to parse the input expression.
966            opts: other options to use to parse the input expressions.
967
968        Returns:
969            The new Except expression.
970        """
971        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):
974class UDTF(DerivedTable, Unionable):
975    @property
976    def selects(self) -> t.List[Expression]:
977        alias = self.args.get("alias")
978        return alias.columns if alias else []
key = 'udtf'
class Cache(Expression):
981class Cache(Expression):
982    arg_types = {
983        "with": False,
984        "this": True,
985        "lazy": False,
986        "options": False,
987        "expression": False,
988    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
991class Uncache(Expression):
992    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class DDL(Expression):
 995class DDL(Expression):
 996    @property
 997    def ctes(self):
 998        with_ = self.args.get("with")
 999        if not with_:
1000            return []
1001        return with_.expressions
1002
1003    @property
1004    def named_selects(self) -> t.List[str]:
1005        if isinstance(self.expression, Subqueryable):
1006            return self.expression.named_selects
1007        return []
1008
1009    @property
1010    def selects(self) -> t.List[Expression]:
1011        if isinstance(self.expression, Subqueryable):
1012            return self.expression.selects
1013        return []
ctes
named_selects: List[str]
key = 'ddl'
class Create(DDL):
1016class Create(DDL):
1017    arg_types = {
1018        "with": False,
1019        "this": True,
1020        "kind": True,
1021        "expression": False,
1022        "exists": False,
1023        "properties": False,
1024        "replace": False,
1025        "unique": False,
1026        "indexes": False,
1027        "no_schema_binding": False,
1028        "begin": False,
1029        "clone": False,
1030    }
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):
1034class Clone(Expression):
1035    arg_types = {
1036        "this": True,
1037        "when": False,
1038        "kind": False,
1039        "shallow": False,
1040        "expression": False,
1041    }
arg_types = {'this': True, 'when': False, 'kind': False, 'shallow': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1044class Describe(Expression):
1045    arg_types = {"this": True, "kind": False, "expressions": False}
arg_types = {'this': True, 'kind': False, 'expressions': False}
key = 'describe'
class Pragma(Expression):
1048class Pragma(Expression):
1049    pass
key = 'pragma'
class Set(Expression):
1052class Set(Expression):
1053    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1056class SetItem(Expression):
1057    arg_types = {
1058        "this": False,
1059        "expressions": False,
1060        "kind": False,
1061        "collate": False,  # MySQL SET NAMES statement
1062        "global": False,
1063    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1066class Show(Expression):
1067    arg_types = {
1068        "this": True,
1069        "target": False,
1070        "offset": False,
1071        "limit": False,
1072        "like": False,
1073        "where": False,
1074        "db": False,
1075        "scope": False,
1076        "scope_kind": False,
1077        "full": False,
1078        "mutex": False,
1079        "query": False,
1080        "channel": False,
1081        "global": False,
1082        "log": False,
1083        "position": False,
1084        "types": False,
1085    }
arg_types = {'this': True, 'target': False, 'offset': False, 'limit': False, 'like': False, 'where': False, 'db': False, 'scope': False, 'scope_kind': False, 'full': False, 'mutex': False, 'query': False, 'channel': False, 'global': False, 'log': False, 'position': False, 'types': False}
key = 'show'
class UserDefinedFunction(Expression):
1088class UserDefinedFunction(Expression):
1089    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1092class CharacterSet(Expression):
1093    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1096class With(Expression):
1097    arg_types = {"expressions": True, "recursive": False}
1098
1099    @property
1100    def recursive(self) -> bool:
1101        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1104class WithinGroup(Expression):
1105    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1108class CTE(DerivedTable):
1109    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1112class TableAlias(Expression):
1113    arg_types = {"this": False, "columns": False}
1114
1115    @property
1116    def columns(self):
1117        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1120class BitString(Condition):
1121    pass
key = 'bitstring'
class HexString(Condition):
1124class HexString(Condition):
1125    pass
key = 'hexstring'
class ByteString(Condition):
1128class ByteString(Condition):
1129    pass
key = 'bytestring'
class RawString(Condition):
1132class RawString(Condition):
1133    pass
key = 'rawstring'
class Column(Condition):
1136class Column(Condition):
1137    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1138
1139    @property
1140    def table(self) -> str:
1141        return self.text("table")
1142
1143    @property
1144    def db(self) -> str:
1145        return self.text("db")
1146
1147    @property
1148    def catalog(self) -> str:
1149        return self.text("catalog")
1150
1151    @property
1152    def output_name(self) -> str:
1153        return self.name
1154
1155    @property
1156    def parts(self) -> t.List[Identifier]:
1157        """Return the parts of a column in order catalog, db, table, name."""
1158        return [
1159            t.cast(Identifier, self.args[part])
1160            for part in ("catalog", "db", "table", "this")
1161            if self.args.get(part)
1162        ]
1163
1164    def to_dot(self) -> Dot:
1165        """Converts the column into a dot expression."""
1166        parts = self.parts
1167        parent = self.parent
1168
1169        while parent:
1170            if isinstance(parent, Dot):
1171                parts.append(parent.expression)
1172            parent = parent.parent
1173
1174        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:
1164    def to_dot(self) -> Dot:
1165        """Converts the column into a dot expression."""
1166        parts = self.parts
1167        parent = self.parent
1168
1169        while parent:
1170            if isinstance(parent, Dot):
1171                parts.append(parent.expression)
1172            parent = parent.parent
1173
1174        return Dot.build(parts)

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1177class ColumnPosition(Expression):
1178    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1181class ColumnDef(Expression):
1182    arg_types = {
1183        "this": True,
1184        "kind": False,
1185        "constraints": False,
1186        "exists": False,
1187        "position": False,
1188    }
1189
1190    @property
1191    def constraints(self) -> t.List[ColumnConstraint]:
1192        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
key = 'columndef'
class AlterColumn(Expression):
1195class AlterColumn(Expression):
1196    arg_types = {
1197        "this": True,
1198        "dtype": False,
1199        "collate": False,
1200        "using": False,
1201        "default": False,
1202        "drop": False,
1203    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1206class RenameTable(Expression):
1207    pass
key = 'renametable'
class Comment(Expression):
1210class Comment(Expression):
1211    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
arg_types = {'this': True, 'kind': True, 'expression': True, 'exists': False}
key = 'comment'
class Comprehension(Expression):
1214class Comprehension(Expression):
1215    arg_types = {"this": True, "expression": True, "iterator": True, "condition": False}
arg_types = {'this': True, 'expression': True, 'iterator': True, 'condition': False}
key = 'comprehension'
class MergeTreeTTLAction(Expression):
1219class MergeTreeTTLAction(Expression):
1220    arg_types = {
1221        "this": True,
1222        "delete": False,
1223        "recompress": False,
1224        "to_disk": False,
1225        "to_volume": False,
1226    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1230class MergeTreeTTL(Expression):
1231    arg_types = {
1232        "expressions": True,
1233        "where": False,
1234        "group": False,
1235        "aggregates": False,
1236    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class IndexConstraintOption(Expression):
1240class IndexConstraintOption(Expression):
1241    arg_types = {
1242        "key_block_size": False,
1243        "using": False,
1244        "parser": False,
1245        "comment": False,
1246        "visible": False,
1247        "engine_attr": False,
1248        "secondary_engine_attr": False,
1249    }
arg_types = {'key_block_size': False, 'using': False, 'parser': False, 'comment': False, 'visible': False, 'engine_attr': False, 'secondary_engine_attr': False}
key = 'indexconstraintoption'
class ColumnConstraint(Expression):
1252class ColumnConstraint(Expression):
1253    arg_types = {"this": False, "kind": True}
1254
1255    @property
1256    def kind(self) -> ColumnConstraintKind:
1257        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1260class ColumnConstraintKind(Expression):
1261    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1264class AutoIncrementColumnConstraint(ColumnConstraintKind):
1265    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1268class CaseSpecificColumnConstraint(ColumnConstraintKind):
1269    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1272class CharacterSetColumnConstraint(ColumnConstraintKind):
1273    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1276class CheckColumnConstraint(ColumnConstraintKind):
1277    pass
key = 'checkcolumnconstraint'
class ClusteredColumnConstraint(ColumnConstraintKind):
1280class ClusteredColumnConstraint(ColumnConstraintKind):
1281    pass
key = 'clusteredcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1284class CollateColumnConstraint(ColumnConstraintKind):
1285    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1288class CommentColumnConstraint(ColumnConstraintKind):
1289    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1292class CompressColumnConstraint(ColumnConstraintKind):
1293    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1296class DateFormatColumnConstraint(ColumnConstraintKind):
1297    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1300class DefaultColumnConstraint(ColumnConstraintKind):
1301    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1304class EncodeColumnConstraint(ColumnConstraintKind):
1305    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1308class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1309    # this: True -> ALWAYS, this: False -> BY DEFAULT
1310    arg_types = {
1311        "this": False,
1312        "expression": False,
1313        "on_null": False,
1314        "start": False,
1315        "increment": False,
1316        "minvalue": False,
1317        "maxvalue": False,
1318        "cycle": False,
1319    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class IndexColumnConstraint(ColumnConstraintKind):
1323class IndexColumnConstraint(ColumnConstraintKind):
1324    arg_types = {"this": False, "schema": True, "kind": False, "type": False, "options": False}
arg_types = {'this': False, 'schema': True, 'kind': False, 'type': False, 'options': False}
key = 'indexcolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1327class InlineLengthColumnConstraint(ColumnConstraintKind):
1328    pass
key = 'inlinelengthcolumnconstraint'
class NonClusteredColumnConstraint(ColumnConstraintKind):
1331class NonClusteredColumnConstraint(ColumnConstraintKind):
1332    pass
key = 'nonclusteredcolumnconstraint'
class NotForReplicationColumnConstraint(ColumnConstraintKind):
1335class NotForReplicationColumnConstraint(ColumnConstraintKind):
1336    arg_types = {}
arg_types = {}
key = 'notforreplicationcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1339class NotNullColumnConstraint(ColumnConstraintKind):
1340    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1344class OnUpdateColumnConstraint(ColumnConstraintKind):
1345    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1348class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1349    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1352class TitleColumnConstraint(ColumnConstraintKind):
1353    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1356class UniqueColumnConstraint(ColumnConstraintKind):
1357    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1360class UppercaseColumnConstraint(ColumnConstraintKind):
1361    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1364class PathColumnConstraint(ColumnConstraintKind):
1365    pass
key = 'pathcolumnconstraint'
class ComputedColumnConstraint(ColumnConstraintKind):
1370class ComputedColumnConstraint(ColumnConstraintKind):
1371    arg_types = {"this": True, "persisted": False, "not_null": False}
arg_types = {'this': True, 'persisted': False, 'not_null': False}
key = 'computedcolumnconstraint'
class Constraint(Expression):
1374class Constraint(Expression):
1375    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1378class Delete(Expression):
1379    arg_types = {
1380        "with": False,
1381        "this": False,
1382        "using": False,
1383        "where": False,
1384        "returning": False,
1385        "limit": False,
1386        "tables": False,  # Multiple-Table Syntax (MySQL)
1387    }
1388
1389    def delete(
1390        self,
1391        table: ExpOrStr,
1392        dialect: DialectType = None,
1393        copy: bool = True,
1394        **opts,
1395    ) -> Delete:
1396        """
1397        Create a DELETE expression or replace the table on an existing DELETE expression.
1398
1399        Example:
1400            >>> delete("tbl").sql()
1401            'DELETE FROM tbl'
1402
1403        Args:
1404            table: the table from which to delete.
1405            dialect: the dialect used to parse the input expression.
1406            copy: if `False`, modify this expression instance in-place.
1407            opts: other options to use to parse the input expressions.
1408
1409        Returns:
1410            Delete: the modified expression.
1411        """
1412        return _apply_builder(
1413            expression=table,
1414            instance=self,
1415            arg="this",
1416            dialect=dialect,
1417            into=Table,
1418            copy=copy,
1419            **opts,
1420        )
1421
1422    def where(
1423        self,
1424        *expressions: t.Optional[ExpOrStr],
1425        append: bool = True,
1426        dialect: DialectType = None,
1427        copy: bool = True,
1428        **opts,
1429    ) -> Delete:
1430        """
1431        Append to or set the WHERE expressions.
1432
1433        Example:
1434            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1435            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1436
1437        Args:
1438            *expressions: the SQL code strings to parse.
1439                If an `Expression` instance is passed, it will be used as-is.
1440                Multiple expressions are combined with an AND operator.
1441            append: if `True`, AND the new expressions to any existing expression.
1442                Otherwise, this resets the expression.
1443            dialect: the dialect used to parse the input expressions.
1444            copy: if `False`, modify this expression instance in-place.
1445            opts: other options to use to parse the input expressions.
1446
1447        Returns:
1448            Delete: the modified expression.
1449        """
1450        return _apply_conjunction_builder(
1451            *expressions,
1452            instance=self,
1453            arg="where",
1454            append=append,
1455            into=Where,
1456            dialect=dialect,
1457            copy=copy,
1458            **opts,
1459        )
1460
1461    def returning(
1462        self,
1463        expression: ExpOrStr,
1464        dialect: DialectType = None,
1465        copy: bool = True,
1466        **opts,
1467    ) -> Delete:
1468        """
1469        Set the RETURNING expression. Not supported by all dialects.
1470
1471        Example:
1472            >>> delete("tbl").returning("*", dialect="postgres").sql()
1473            'DELETE FROM tbl RETURNING *'
1474
1475        Args:
1476            expression: the SQL code strings to parse.
1477                If an `Expression` instance is passed, it will be used as-is.
1478            dialect: the dialect used to parse the input expressions.
1479            copy: if `False`, modify this expression instance in-place.
1480            opts: other options to use to parse the input expressions.
1481
1482        Returns:
1483            Delete: the modified expression.
1484        """
1485        return _apply_builder(
1486            expression=expression,
1487            instance=self,
1488            arg="returning",
1489            prefix="RETURNING",
1490            dialect=dialect,
1491            copy=copy,
1492            into=Returning,
1493            **opts,
1494        )
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:
1389    def delete(
1390        self,
1391        table: ExpOrStr,
1392        dialect: DialectType = None,
1393        copy: bool = True,
1394        **opts,
1395    ) -> Delete:
1396        """
1397        Create a DELETE expression or replace the table on an existing DELETE expression.
1398
1399        Example:
1400            >>> delete("tbl").sql()
1401            'DELETE FROM tbl'
1402
1403        Args:
1404            table: the table from which to delete.
1405            dialect: the dialect used to parse the input expression.
1406            copy: if `False`, modify this expression instance in-place.
1407            opts: other options to use to parse the input expressions.
1408
1409        Returns:
1410            Delete: the modified expression.
1411        """
1412        return _apply_builder(
1413            expression=table,
1414            instance=self,
1415            arg="this",
1416            dialect=dialect,
1417            into=Table,
1418            copy=copy,
1419            **opts,
1420        )

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:
1422    def where(
1423        self,
1424        *expressions: t.Optional[ExpOrStr],
1425        append: bool = True,
1426        dialect: DialectType = None,
1427        copy: bool = True,
1428        **opts,
1429    ) -> Delete:
1430        """
1431        Append to or set the WHERE expressions.
1432
1433        Example:
1434            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1435            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1436
1437        Args:
1438            *expressions: the SQL code strings to parse.
1439                If an `Expression` instance is passed, it will be used as-is.
1440                Multiple expressions are combined with an AND operator.
1441            append: if `True`, AND the new expressions to any existing expression.
1442                Otherwise, this resets the expression.
1443            dialect: the dialect used to parse the input expressions.
1444            copy: if `False`, modify this expression instance in-place.
1445            opts: other options to use to parse the input expressions.
1446
1447        Returns:
1448            Delete: the modified expression.
1449        """
1450        return _apply_conjunction_builder(
1451            *expressions,
1452            instance=self,
1453            arg="where",
1454            append=append,
1455            into=Where,
1456            dialect=dialect,
1457            copy=copy,
1458            **opts,
1459        )

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:
1461    def returning(
1462        self,
1463        expression: ExpOrStr,
1464        dialect: DialectType = None,
1465        copy: bool = True,
1466        **opts,
1467    ) -> Delete:
1468        """
1469        Set the RETURNING expression. Not supported by all dialects.
1470
1471        Example:
1472            >>> delete("tbl").returning("*", dialect="postgres").sql()
1473            'DELETE FROM tbl RETURNING *'
1474
1475        Args:
1476            expression: the SQL code strings to parse.
1477                If an `Expression` instance is passed, it will be used as-is.
1478            dialect: the dialect used to parse the input expressions.
1479            copy: if `False`, modify this expression instance in-place.
1480            opts: other options to use to parse the input expressions.
1481
1482        Returns:
1483            Delete: the modified expression.
1484        """
1485        return _apply_builder(
1486            expression=expression,
1487            instance=self,
1488            arg="returning",
1489            prefix="RETURNING",
1490            dialect=dialect,
1491            copy=copy,
1492            into=Returning,
1493            **opts,
1494        )

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):
1497class Drop(Expression):
1498    arg_types = {
1499        "this": False,
1500        "kind": False,
1501        "exists": False,
1502        "temporary": False,
1503        "materialized": False,
1504        "cascade": False,
1505        "constraints": False,
1506        "purge": False,
1507    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1510class Filter(Expression):
1511    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1514class Check(Expression):
1515    pass
key = 'check'
class Connect(Expression):
1519class Connect(Expression):
1520    arg_types = {"start": False, "connect": True}
arg_types = {'start': False, 'connect': True}
key = 'connect'
class Prior(Expression):
1523class Prior(Expression):
1524    pass
key = 'prior'
class Directory(Expression):
1527class Directory(Expression):
1528    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1529    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1532class ForeignKey(Expression):
1533    arg_types = {
1534        "expressions": True,
1535        "reference": False,
1536        "delete": False,
1537        "update": False,
1538    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1541class PrimaryKey(Expression):
1542    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1547class Into(Expression):
1548    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1551class From(Expression):
1552    @property
1553    def name(self) -> str:
1554        return self.this.name
1555
1556    @property
1557    def alias_or_name(self) -> str:
1558        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1561class Having(Expression):
1562    pass
key = 'having'
class Hint(Expression):
1565class Hint(Expression):
1566    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1569class JoinHint(Expression):
1570    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1573class Identifier(Expression):
1574    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1575
1576    @property
1577    def quoted(self) -> bool:
1578        return bool(self.args.get("quoted"))
1579
1580    @property
1581    def hashable_args(self) -> t.Any:
1582        return (self.this, self.quoted)
1583
1584    @property
1585    def output_name(self) -> str:
1586        return self.name
arg_types = {'this': True, 'quoted': False, 'global': False, 'temporary': False}
quoted: bool
hashable_args: Any
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'identifier'
class Index(Expression):
1589class Index(Expression):
1590    arg_types = {
1591        "this": False,
1592        "table": False,
1593        "using": False,
1594        "where": False,
1595        "columns": False,
1596        "unique": False,
1597        "primary": False,
1598        "amp": False,  # teradata
1599        "partition_by": False,  # teradata
1600    }
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(DDL):
1603class Insert(DDL):
1604    arg_types = {
1605        "with": False,
1606        "this": True,
1607        "expression": False,
1608        "conflict": False,
1609        "returning": False,
1610        "overwrite": False,
1611        "exists": False,
1612        "partition": False,
1613        "alternative": False,
1614        "where": False,
1615        "ignore": False,
1616        "by_name": False,
1617    }
1618
1619    def with_(
1620        self,
1621        alias: ExpOrStr,
1622        as_: ExpOrStr,
1623        recursive: t.Optional[bool] = None,
1624        append: bool = True,
1625        dialect: DialectType = None,
1626        copy: bool = True,
1627        **opts,
1628    ) -> Insert:
1629        """
1630        Append to or set the common table expressions.
1631
1632        Example:
1633            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1634            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1635
1636        Args:
1637            alias: the SQL code string to parse as the table name.
1638                If an `Expression` instance is passed, this is used as-is.
1639            as_: the SQL code string to parse as the table expression.
1640                If an `Expression` instance is passed, it will be used as-is.
1641            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1642            append: if `True`, add to any existing expressions.
1643                Otherwise, this resets the expressions.
1644            dialect: the dialect used to parse the input expression.
1645            copy: if `False`, modify this expression instance in-place.
1646            opts: other options to use to parse the input expressions.
1647
1648        Returns:
1649            The modified expression.
1650        """
1651        return _apply_cte_builder(
1652            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1653        )
arg_types = {'with': False, 'this': True, 'expression': False, 'conflict': False, 'returning': False, 'overwrite': False, 'exists': False, 'partition': False, 'alternative': False, 'where': False, 'ignore': False, 'by_name': 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:
1619    def with_(
1620        self,
1621        alias: ExpOrStr,
1622        as_: ExpOrStr,
1623        recursive: t.Optional[bool] = None,
1624        append: bool = True,
1625        dialect: DialectType = None,
1626        copy: bool = True,
1627        **opts,
1628    ) -> Insert:
1629        """
1630        Append to or set the common table expressions.
1631
1632        Example:
1633            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1634            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1635
1636        Args:
1637            alias: the SQL code string to parse as the table name.
1638                If an `Expression` instance is passed, this is used as-is.
1639            as_: the SQL code string to parse as the table expression.
1640                If an `Expression` instance is passed, it will be used as-is.
1641            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1642            append: if `True`, add to any existing expressions.
1643                Otherwise, this resets the expressions.
1644            dialect: the dialect used to parse the input expression.
1645            copy: if `False`, modify this expression instance in-place.
1646            opts: other options to use to parse the input expressions.
1647
1648        Returns:
1649            The modified expression.
1650        """
1651        return _apply_cte_builder(
1652            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1653        )

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):
1656class OnConflict(Expression):
1657    arg_types = {
1658        "duplicate": False,
1659        "expressions": False,
1660        "nothing": False,
1661        "key": False,
1662        "constraint": False,
1663    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1666class Returning(Expression):
1667    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1671class Introducer(Expression):
1672    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1676class National(Expression):
1677    pass
key = 'national'
class LoadData(Expression):
1680class LoadData(Expression):
1681    arg_types = {
1682        "this": True,
1683        "local": False,
1684        "overwrite": False,
1685        "inpath": True,
1686        "partition": False,
1687        "input_format": False,
1688        "serde": False,
1689    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1692class Partition(Expression):
1693    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1696class Fetch(Expression):
1697    arg_types = {
1698        "direction": False,
1699        "count": False,
1700        "percent": False,
1701        "with_ties": False,
1702    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1705class Group(Expression):
1706    arg_types = {
1707        "expressions": False,
1708        "grouping_sets": False,
1709        "cube": False,
1710        "rollup": False,
1711        "totals": False,
1712        "all": False,
1713    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1716class Lambda(Expression):
1717    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1720class Limit(Expression):
1721    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1724class Literal(Condition):
1725    arg_types = {"this": True, "is_string": True}
1726
1727    @property
1728    def hashable_args(self) -> t.Any:
1729        return (self.this, self.args.get("is_string"))
1730
1731    @classmethod
1732    def number(cls, number) -> Literal:
1733        return cls(this=str(number), is_string=False)
1734
1735    @classmethod
1736    def string(cls, string) -> Literal:
1737        return cls(this=str(string), is_string=True)
1738
1739    @property
1740    def output_name(self) -> str:
1741        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1731    @classmethod
1732    def number(cls, number) -> Literal:
1733        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1735    @classmethod
1736    def string(cls, string) -> Literal:
1737        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):
1744class Join(Expression):
1745    arg_types = {
1746        "this": True,
1747        "on": False,
1748        "side": False,
1749        "kind": False,
1750        "using": False,
1751        "method": False,
1752        "global": False,
1753        "hint": False,
1754    }
1755
1756    @property
1757    def method(self) -> str:
1758        return self.text("method").upper()
1759
1760    @property
1761    def kind(self) -> str:
1762        return self.text("kind").upper()
1763
1764    @property
1765    def side(self) -> str:
1766        return self.text("side").upper()
1767
1768    @property
1769    def hint(self) -> str:
1770        return self.text("hint").upper()
1771
1772    @property
1773    def alias_or_name(self) -> str:
1774        return self.this.alias_or_name
1775
1776    def on(
1777        self,
1778        *expressions: t.Optional[ExpOrStr],
1779        append: bool = True,
1780        dialect: DialectType = None,
1781        copy: bool = True,
1782        **opts,
1783    ) -> Join:
1784        """
1785        Append to or set the ON expressions.
1786
1787        Example:
1788            >>> import sqlglot
1789            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1790            'JOIN x ON y = 1'
1791
1792        Args:
1793            *expressions: the SQL code strings to parse.
1794                If an `Expression` instance is passed, it will be used as-is.
1795                Multiple expressions are combined with an AND operator.
1796            append: if `True`, AND the new expressions to any existing expression.
1797                Otherwise, this resets the expression.
1798            dialect: the dialect used to parse the input expressions.
1799            copy: if `False`, modify this expression instance in-place.
1800            opts: other options to use to parse the input expressions.
1801
1802        Returns:
1803            The modified Join expression.
1804        """
1805        join = _apply_conjunction_builder(
1806            *expressions,
1807            instance=self,
1808            arg="on",
1809            append=append,
1810            dialect=dialect,
1811            copy=copy,
1812            **opts,
1813        )
1814
1815        if join.kind == "CROSS":
1816            join.set("kind", None)
1817
1818        return join
1819
1820    def using(
1821        self,
1822        *expressions: t.Optional[ExpOrStr],
1823        append: bool = True,
1824        dialect: DialectType = None,
1825        copy: bool = True,
1826        **opts,
1827    ) -> Join:
1828        """
1829        Append to or set the USING expressions.
1830
1831        Example:
1832            >>> import sqlglot
1833            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1834            'JOIN x USING (foo, bla)'
1835
1836        Args:
1837            *expressions: the SQL code strings to parse.
1838                If an `Expression` instance is passed, it will be used as-is.
1839            append: if `True`, concatenate the new expressions to the existing "using" list.
1840                Otherwise, this resets the expression.
1841            dialect: the dialect used to parse the input expressions.
1842            copy: if `False`, modify this expression instance in-place.
1843            opts: other options to use to parse the input expressions.
1844
1845        Returns:
1846            The modified Join expression.
1847        """
1848        join = _apply_list_builder(
1849            *expressions,
1850            instance=self,
1851            arg="using",
1852            append=append,
1853            dialect=dialect,
1854            copy=copy,
1855            **opts,
1856        )
1857
1858        if join.kind == "CROSS":
1859            join.set("kind", None)
1860
1861        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:
1776    def on(
1777        self,
1778        *expressions: t.Optional[ExpOrStr],
1779        append: bool = True,
1780        dialect: DialectType = None,
1781        copy: bool = True,
1782        **opts,
1783    ) -> Join:
1784        """
1785        Append to or set the ON expressions.
1786
1787        Example:
1788            >>> import sqlglot
1789            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1790            'JOIN x ON y = 1'
1791
1792        Args:
1793            *expressions: the SQL code strings to parse.
1794                If an `Expression` instance is passed, it will be used as-is.
1795                Multiple expressions are combined with an AND operator.
1796            append: if `True`, AND the new expressions to any existing expression.
1797                Otherwise, this resets the expression.
1798            dialect: the dialect used to parse the input expressions.
1799            copy: if `False`, modify this expression instance in-place.
1800            opts: other options to use to parse the input expressions.
1801
1802        Returns:
1803            The modified Join expression.
1804        """
1805        join = _apply_conjunction_builder(
1806            *expressions,
1807            instance=self,
1808            arg="on",
1809            append=append,
1810            dialect=dialect,
1811            copy=copy,
1812            **opts,
1813        )
1814
1815        if join.kind == "CROSS":
1816            join.set("kind", None)
1817
1818        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:
1820    def using(
1821        self,
1822        *expressions: t.Optional[ExpOrStr],
1823        append: bool = True,
1824        dialect: DialectType = None,
1825        copy: bool = True,
1826        **opts,
1827    ) -> Join:
1828        """
1829        Append to or set the USING expressions.
1830
1831        Example:
1832            >>> import sqlglot
1833            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1834            'JOIN x USING (foo, bla)'
1835
1836        Args:
1837            *expressions: the SQL code strings to parse.
1838                If an `Expression` instance is passed, it will be used as-is.
1839            append: if `True`, concatenate the new expressions to the existing "using" list.
1840                Otherwise, this resets the expression.
1841            dialect: the dialect used to parse the input expressions.
1842            copy: if `False`, modify this expression instance in-place.
1843            opts: other options to use to parse the input expressions.
1844
1845        Returns:
1846            The modified Join expression.
1847        """
1848        join = _apply_list_builder(
1849            *expressions,
1850            instance=self,
1851            arg="using",
1852            append=append,
1853            dialect=dialect,
1854            copy=copy,
1855            **opts,
1856        )
1857
1858        if join.kind == "CROSS":
1859            join.set("kind", None)
1860
1861        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):
1864class Lateral(UDTF):
1865    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):
1868class MatchRecognize(Expression):
1869    arg_types = {
1870        "partition_by": False,
1871        "order": False,
1872        "measures": False,
1873        "rows": False,
1874        "after": False,
1875        "pattern": False,
1876        "define": False,
1877        "alias": False,
1878    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1883class Final(Expression):
1884    pass
key = 'final'
class Offset(Expression):
1887class Offset(Expression):
1888    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1891class Order(Expression):
1892    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1897class Cluster(Order):
1898    pass
key = 'cluster'
class Distribute(Order):
1901class Distribute(Order):
1902    pass
key = 'distribute'
class Sort(Order):
1905class Sort(Order):
1906    pass
key = 'sort'
class Ordered(Expression):
1909class Ordered(Expression):
1910    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1913class Property(Expression):
1914    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1917class AlgorithmProperty(Property):
1918    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1921class AutoIncrementProperty(Property):
1922    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1925class BlockCompressionProperty(Property):
1926    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):
1929class CharacterSetProperty(Property):
1930    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1933class ChecksumProperty(Property):
1934    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1937class CollateProperty(Property):
1938    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1941class CopyGrantsProperty(Property):
1942    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1945class DataBlocksizeProperty(Property):
1946    arg_types = {
1947        "size": False,
1948        "units": False,
1949        "minimum": False,
1950        "maximum": False,
1951        "default": False,
1952    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1955class DefinerProperty(Property):
1956    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1959class DistKeyProperty(Property):
1960    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1963class DistStyleProperty(Property):
1964    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1967class EngineProperty(Property):
1968    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
1971class HeapProperty(Property):
1972    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
1975class ToTableProperty(Property):
1976    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1979class ExecuteAsProperty(Property):
1980    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1983class ExternalProperty(Property):
1984    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1987class FallbackProperty(Property):
1988    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1991class FileFormatProperty(Property):
1992    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1995class FreespaceProperty(Property):
1996    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1999class InputOutputFormat(Expression):
2000    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
2003class IsolatedLoadingProperty(Property):
2004    arg_types = {
2005        "no": True,
2006        "concurrent": True,
2007        "for_all": True,
2008        "for_insert": True,
2009        "for_none": True,
2010    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
2013class JournalProperty(Property):
2014    arg_types = {
2015        "no": False,
2016        "dual": False,
2017        "before": False,
2018        "local": False,
2019        "after": False,
2020    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
2023class LanguageProperty(Property):
2024    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
2028class ClusteredByProperty(Property):
2029    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
2032class DictProperty(Property):
2033    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2036class DictSubProperty(Property):
2037    pass
key = 'dictsubproperty'
class DictRange(Property):
2040class DictRange(Property):
2041    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2046class OnCluster(Property):
2047    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2050class LikeProperty(Property):
2051    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2054class LocationProperty(Property):
2055    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2058class LockingProperty(Property):
2059    arg_types = {
2060        "this": False,
2061        "kind": True,
2062        "for_or_in": True,
2063        "lock_type": True,
2064        "override": False,
2065    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2068class LogProperty(Property):
2069    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2072class MaterializedProperty(Property):
2073    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2076class MergeBlockRatioProperty(Property):
2077    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):
2080class NoPrimaryIndexProperty(Property):
2081    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnProperty(Property):
2084class OnProperty(Property):
2085    arg_types = {"this": True}
arg_types = {'this': True}
key = 'onproperty'
class OnCommitProperty(Property):
2088class OnCommitProperty(Property):
2089    arg_types = {"delete": False}
arg_types = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2092class PartitionedByProperty(Property):
2093    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2096class ReturnsProperty(Property):
2097    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2100class RowFormatProperty(Property):
2101    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2104class RowFormatDelimitedProperty(Property):
2105    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2106    arg_types = {
2107        "fields": False,
2108        "escaped": False,
2109        "collection_items": False,
2110        "map_keys": False,
2111        "lines": False,
2112        "null": False,
2113        "serde": False,
2114    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2117class RowFormatSerdeProperty(Property):
2118    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2122class QueryTransform(Expression):
2123    arg_types = {
2124        "expressions": True,
2125        "command_script": True,
2126        "schema": False,
2127        "row_format_before": False,
2128        "record_writer": False,
2129        "row_format_after": False,
2130        "record_reader": False,
2131    }
arg_types = {'expressions': True, 'command_script': True, 'schema': False, 'row_format_before': False, 'record_writer': False, 'row_format_after': False, 'record_reader': False}
key = 'querytransform'
class SchemaCommentProperty(Property):
2134class SchemaCommentProperty(Property):
2135    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2138class SerdeProperties(Property):
2139    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2142class SetProperty(Property):
2143    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2146class SettingsProperty(Property):
2147    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2150class SortKeyProperty(Property):
2151    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2154class SqlSecurityProperty(Property):
2155    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2158class StabilityProperty(Property):
2159    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2162class TemporaryProperty(Property):
2163    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2166class TransientProperty(Property):
2167    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2170class VolatileProperty(Property):
2171    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2174class WithDataProperty(Property):
2175    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2178class WithJournalTableProperty(Property):
2179    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2182class Properties(Expression):
2183    arg_types = {"expressions": True}
2184
2185    NAME_TO_PROPERTY = {
2186        "ALGORITHM": AlgorithmProperty,
2187        "AUTO_INCREMENT": AutoIncrementProperty,
2188        "CHARACTER SET": CharacterSetProperty,
2189        "CLUSTERED_BY": ClusteredByProperty,
2190        "COLLATE": CollateProperty,
2191        "COMMENT": SchemaCommentProperty,
2192        "DEFINER": DefinerProperty,
2193        "DISTKEY": DistKeyProperty,
2194        "DISTSTYLE": DistStyleProperty,
2195        "ENGINE": EngineProperty,
2196        "EXECUTE AS": ExecuteAsProperty,
2197        "FORMAT": FileFormatProperty,
2198        "LANGUAGE": LanguageProperty,
2199        "LOCATION": LocationProperty,
2200        "PARTITIONED_BY": PartitionedByProperty,
2201        "RETURNS": ReturnsProperty,
2202        "ROW_FORMAT": RowFormatProperty,
2203        "SORTKEY": SortKeyProperty,
2204    }
2205
2206    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2207
2208    # CREATE property locations
2209    # Form: schema specified
2210    #   create [POST_CREATE]
2211    #     table a [POST_NAME]
2212    #     (b int) [POST_SCHEMA]
2213    #     with ([POST_WITH])
2214    #     index (b) [POST_INDEX]
2215    #
2216    # Form: alias selection
2217    #   create [POST_CREATE]
2218    #     table a [POST_NAME]
2219    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2220    #     index (c) [POST_INDEX]
2221    class Location(AutoName):
2222        POST_CREATE = auto()
2223        POST_NAME = auto()
2224        POST_SCHEMA = auto()
2225        POST_WITH = auto()
2226        POST_ALIAS = auto()
2227        POST_EXPRESSION = auto()
2228        POST_INDEX = auto()
2229        UNSUPPORTED = auto()
2230
2231    @classmethod
2232    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2233        expressions = []
2234        for key, value in properties_dict.items():
2235            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2236            if property_cls:
2237                expressions.append(property_cls(this=convert(value)))
2238            else:
2239                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2240
2241        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:
2231    @classmethod
2232    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2233        expressions = []
2234        for key, value in properties_dict.items():
2235            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2236            if property_cls:
2237                expressions.append(property_cls(this=convert(value)))
2238            else:
2239                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2240
2241        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2221    class Location(AutoName):
2222        POST_CREATE = auto()
2223        POST_NAME = auto()
2224        POST_SCHEMA = auto()
2225        POST_WITH = auto()
2226        POST_ALIAS = auto()
2227        POST_EXPRESSION = auto()
2228        POST_INDEX = auto()
2229        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):
2244class Qualify(Expression):
2245    pass
key = 'qualify'
class Return(Expression):
2249class Return(Expression):
2250    pass
key = 'return'
class Reference(Expression):
2253class Reference(Expression):
2254    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2257class Tuple(Expression):
2258    arg_types = {"expressions": False}
2259
2260    def isin(
2261        self,
2262        *expressions: t.Any,
2263        query: t.Optional[ExpOrStr] = None,
2264        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2265        copy: bool = True,
2266        **opts,
2267    ) -> In:
2268        return In(
2269            this=maybe_copy(self, copy),
2270            expressions=[convert(e, copy=copy) for e in expressions],
2271            query=maybe_parse(query, copy=copy, **opts) if query else None,
2272            unnest=Unnest(
2273                expressions=[
2274                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2275                ]
2276            )
2277            if unnest
2278            else None,
2279        )
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:
2260    def isin(
2261        self,
2262        *expressions: t.Any,
2263        query: t.Optional[ExpOrStr] = None,
2264        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2265        copy: bool = True,
2266        **opts,
2267    ) -> In:
2268        return In(
2269            this=maybe_copy(self, copy),
2270            expressions=[convert(e, copy=copy) for e in expressions],
2271            query=maybe_parse(query, copy=copy, **opts) if query else None,
2272            unnest=Unnest(
2273                expressions=[
2274                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2275                ]
2276            )
2277            if unnest
2278            else None,
2279        )
key = 'tuple'
class Subqueryable(Unionable):
2282class Subqueryable(Unionable):
2283    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2284        """
2285        Convert this expression to an aliased expression that can be used as a Subquery.
2286
2287        Example:
2288            >>> subquery = Select().select("x").from_("tbl").subquery()
2289            >>> Select().select("x").from_(subquery).sql()
2290            'SELECT x FROM (SELECT x FROM tbl)'
2291
2292        Args:
2293            alias (str | Identifier): an optional alias for the subquery
2294            copy (bool): if `False`, modify this expression instance in-place.
2295
2296        Returns:
2297            Alias: the subquery
2298        """
2299        instance = maybe_copy(self, copy)
2300        if not isinstance(alias, Expression):
2301            alias = TableAlias(this=to_identifier(alias)) if alias else None
2302
2303        return Subquery(this=instance, alias=alias)
2304
2305    def limit(
2306        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2307    ) -> Select:
2308        raise NotImplementedError
2309
2310    @property
2311    def ctes(self):
2312        with_ = self.args.get("with")
2313        if not with_:
2314            return []
2315        return with_.expressions
2316
2317    @property
2318    def selects(self) -> t.List[Expression]:
2319        raise NotImplementedError("Subqueryable objects must implement `selects`")
2320
2321    @property
2322    def named_selects(self) -> t.List[str]:
2323        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2324
2325    def select(
2326        self,
2327        *expressions: t.Optional[ExpOrStr],
2328        append: bool = True,
2329        dialect: DialectType = None,
2330        copy: bool = True,
2331        **opts,
2332    ) -> Subqueryable:
2333        raise NotImplementedError("Subqueryable objects must implement `select`")
2334
2335    def with_(
2336        self,
2337        alias: ExpOrStr,
2338        as_: ExpOrStr,
2339        recursive: t.Optional[bool] = None,
2340        append: bool = True,
2341        dialect: DialectType = None,
2342        copy: bool = True,
2343        **opts,
2344    ) -> Subqueryable:
2345        """
2346        Append to or set the common table expressions.
2347
2348        Example:
2349            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2350            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2351
2352        Args:
2353            alias: the SQL code string to parse as the table name.
2354                If an `Expression` instance is passed, this is used as-is.
2355            as_: the SQL code string to parse as the table expression.
2356                If an `Expression` instance is passed, it will be used as-is.
2357            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2358            append: if `True`, add to any existing expressions.
2359                Otherwise, this resets the expressions.
2360            dialect: the dialect used to parse the input expression.
2361            copy: if `False`, modify this expression instance in-place.
2362            opts: other options to use to parse the input expressions.
2363
2364        Returns:
2365            The modified expression.
2366        """
2367        return _apply_cte_builder(
2368            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2369        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2283    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2284        """
2285        Convert this expression to an aliased expression that can be used as a Subquery.
2286
2287        Example:
2288            >>> subquery = Select().select("x").from_("tbl").subquery()
2289            >>> Select().select("x").from_(subquery).sql()
2290            'SELECT x FROM (SELECT x FROM tbl)'
2291
2292        Args:
2293            alias (str | Identifier): an optional alias for the subquery
2294            copy (bool): if `False`, modify this expression instance in-place.
2295
2296        Returns:
2297            Alias: the subquery
2298        """
2299        instance = maybe_copy(self, copy)
2300        if not isinstance(alias, Expression):
2301            alias = TableAlias(this=to_identifier(alias)) if alias else None
2302
2303        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:
2305    def limit(
2306        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2307    ) -> Select:
2308        raise NotImplementedError
ctes
named_selects: List[str]
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.Subqueryable:
2325    def select(
2326        self,
2327        *expressions: t.Optional[ExpOrStr],
2328        append: bool = True,
2329        dialect: DialectType = None,
2330        copy: bool = True,
2331        **opts,
2332    ) -> Subqueryable:
2333        raise NotImplementedError("Subqueryable objects must implement `select`")
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:
2335    def with_(
2336        self,
2337        alias: ExpOrStr,
2338        as_: ExpOrStr,
2339        recursive: t.Optional[bool] = None,
2340        append: bool = True,
2341        dialect: DialectType = None,
2342        copy: bool = True,
2343        **opts,
2344    ) -> Subqueryable:
2345        """
2346        Append to or set the common table expressions.
2347
2348        Example:
2349            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2350            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2351
2352        Args:
2353            alias: the SQL code string to parse as the table name.
2354                If an `Expression` instance is passed, this is used as-is.
2355            as_: the SQL code string to parse as the table expression.
2356                If an `Expression` instance is passed, it will be used as-is.
2357            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2358            append: if `True`, add to any existing expressions.
2359                Otherwise, this resets the expressions.
2360            dialect: the dialect used to parse the input expression.
2361            copy: if `False`, modify this expression instance in-place.
2362            opts: other options to use to parse the input expressions.
2363
2364        Returns:
2365            The modified expression.
2366        """
2367        return _apply_cte_builder(
2368            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2369        )

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, 'connect': 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):
2397class WithTableHint(Expression):
2398    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2402class IndexTableHint(Expression):
2403    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2406class Table(Expression):
2407    arg_types = {
2408        "this": True,
2409        "alias": False,
2410        "db": False,
2411        "catalog": False,
2412        "laterals": False,
2413        "joins": False,
2414        "pivots": False,
2415        "hints": False,
2416        "system_time": False,
2417        "version": False,
2418    }
2419
2420    @property
2421    def name(self) -> str:
2422        if isinstance(self.this, Func):
2423            return ""
2424        return self.this.name
2425
2426    @property
2427    def db(self) -> str:
2428        return self.text("db")
2429
2430    @property
2431    def catalog(self) -> str:
2432        return self.text("catalog")
2433
2434    @property
2435    def selects(self) -> t.List[Expression]:
2436        return []
2437
2438    @property
2439    def named_selects(self) -> t.List[str]:
2440        return []
2441
2442    @property
2443    def parts(self) -> t.List[Identifier]:
2444        """Return the parts of a table in order catalog, db, table."""
2445        parts: t.List[Identifier] = []
2446
2447        for arg in ("catalog", "db", "this"):
2448            part = self.args.get(arg)
2449
2450            if isinstance(part, Identifier):
2451                parts.append(part)
2452            elif isinstance(part, Dot):
2453                parts.extend(part.flatten())
2454
2455        return parts
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False, 'version': 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 Union(Subqueryable):
2458class Union(Subqueryable):
2459    arg_types = {
2460        "with": False,
2461        "this": True,
2462        "expression": True,
2463        "distinct": False,
2464        "by_name": False,
2465        **QUERY_MODIFIERS,
2466    }
2467
2468    def limit(
2469        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2470    ) -> Select:
2471        """
2472        Set the LIMIT expression.
2473
2474        Example:
2475            >>> select("1").union(select("1")).limit(1).sql()
2476            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2477
2478        Args:
2479            expression: the SQL code string to parse.
2480                This can also be an integer.
2481                If a `Limit` instance is passed, this is used as-is.
2482                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2483            dialect: the dialect used to parse the input expression.
2484            copy: if `False`, modify this expression instance in-place.
2485            opts: other options to use to parse the input expressions.
2486
2487        Returns:
2488            The limited subqueryable.
2489        """
2490        return (
2491            select("*")
2492            .from_(self.subquery(alias="_l_0", copy=copy))
2493            .limit(expression, dialect=dialect, copy=False, **opts)
2494        )
2495
2496    def select(
2497        self,
2498        *expressions: t.Optional[ExpOrStr],
2499        append: bool = True,
2500        dialect: DialectType = None,
2501        copy: bool = True,
2502        **opts,
2503    ) -> Union:
2504        """Append to or set the SELECT of the union recursively.
2505
2506        Example:
2507            >>> from sqlglot import parse_one
2508            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2509            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2510
2511        Args:
2512            *expressions: the SQL code strings to parse.
2513                If an `Expression` instance is passed, it will be used as-is.
2514            append: if `True`, add to any existing expressions.
2515                Otherwise, this resets the expressions.
2516            dialect: the dialect used to parse the input expressions.
2517            copy: if `False`, modify this expression instance in-place.
2518            opts: other options to use to parse the input expressions.
2519
2520        Returns:
2521            Union: the modified expression.
2522        """
2523        this = self.copy() if copy else self
2524        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2525        this.expression.unnest().select(
2526            *expressions, append=append, dialect=dialect, copy=False, **opts
2527        )
2528        return this
2529
2530    @property
2531    def named_selects(self) -> t.List[str]:
2532        return self.this.unnest().named_selects
2533
2534    @property
2535    def is_star(self) -> bool:
2536        return self.this.is_star or self.expression.is_star
2537
2538    @property
2539    def selects(self) -> t.List[Expression]:
2540        return self.this.unnest().selects
2541
2542    @property
2543    def left(self):
2544        return self.this
2545
2546    @property
2547    def right(self):
2548        return self.expression
arg_types = {'with': False, 'this': True, 'expression': True, 'distinct': False, 'by_name': False, 'match': False, 'laterals': False, 'joins': False, 'connect': 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:
2468    def limit(
2469        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2470    ) -> Select:
2471        """
2472        Set the LIMIT expression.
2473
2474        Example:
2475            >>> select("1").union(select("1")).limit(1).sql()
2476            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2477
2478        Args:
2479            expression: the SQL code string to parse.
2480                This can also be an integer.
2481                If a `Limit` instance is passed, this is used as-is.
2482                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2483            dialect: the dialect used to parse the input expression.
2484            copy: if `False`, modify this expression instance in-place.
2485            opts: other options to use to parse the input expressions.
2486
2487        Returns:
2488            The limited subqueryable.
2489        """
2490        return (
2491            select("*")
2492            .from_(self.subquery(alias="_l_0", copy=copy))
2493            .limit(expression, dialect=dialect, copy=False, **opts)
2494        )

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:
2496    def select(
2497        self,
2498        *expressions: t.Optional[ExpOrStr],
2499        append: bool = True,
2500        dialect: DialectType = None,
2501        copy: bool = True,
2502        **opts,
2503    ) -> Union:
2504        """Append to or set the SELECT of the union recursively.
2505
2506        Example:
2507            >>> from sqlglot import parse_one
2508            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2509            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2510
2511        Args:
2512            *expressions: the SQL code strings to parse.
2513                If an `Expression` instance is passed, it will be used as-is.
2514            append: if `True`, add to any existing expressions.
2515                Otherwise, this resets the expressions.
2516            dialect: the dialect used to parse the input expressions.
2517            copy: if `False`, modify this expression instance in-place.
2518            opts: other options to use to parse the input expressions.
2519
2520        Returns:
2521            Union: the modified expression.
2522        """
2523        this = self.copy() if copy else self
2524        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2525        this.expression.unnest().select(
2526            *expressions, append=append, dialect=dialect, copy=False, **opts
2527        )
2528        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):
2551class Except(Union):
2552    pass
key = 'except'
class Intersect(Union):
2555class Intersect(Union):
2556    pass
key = 'intersect'
class Unnest(UDTF):
2559class Unnest(UDTF):
2560    arg_types = {
2561        "expressions": True,
2562        "ordinality": False,
2563        "alias": False,
2564        "offset": False,
2565    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False, 'offset': False}
key = 'unnest'
class Update(Expression):
2568class Update(Expression):
2569    arg_types = {
2570        "with": False,
2571        "this": False,
2572        "expressions": True,
2573        "from": False,
2574        "where": False,
2575        "returning": False,
2576        "order": False,
2577        "limit": False,
2578    }
arg_types = {'with': False, 'this': False, 'expressions': True, 'from': False, 'where': False, 'returning': False, 'order': False, 'limit': False}
key = 'update'
class Values(UDTF):
2581class Values(UDTF):
2582    arg_types = {
2583        "expressions": True,
2584        "ordinality": False,
2585        "alias": False,
2586    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False}
key = 'values'
class Var(Expression):
2589class Var(Expression):
2590    pass
key = 'var'
class Version(Expression):
2593class Version(Expression):
2594    """
2595    Time travel, iceberg, bigquery etc
2596    https://trino.io/docs/current/connector/iceberg.html?highlight=snapshot#using-snapshots
2597    https://www.databricks.com/blog/2019/02/04/introducing-delta-time-travel-for-large-scale-data-lakes.html
2598    https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#for_system_time_as_of
2599    https://learn.microsoft.com/en-us/sql/relational-databases/tables/querying-data-in-a-system-versioned-temporal-table?view=sql-server-ver16
2600    this is either TIMESTAMP or VERSION
2601    kind is ("AS OF", "BETWEEN")
2602    """
2603
2604    arg_types = {"this": True, "kind": True, "expression": False}
arg_types = {'this': True, 'kind': True, 'expression': False}
key = 'version'
class Schema(Expression):
2607class Schema(Expression):
2608    arg_types = {"this": False, "expressions": False}
arg_types = {'this': False, 'expressions': False}
key = 'schema'
class Lock(Expression):
2613class Lock(Expression):
2614    arg_types = {"update": True, "expressions": False, "wait": False}
arg_types = {'update': True, 'expressions': False, 'wait': False}
key = 'lock'
class Select(Subqueryable):
2617class Select(Subqueryable):
2618    arg_types = {
2619        "with": False,
2620        "kind": False,
2621        "expressions": False,
2622        "hint": False,
2623        "distinct": False,
2624        "into": False,
2625        "from": False,
2626        **QUERY_MODIFIERS,
2627    }
2628
2629    def from_(
2630        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2631    ) -> Select:
2632        """
2633        Set the FROM expression.
2634
2635        Example:
2636            >>> Select().from_("tbl").select("x").sql()
2637            'SELECT x FROM tbl'
2638
2639        Args:
2640            expression : the SQL code strings to parse.
2641                If a `From` instance is passed, this is used as-is.
2642                If another `Expression` instance is passed, it will be wrapped in a `From`.
2643            dialect: the dialect used to parse the input expression.
2644            copy: if `False`, modify this expression instance in-place.
2645            opts: other options to use to parse the input expressions.
2646
2647        Returns:
2648            The modified Select expression.
2649        """
2650        return _apply_builder(
2651            expression=expression,
2652            instance=self,
2653            arg="from",
2654            into=From,
2655            prefix="FROM",
2656            dialect=dialect,
2657            copy=copy,
2658            **opts,
2659        )
2660
2661    def group_by(
2662        self,
2663        *expressions: t.Optional[ExpOrStr],
2664        append: bool = True,
2665        dialect: DialectType = None,
2666        copy: bool = True,
2667        **opts,
2668    ) -> Select:
2669        """
2670        Set the GROUP BY expression.
2671
2672        Example:
2673            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2674            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2675
2676        Args:
2677            *expressions: the SQL code strings to parse.
2678                If a `Group` instance is passed, this is used as-is.
2679                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2680                If nothing is passed in then a group by is not applied to the expression
2681            append: if `True`, add to any existing expressions.
2682                Otherwise, this flattens all the `Group` expression into a single expression.
2683            dialect: the dialect used to parse the input expression.
2684            copy: if `False`, modify this expression instance in-place.
2685            opts: other options to use to parse the input expressions.
2686
2687        Returns:
2688            The modified Select expression.
2689        """
2690        if not expressions:
2691            return self if not copy else self.copy()
2692
2693        return _apply_child_list_builder(
2694            *expressions,
2695            instance=self,
2696            arg="group",
2697            append=append,
2698            copy=copy,
2699            prefix="GROUP BY",
2700            into=Group,
2701            dialect=dialect,
2702            **opts,
2703        )
2704
2705    def order_by(
2706        self,
2707        *expressions: t.Optional[ExpOrStr],
2708        append: bool = True,
2709        dialect: DialectType = None,
2710        copy: bool = True,
2711        **opts,
2712    ) -> Select:
2713        """
2714        Set the ORDER BY expression.
2715
2716        Example:
2717            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2718            'SELECT x FROM tbl ORDER BY x DESC'
2719
2720        Args:
2721            *expressions: the SQL code strings to parse.
2722                If a `Group` instance is passed, this is used as-is.
2723                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2724            append: if `True`, add to any existing expressions.
2725                Otherwise, this flattens all the `Order` expression into a single expression.
2726            dialect: the dialect used to parse the input expression.
2727            copy: if `False`, modify this expression instance in-place.
2728            opts: other options to use to parse the input expressions.
2729
2730        Returns:
2731            The modified Select expression.
2732        """
2733        return _apply_child_list_builder(
2734            *expressions,
2735            instance=self,
2736            arg="order",
2737            append=append,
2738            copy=copy,
2739            prefix="ORDER BY",
2740            into=Order,
2741            dialect=dialect,
2742            **opts,
2743        )
2744
2745    def sort_by(
2746        self,
2747        *expressions: t.Optional[ExpOrStr],
2748        append: bool = True,
2749        dialect: DialectType = None,
2750        copy: bool = True,
2751        **opts,
2752    ) -> Select:
2753        """
2754        Set the SORT BY expression.
2755
2756        Example:
2757            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2758            'SELECT x FROM tbl SORT BY x DESC'
2759
2760        Args:
2761            *expressions: the SQL code strings to parse.
2762                If a `Group` instance is passed, this is used as-is.
2763                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2764            append: if `True`, add to any existing expressions.
2765                Otherwise, this flattens all the `Order` expression into a single expression.
2766            dialect: the dialect used to parse the input expression.
2767            copy: if `False`, modify this expression instance in-place.
2768            opts: other options to use to parse the input expressions.
2769
2770        Returns:
2771            The modified Select expression.
2772        """
2773        return _apply_child_list_builder(
2774            *expressions,
2775            instance=self,
2776            arg="sort",
2777            append=append,
2778            copy=copy,
2779            prefix="SORT BY",
2780            into=Sort,
2781            dialect=dialect,
2782            **opts,
2783        )
2784
2785    def cluster_by(
2786        self,
2787        *expressions: t.Optional[ExpOrStr],
2788        append: bool = True,
2789        dialect: DialectType = None,
2790        copy: bool = True,
2791        **opts,
2792    ) -> Select:
2793        """
2794        Set the CLUSTER BY expression.
2795
2796        Example:
2797            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2798            'SELECT x FROM tbl CLUSTER BY x DESC'
2799
2800        Args:
2801            *expressions: the SQL code strings to parse.
2802                If a `Group` instance is passed, this is used as-is.
2803                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2804            append: if `True`, add to any existing expressions.
2805                Otherwise, this flattens all the `Order` expression into a single expression.
2806            dialect: the dialect used to parse the input expression.
2807            copy: if `False`, modify this expression instance in-place.
2808            opts: other options to use to parse the input expressions.
2809
2810        Returns:
2811            The modified Select expression.
2812        """
2813        return _apply_child_list_builder(
2814            *expressions,
2815            instance=self,
2816            arg="cluster",
2817            append=append,
2818            copy=copy,
2819            prefix="CLUSTER BY",
2820            into=Cluster,
2821            dialect=dialect,
2822            **opts,
2823        )
2824
2825    def limit(
2826        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2827    ) -> Select:
2828        """
2829        Set the LIMIT expression.
2830
2831        Example:
2832            >>> Select().from_("tbl").select("x").limit(10).sql()
2833            'SELECT x FROM tbl LIMIT 10'
2834
2835        Args:
2836            expression: the SQL code string to parse.
2837                This can also be an integer.
2838                If a `Limit` instance is passed, this is used as-is.
2839                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2840            dialect: the dialect used to parse the input expression.
2841            copy: if `False`, modify this expression instance in-place.
2842            opts: other options to use to parse the input expressions.
2843
2844        Returns:
2845            Select: the modified expression.
2846        """
2847        return _apply_builder(
2848            expression=expression,
2849            instance=self,
2850            arg="limit",
2851            into=Limit,
2852            prefix="LIMIT",
2853            dialect=dialect,
2854            copy=copy,
2855            **opts,
2856        )
2857
2858    def offset(
2859        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2860    ) -> Select:
2861        """
2862        Set the OFFSET expression.
2863
2864        Example:
2865            >>> Select().from_("tbl").select("x").offset(10).sql()
2866            'SELECT x FROM tbl OFFSET 10'
2867
2868        Args:
2869            expression: the SQL code string to parse.
2870                This can also be an integer.
2871                If a `Offset` instance is passed, this is used as-is.
2872                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2873            dialect: the dialect used to parse the input expression.
2874            copy: if `False`, modify this expression instance in-place.
2875            opts: other options to use to parse the input expressions.
2876
2877        Returns:
2878            The modified Select expression.
2879        """
2880        return _apply_builder(
2881            expression=expression,
2882            instance=self,
2883            arg="offset",
2884            into=Offset,
2885            prefix="OFFSET",
2886            dialect=dialect,
2887            copy=copy,
2888            **opts,
2889        )
2890
2891    def select(
2892        self,
2893        *expressions: t.Optional[ExpOrStr],
2894        append: bool = True,
2895        dialect: DialectType = None,
2896        copy: bool = True,
2897        **opts,
2898    ) -> Select:
2899        """
2900        Append to or set the SELECT expressions.
2901
2902        Example:
2903            >>> Select().select("x", "y").sql()
2904            'SELECT x, y'
2905
2906        Args:
2907            *expressions: the SQL code strings to parse.
2908                If an `Expression` instance is passed, it will be used as-is.
2909            append: if `True`, add to any existing expressions.
2910                Otherwise, this resets the expressions.
2911            dialect: the dialect used to parse the input expressions.
2912            copy: if `False`, modify this expression instance in-place.
2913            opts: other options to use to parse the input expressions.
2914
2915        Returns:
2916            The modified Select expression.
2917        """
2918        return _apply_list_builder(
2919            *expressions,
2920            instance=self,
2921            arg="expressions",
2922            append=append,
2923            dialect=dialect,
2924            copy=copy,
2925            **opts,
2926        )
2927
2928    def lateral(
2929        self,
2930        *expressions: t.Optional[ExpOrStr],
2931        append: bool = True,
2932        dialect: DialectType = None,
2933        copy: bool = True,
2934        **opts,
2935    ) -> Select:
2936        """
2937        Append to or set the LATERAL expressions.
2938
2939        Example:
2940            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2941            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2942
2943        Args:
2944            *expressions: the SQL code strings to parse.
2945                If an `Expression` instance is passed, it will be used as-is.
2946            append: if `True`, add to any existing expressions.
2947                Otherwise, this resets the expressions.
2948            dialect: the dialect used to parse the input expressions.
2949            copy: if `False`, modify this expression instance in-place.
2950            opts: other options to use to parse the input expressions.
2951
2952        Returns:
2953            The modified Select expression.
2954        """
2955        return _apply_list_builder(
2956            *expressions,
2957            instance=self,
2958            arg="laterals",
2959            append=append,
2960            into=Lateral,
2961            prefix="LATERAL VIEW",
2962            dialect=dialect,
2963            copy=copy,
2964            **opts,
2965        )
2966
2967    def join(
2968        self,
2969        expression: ExpOrStr,
2970        on: t.Optional[ExpOrStr] = None,
2971        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
2972        append: bool = True,
2973        join_type: t.Optional[str] = None,
2974        join_alias: t.Optional[Identifier | str] = None,
2975        dialect: DialectType = None,
2976        copy: bool = True,
2977        **opts,
2978    ) -> Select:
2979        """
2980        Append to or set the JOIN expressions.
2981
2982        Example:
2983            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2984            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2985
2986            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2987            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2988
2989            Use `join_type` to change the type of join:
2990
2991            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2992            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2993
2994        Args:
2995            expression: the SQL code string to parse.
2996                If an `Expression` instance is passed, it will be used as-is.
2997            on: optionally specify the join "on" criteria as a SQL string.
2998                If an `Expression` instance is passed, it will be used as-is.
2999            using: optionally specify the join "using" criteria as a SQL string.
3000                If an `Expression` instance is passed, it will be used as-is.
3001            append: if `True`, add to any existing expressions.
3002                Otherwise, this resets the expressions.
3003            join_type: if set, alter the parsed join type.
3004            join_alias: an optional alias for the joined source.
3005            dialect: the dialect used to parse the input expressions.
3006            copy: if `False`, modify this expression instance in-place.
3007            opts: other options to use to parse the input expressions.
3008
3009        Returns:
3010            Select: the modified expression.
3011        """
3012        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
3013
3014        try:
3015            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
3016        except ParseError:
3017            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
3018
3019        join = expression if isinstance(expression, Join) else Join(this=expression)
3020
3021        if isinstance(join.this, Select):
3022            join.this.replace(join.this.subquery())
3023
3024        if join_type:
3025            method: t.Optional[Token]
3026            side: t.Optional[Token]
3027            kind: t.Optional[Token]
3028
3029            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
3030
3031            if method:
3032                join.set("method", method.text)
3033            if side:
3034                join.set("side", side.text)
3035            if kind:
3036                join.set("kind", kind.text)
3037
3038        if on:
3039            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
3040            join.set("on", on)
3041
3042        if using:
3043            join = _apply_list_builder(
3044                *ensure_list(using),
3045                instance=join,
3046                arg="using",
3047                append=append,
3048                copy=copy,
3049                into=Identifier,
3050                **opts,
3051            )
3052
3053        if join_alias:
3054            join.set("this", alias_(join.this, join_alias, table=True))
3055
3056        return _apply_list_builder(
3057            join,
3058            instance=self,
3059            arg="joins",
3060            append=append,
3061            copy=copy,
3062            **opts,
3063        )
3064
3065    def where(
3066        self,
3067        *expressions: t.Optional[ExpOrStr],
3068        append: bool = True,
3069        dialect: DialectType = None,
3070        copy: bool = True,
3071        **opts,
3072    ) -> Select:
3073        """
3074        Append to or set the WHERE expressions.
3075
3076        Example:
3077            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3078            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3079
3080        Args:
3081            *expressions: the SQL code strings to parse.
3082                If an `Expression` instance is passed, it will be used as-is.
3083                Multiple expressions are combined with an AND operator.
3084            append: if `True`, AND the new expressions to any existing expression.
3085                Otherwise, this resets the expression.
3086            dialect: the dialect used to parse the input expressions.
3087            copy: if `False`, modify this expression instance in-place.
3088            opts: other options to use to parse the input expressions.
3089
3090        Returns:
3091            Select: the modified expression.
3092        """
3093        return _apply_conjunction_builder(
3094            *expressions,
3095            instance=self,
3096            arg="where",
3097            append=append,
3098            into=Where,
3099            dialect=dialect,
3100            copy=copy,
3101            **opts,
3102        )
3103
3104    def having(
3105        self,
3106        *expressions: t.Optional[ExpOrStr],
3107        append: bool = True,
3108        dialect: DialectType = None,
3109        copy: bool = True,
3110        **opts,
3111    ) -> Select:
3112        """
3113        Append to or set the HAVING expressions.
3114
3115        Example:
3116            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3117            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3118
3119        Args:
3120            *expressions: the SQL code strings to parse.
3121                If an `Expression` instance is passed, it will be used as-is.
3122                Multiple expressions are combined with an AND operator.
3123            append: if `True`, AND the new expressions to any existing expression.
3124                Otherwise, this resets the expression.
3125            dialect: the dialect used to parse the input expressions.
3126            copy: if `False`, modify this expression instance in-place.
3127            opts: other options to use to parse the input expressions.
3128
3129        Returns:
3130            The modified Select expression.
3131        """
3132        return _apply_conjunction_builder(
3133            *expressions,
3134            instance=self,
3135            arg="having",
3136            append=append,
3137            into=Having,
3138            dialect=dialect,
3139            copy=copy,
3140            **opts,
3141        )
3142
3143    def window(
3144        self,
3145        *expressions: t.Optional[ExpOrStr],
3146        append: bool = True,
3147        dialect: DialectType = None,
3148        copy: bool = True,
3149        **opts,
3150    ) -> Select:
3151        return _apply_list_builder(
3152            *expressions,
3153            instance=self,
3154            arg="windows",
3155            append=append,
3156            into=Window,
3157            dialect=dialect,
3158            copy=copy,
3159            **opts,
3160        )
3161
3162    def qualify(
3163        self,
3164        *expressions: t.Optional[ExpOrStr],
3165        append: bool = True,
3166        dialect: DialectType = None,
3167        copy: bool = True,
3168        **opts,
3169    ) -> Select:
3170        return _apply_conjunction_builder(
3171            *expressions,
3172            instance=self,
3173            arg="qualify",
3174            append=append,
3175            into=Qualify,
3176            dialect=dialect,
3177            copy=copy,
3178            **opts,
3179        )
3180
3181    def distinct(
3182        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3183    ) -> Select:
3184        """
3185        Set the OFFSET expression.
3186
3187        Example:
3188            >>> Select().from_("tbl").select("x").distinct().sql()
3189            'SELECT DISTINCT x FROM tbl'
3190
3191        Args:
3192            ons: the expressions to distinct on
3193            distinct: whether the Select should be distinct
3194            copy: if `False`, modify this expression instance in-place.
3195
3196        Returns:
3197            Select: the modified expression.
3198        """
3199        instance = maybe_copy(self, copy)
3200        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3201        instance.set("distinct", Distinct(on=on) if distinct else None)
3202        return instance
3203
3204    def ctas(
3205        self,
3206        table: ExpOrStr,
3207        properties: t.Optional[t.Dict] = None,
3208        dialect: DialectType = None,
3209        copy: bool = True,
3210        **opts,
3211    ) -> Create:
3212        """
3213        Convert this expression to a CREATE TABLE AS statement.
3214
3215        Example:
3216            >>> Select().select("*").from_("tbl").ctas("x").sql()
3217            'CREATE TABLE x AS SELECT * FROM tbl'
3218
3219        Args:
3220            table: the SQL code string to parse as the table name.
3221                If another `Expression` instance is passed, it will be used as-is.
3222            properties: an optional mapping of table properties
3223            dialect: the dialect used to parse the input table.
3224            copy: if `False`, modify this expression instance in-place.
3225            opts: other options to use to parse the input table.
3226
3227        Returns:
3228            The new Create expression.
3229        """
3230        instance = maybe_copy(self, copy)
3231        table_expression = maybe_parse(
3232            table,
3233            into=Table,
3234            dialect=dialect,
3235            **opts,
3236        )
3237        properties_expression = None
3238        if properties:
3239            properties_expression = Properties.from_dict(properties)
3240
3241        return Create(
3242            this=table_expression,
3243            kind="table",
3244            expression=instance,
3245            properties=properties_expression,
3246        )
3247
3248    def lock(self, update: bool = True, copy: bool = True) -> Select:
3249        """
3250        Set the locking read mode for this expression.
3251
3252        Examples:
3253            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3254            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3255
3256            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3257            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3258
3259        Args:
3260            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3261            copy: if `False`, modify this expression instance in-place.
3262
3263        Returns:
3264            The modified expression.
3265        """
3266        inst = maybe_copy(self, copy)
3267        inst.set("locks", [Lock(update=update)])
3268
3269        return inst
3270
3271    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3272        """
3273        Set hints for this expression.
3274
3275        Examples:
3276            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3277            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3278
3279        Args:
3280            hints: The SQL code strings to parse as the hints.
3281                If an `Expression` instance is passed, it will be used as-is.
3282            dialect: The dialect used to parse the hints.
3283            copy: If `False`, modify this expression instance in-place.
3284
3285        Returns:
3286            The modified expression.
3287        """
3288        inst = maybe_copy(self, copy)
3289        inst.set(
3290            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3291        )
3292
3293        return inst
3294
3295    @property
3296    def named_selects(self) -> t.List[str]:
3297        return [e.output_name for e in self.expressions if e.alias_or_name]
3298
3299    @property
3300    def is_star(self) -> bool:
3301        return any(expression.is_star for expression in self.expressions)
3302
3303    @property
3304    def selects(self) -> t.List[Expression]:
3305        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, 'connect': 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:
2629    def from_(
2630        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2631    ) -> Select:
2632        """
2633        Set the FROM expression.
2634
2635        Example:
2636            >>> Select().from_("tbl").select("x").sql()
2637            'SELECT x FROM tbl'
2638
2639        Args:
2640            expression : the SQL code strings to parse.
2641                If a `From` instance is passed, this is used as-is.
2642                If another `Expression` instance is passed, it will be wrapped in a `From`.
2643            dialect: the dialect used to parse the input expression.
2644            copy: if `False`, modify this expression instance in-place.
2645            opts: other options to use to parse the input expressions.
2646
2647        Returns:
2648            The modified Select expression.
2649        """
2650        return _apply_builder(
2651            expression=expression,
2652            instance=self,
2653            arg="from",
2654            into=From,
2655            prefix="FROM",
2656            dialect=dialect,
2657            copy=copy,
2658            **opts,
2659        )

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:
2661    def group_by(
2662        self,
2663        *expressions: t.Optional[ExpOrStr],
2664        append: bool = True,
2665        dialect: DialectType = None,
2666        copy: bool = True,
2667        **opts,
2668    ) -> Select:
2669        """
2670        Set the GROUP BY expression.
2671
2672        Example:
2673            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2674            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2675
2676        Args:
2677            *expressions: the SQL code strings to parse.
2678                If a `Group` instance is passed, this is used as-is.
2679                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2680                If nothing is passed in then a group by is not applied to the expression
2681            append: if `True`, add to any existing expressions.
2682                Otherwise, this flattens all the `Group` expression into a single expression.
2683            dialect: the dialect used to parse the input expression.
2684            copy: if `False`, modify this expression instance in-place.
2685            opts: other options to use to parse the input expressions.
2686
2687        Returns:
2688            The modified Select expression.
2689        """
2690        if not expressions:
2691            return self if not copy else self.copy()
2692
2693        return _apply_child_list_builder(
2694            *expressions,
2695            instance=self,
2696            arg="group",
2697            append=append,
2698            copy=copy,
2699            prefix="GROUP BY",
2700            into=Group,
2701            dialect=dialect,
2702            **opts,
2703        )

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:
2705    def order_by(
2706        self,
2707        *expressions: t.Optional[ExpOrStr],
2708        append: bool = True,
2709        dialect: DialectType = None,
2710        copy: bool = True,
2711        **opts,
2712    ) -> Select:
2713        """
2714        Set the ORDER BY expression.
2715
2716        Example:
2717            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2718            'SELECT x FROM tbl ORDER BY x DESC'
2719
2720        Args:
2721            *expressions: the SQL code strings to parse.
2722                If a `Group` instance is passed, this is used as-is.
2723                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2724            append: if `True`, add to any existing expressions.
2725                Otherwise, this flattens all the `Order` expression into a single expression.
2726            dialect: the dialect used to parse the input expression.
2727            copy: if `False`, modify this expression instance in-place.
2728            opts: other options to use to parse the input expressions.
2729
2730        Returns:
2731            The modified Select expression.
2732        """
2733        return _apply_child_list_builder(
2734            *expressions,
2735            instance=self,
2736            arg="order",
2737            append=append,
2738            copy=copy,
2739            prefix="ORDER BY",
2740            into=Order,
2741            dialect=dialect,
2742            **opts,
2743        )

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:
2745    def sort_by(
2746        self,
2747        *expressions: t.Optional[ExpOrStr],
2748        append: bool = True,
2749        dialect: DialectType = None,
2750        copy: bool = True,
2751        **opts,
2752    ) -> Select:
2753        """
2754        Set the SORT BY expression.
2755
2756        Example:
2757            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2758            'SELECT x FROM tbl SORT BY x DESC'
2759
2760        Args:
2761            *expressions: the SQL code strings to parse.
2762                If a `Group` instance is passed, this is used as-is.
2763                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2764            append: if `True`, add to any existing expressions.
2765                Otherwise, this flattens all the `Order` expression into a single expression.
2766            dialect: the dialect used to parse the input expression.
2767            copy: if `False`, modify this expression instance in-place.
2768            opts: other options to use to parse the input expressions.
2769
2770        Returns:
2771            The modified Select expression.
2772        """
2773        return _apply_child_list_builder(
2774            *expressions,
2775            instance=self,
2776            arg="sort",
2777            append=append,
2778            copy=copy,
2779            prefix="SORT BY",
2780            into=Sort,
2781            dialect=dialect,
2782            **opts,
2783        )

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:
2785    def cluster_by(
2786        self,
2787        *expressions: t.Optional[ExpOrStr],
2788        append: bool = True,
2789        dialect: DialectType = None,
2790        copy: bool = True,
2791        **opts,
2792    ) -> Select:
2793        """
2794        Set the CLUSTER BY expression.
2795
2796        Example:
2797            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2798            'SELECT x FROM tbl CLUSTER BY x DESC'
2799
2800        Args:
2801            *expressions: the SQL code strings to parse.
2802                If a `Group` instance is passed, this is used as-is.
2803                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2804            append: if `True`, add to any existing expressions.
2805                Otherwise, this flattens all the `Order` expression into a single expression.
2806            dialect: the dialect used to parse the input expression.
2807            copy: if `False`, modify this expression instance in-place.
2808            opts: other options to use to parse the input expressions.
2809
2810        Returns:
2811            The modified Select expression.
2812        """
2813        return _apply_child_list_builder(
2814            *expressions,
2815            instance=self,
2816            arg="cluster",
2817            append=append,
2818            copy=copy,
2819            prefix="CLUSTER BY",
2820            into=Cluster,
2821            dialect=dialect,
2822            **opts,
2823        )

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:
2825    def limit(
2826        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2827    ) -> Select:
2828        """
2829        Set the LIMIT expression.
2830
2831        Example:
2832            >>> Select().from_("tbl").select("x").limit(10).sql()
2833            'SELECT x FROM tbl LIMIT 10'
2834
2835        Args:
2836            expression: the SQL code string to parse.
2837                This can also be an integer.
2838                If a `Limit` instance is passed, this is used as-is.
2839                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2840            dialect: the dialect used to parse the input expression.
2841            copy: if `False`, modify this expression instance in-place.
2842            opts: other options to use to parse the input expressions.
2843
2844        Returns:
2845            Select: the modified expression.
2846        """
2847        return _apply_builder(
2848            expression=expression,
2849            instance=self,
2850            arg="limit",
2851            into=Limit,
2852            prefix="LIMIT",
2853            dialect=dialect,
2854            copy=copy,
2855            **opts,
2856        )

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:
2858    def offset(
2859        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2860    ) -> Select:
2861        """
2862        Set the OFFSET expression.
2863
2864        Example:
2865            >>> Select().from_("tbl").select("x").offset(10).sql()
2866            'SELECT x FROM tbl OFFSET 10'
2867
2868        Args:
2869            expression: the SQL code string to parse.
2870                This can also be an integer.
2871                If a `Offset` instance is passed, this is used as-is.
2872                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2873            dialect: the dialect used to parse the input expression.
2874            copy: if `False`, modify this expression instance in-place.
2875            opts: other options to use to parse the input expressions.
2876
2877        Returns:
2878            The modified Select expression.
2879        """
2880        return _apply_builder(
2881            expression=expression,
2882            instance=self,
2883            arg="offset",
2884            into=Offset,
2885            prefix="OFFSET",
2886            dialect=dialect,
2887            copy=copy,
2888            **opts,
2889        )

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:
2891    def select(
2892        self,
2893        *expressions: t.Optional[ExpOrStr],
2894        append: bool = True,
2895        dialect: DialectType = None,
2896        copy: bool = True,
2897        **opts,
2898    ) -> Select:
2899        """
2900        Append to or set the SELECT expressions.
2901
2902        Example:
2903            >>> Select().select("x", "y").sql()
2904            'SELECT x, y'
2905
2906        Args:
2907            *expressions: the SQL code strings to parse.
2908                If an `Expression` instance is passed, it will be used as-is.
2909            append: if `True`, add to any existing expressions.
2910                Otherwise, this resets the expressions.
2911            dialect: the dialect used to parse the input expressions.
2912            copy: if `False`, modify this expression instance in-place.
2913            opts: other options to use to parse the input expressions.
2914
2915        Returns:
2916            The modified Select expression.
2917        """
2918        return _apply_list_builder(
2919            *expressions,
2920            instance=self,
2921            arg="expressions",
2922            append=append,
2923            dialect=dialect,
2924            copy=copy,
2925            **opts,
2926        )

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:
2928    def lateral(
2929        self,
2930        *expressions: t.Optional[ExpOrStr],
2931        append: bool = True,
2932        dialect: DialectType = None,
2933        copy: bool = True,
2934        **opts,
2935    ) -> Select:
2936        """
2937        Append to or set the LATERAL expressions.
2938
2939        Example:
2940            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2941            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2942
2943        Args:
2944            *expressions: the SQL code strings to parse.
2945                If an `Expression` instance is passed, it will be used as-is.
2946            append: if `True`, add to any existing expressions.
2947                Otherwise, this resets the expressions.
2948            dialect: the dialect used to parse the input expressions.
2949            copy: if `False`, modify this expression instance in-place.
2950            opts: other options to use to parse the input expressions.
2951
2952        Returns:
2953            The modified Select expression.
2954        """
2955        return _apply_list_builder(
2956            *expressions,
2957            instance=self,
2958            arg="laterals",
2959            append=append,
2960            into=Lateral,
2961            prefix="LATERAL VIEW",
2962            dialect=dialect,
2963            copy=copy,
2964            **opts,
2965        )

Append to or set the LATERAL expressions.

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

The modified Select expression.

def join( self, expression: Union[str, sqlglot.expressions.Expression], on: Union[str, sqlglot.expressions.Expression, NoneType] = None, using: Union[str, sqlglot.expressions.Expression, Collection[Union[str, sqlglot.expressions.Expression]], NoneType] = None, append: bool = True, join_type: Optional[str] = None, join_alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2967    def join(
2968        self,
2969        expression: ExpOrStr,
2970        on: t.Optional[ExpOrStr] = None,
2971        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
2972        append: bool = True,
2973        join_type: t.Optional[str] = None,
2974        join_alias: t.Optional[Identifier | str] = None,
2975        dialect: DialectType = None,
2976        copy: bool = True,
2977        **opts,
2978    ) -> Select:
2979        """
2980        Append to or set the JOIN expressions.
2981
2982        Example:
2983            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2984            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2985
2986            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2987            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2988
2989            Use `join_type` to change the type of join:
2990
2991            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2992            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2993
2994        Args:
2995            expression: the SQL code string to parse.
2996                If an `Expression` instance is passed, it will be used as-is.
2997            on: optionally specify the join "on" criteria as a SQL string.
2998                If an `Expression` instance is passed, it will be used as-is.
2999            using: optionally specify the join "using" criteria as a SQL string.
3000                If an `Expression` instance is passed, it will be used as-is.
3001            append: if `True`, add to any existing expressions.
3002                Otherwise, this resets the expressions.
3003            join_type: if set, alter the parsed join type.
3004            join_alias: an optional alias for the joined source.
3005            dialect: the dialect used to parse the input expressions.
3006            copy: if `False`, modify this expression instance in-place.
3007            opts: other options to use to parse the input expressions.
3008
3009        Returns:
3010            Select: the modified expression.
3011        """
3012        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
3013
3014        try:
3015            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
3016        except ParseError:
3017            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
3018
3019        join = expression if isinstance(expression, Join) else Join(this=expression)
3020
3021        if isinstance(join.this, Select):
3022            join.this.replace(join.this.subquery())
3023
3024        if join_type:
3025            method: t.Optional[Token]
3026            side: t.Optional[Token]
3027            kind: t.Optional[Token]
3028
3029            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
3030
3031            if method:
3032                join.set("method", method.text)
3033            if side:
3034                join.set("side", side.text)
3035            if kind:
3036                join.set("kind", kind.text)
3037
3038        if on:
3039            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
3040            join.set("on", on)
3041
3042        if using:
3043            join = _apply_list_builder(
3044                *ensure_list(using),
3045                instance=join,
3046                arg="using",
3047                append=append,
3048                copy=copy,
3049                into=Identifier,
3050                **opts,
3051            )
3052
3053        if join_alias:
3054            join.set("this", alias_(join.this, join_alias, table=True))
3055
3056        return _apply_list_builder(
3057            join,
3058            instance=self,
3059            arg="joins",
3060            append=append,
3061            copy=copy,
3062            **opts,
3063        )

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:
3065    def where(
3066        self,
3067        *expressions: t.Optional[ExpOrStr],
3068        append: bool = True,
3069        dialect: DialectType = None,
3070        copy: bool = True,
3071        **opts,
3072    ) -> Select:
3073        """
3074        Append to or set the WHERE expressions.
3075
3076        Example:
3077            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3078            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3079
3080        Args:
3081            *expressions: the SQL code strings to parse.
3082                If an `Expression` instance is passed, it will be used as-is.
3083                Multiple expressions are combined with an AND operator.
3084            append: if `True`, AND the new expressions to any existing expression.
3085                Otherwise, this resets the expression.
3086            dialect: the dialect used to parse the input expressions.
3087            copy: if `False`, modify this expression instance in-place.
3088            opts: other options to use to parse the input expressions.
3089
3090        Returns:
3091            Select: the modified expression.
3092        """
3093        return _apply_conjunction_builder(
3094            *expressions,
3095            instance=self,
3096            arg="where",
3097            append=append,
3098            into=Where,
3099            dialect=dialect,
3100            copy=copy,
3101            **opts,
3102        )

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:
3104    def having(
3105        self,
3106        *expressions: t.Optional[ExpOrStr],
3107        append: bool = True,
3108        dialect: DialectType = None,
3109        copy: bool = True,
3110        **opts,
3111    ) -> Select:
3112        """
3113        Append to or set the HAVING expressions.
3114
3115        Example:
3116            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3117            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3118
3119        Args:
3120            *expressions: the SQL code strings to parse.
3121                If an `Expression` instance is passed, it will be used as-is.
3122                Multiple expressions are combined with an AND operator.
3123            append: if `True`, AND the new expressions to any existing expression.
3124                Otherwise, this resets the expression.
3125            dialect: the dialect used to parse the input expressions.
3126            copy: if `False`, modify this expression instance in-place.
3127            opts: other options to use to parse the input expressions.
3128
3129        Returns:
3130            The modified Select expression.
3131        """
3132        return _apply_conjunction_builder(
3133            *expressions,
3134            instance=self,
3135            arg="having",
3136            append=append,
3137            into=Having,
3138            dialect=dialect,
3139            copy=copy,
3140            **opts,
3141        )

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:
3143    def window(
3144        self,
3145        *expressions: t.Optional[ExpOrStr],
3146        append: bool = True,
3147        dialect: DialectType = None,
3148        copy: bool = True,
3149        **opts,
3150    ) -> Select:
3151        return _apply_list_builder(
3152            *expressions,
3153            instance=self,
3154            arg="windows",
3155            append=append,
3156            into=Window,
3157            dialect=dialect,
3158            copy=copy,
3159            **opts,
3160        )
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:
3162    def qualify(
3163        self,
3164        *expressions: t.Optional[ExpOrStr],
3165        append: bool = True,
3166        dialect: DialectType = None,
3167        copy: bool = True,
3168        **opts,
3169    ) -> Select:
3170        return _apply_conjunction_builder(
3171            *expressions,
3172            instance=self,
3173            arg="qualify",
3174            append=append,
3175            into=Qualify,
3176            dialect=dialect,
3177            copy=copy,
3178            **opts,
3179        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3181    def distinct(
3182        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3183    ) -> Select:
3184        """
3185        Set the OFFSET expression.
3186
3187        Example:
3188            >>> Select().from_("tbl").select("x").distinct().sql()
3189            'SELECT DISTINCT x FROM tbl'
3190
3191        Args:
3192            ons: the expressions to distinct on
3193            distinct: whether the Select should be distinct
3194            copy: if `False`, modify this expression instance in-place.
3195
3196        Returns:
3197            Select: the modified expression.
3198        """
3199        instance = maybe_copy(self, copy)
3200        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3201        instance.set("distinct", Distinct(on=on) if distinct else None)
3202        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:
3204    def ctas(
3205        self,
3206        table: ExpOrStr,
3207        properties: t.Optional[t.Dict] = None,
3208        dialect: DialectType = None,
3209        copy: bool = True,
3210        **opts,
3211    ) -> Create:
3212        """
3213        Convert this expression to a CREATE TABLE AS statement.
3214
3215        Example:
3216            >>> Select().select("*").from_("tbl").ctas("x").sql()
3217            'CREATE TABLE x AS SELECT * FROM tbl'
3218
3219        Args:
3220            table: the SQL code string to parse as the table name.
3221                If another `Expression` instance is passed, it will be used as-is.
3222            properties: an optional mapping of table properties
3223            dialect: the dialect used to parse the input table.
3224            copy: if `False`, modify this expression instance in-place.
3225            opts: other options to use to parse the input table.
3226
3227        Returns:
3228            The new Create expression.
3229        """
3230        instance = maybe_copy(self, copy)
3231        table_expression = maybe_parse(
3232            table,
3233            into=Table,
3234            dialect=dialect,
3235            **opts,
3236        )
3237        properties_expression = None
3238        if properties:
3239            properties_expression = Properties.from_dict(properties)
3240
3241        return Create(
3242            this=table_expression,
3243            kind="table",
3244            expression=instance,
3245            properties=properties_expression,
3246        )

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:
3248    def lock(self, update: bool = True, copy: bool = True) -> Select:
3249        """
3250        Set the locking read mode for this expression.
3251
3252        Examples:
3253            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3254            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3255
3256            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3257            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3258
3259        Args:
3260            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3261            copy: if `False`, modify this expression instance in-place.
3262
3263        Returns:
3264            The modified expression.
3265        """
3266        inst = maybe_copy(self, copy)
3267        inst.set("locks", [Lock(update=update)])
3268
3269        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:
3271    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3272        """
3273        Set hints for this expression.
3274
3275        Examples:
3276            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3277            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3278
3279        Args:
3280            hints: The SQL code strings to parse as the hints.
3281                If an `Expression` instance is passed, it will be used as-is.
3282            dialect: The dialect used to parse the hints.
3283            copy: If `False`, modify this expression instance in-place.
3284
3285        Returns:
3286            The modified expression.
3287        """
3288        inst = maybe_copy(self, copy)
3289        inst.set(
3290            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3291        )
3292
3293        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):
3308class Subquery(DerivedTable, Unionable):
3309    arg_types = {
3310        "this": True,
3311        "alias": False,
3312        "with": False,
3313        **QUERY_MODIFIERS,
3314    }
3315
3316    def unnest(self):
3317        """
3318        Returns the first non subquery.
3319        """
3320        expression = self
3321        while isinstance(expression, Subquery):
3322            expression = expression.this
3323        return expression
3324
3325    def unwrap(self) -> Subquery:
3326        expression = self
3327        while expression.same_parent and expression.is_wrapper:
3328            expression = t.cast(Subquery, expression.parent)
3329        return expression
3330
3331    @property
3332    def is_wrapper(self) -> bool:
3333        """
3334        Whether this Subquery acts as a simple wrapper around another expression.
3335
3336        SELECT * FROM (((SELECT * FROM t)))
3337                      ^
3338                      This corresponds to a "wrapper" Subquery node
3339        """
3340        return all(v is None for k, v in self.args.items() if k != "this")
3341
3342    @property
3343    def is_star(self) -> bool:
3344        return self.this.is_star
3345
3346    @property
3347    def output_name(self) -> str:
3348        return self.alias
arg_types = {'this': True, 'alias': False, 'with': False, 'match': False, 'laterals': False, 'joins': False, 'connect': 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):
3316    def unnest(self):
3317        """
3318        Returns the first non subquery.
3319        """
3320        expression = self
3321        while isinstance(expression, Subquery):
3322            expression = expression.this
3323        return expression

Returns the first non subquery.

def unwrap(self) -> sqlglot.expressions.Subquery:
3325    def unwrap(self) -> Subquery:
3326        expression = self
3327        while expression.same_parent and expression.is_wrapper:
3328            expression = t.cast(Subquery, expression.parent)
3329        return expression
is_wrapper: bool

Whether this Subquery acts as a simple wrapper around another expression.

SELECT * FROM (((SELECT * FROM t))) ^ This corresponds to a "wrapper" Subquery node

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):
3351class TableSample(Expression):
3352    arg_types = {
3353        "this": False,
3354        "expressions": False,
3355        "method": False,
3356        "bucket_numerator": False,
3357        "bucket_denominator": False,
3358        "bucket_field": False,
3359        "percent": False,
3360        "rows": False,
3361        "size": False,
3362        "seed": False,
3363        "kind": False,
3364    }
arg_types = {'this': False, 'expressions': 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):
3367class Tag(Expression):
3368    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3369
3370    arg_types = {
3371        "this": False,
3372        "prefix": False,
3373        "postfix": False,
3374    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3379class Pivot(Expression):
3380    arg_types = {
3381        "this": False,
3382        "alias": False,
3383        "expressions": True,
3384        "field": False,
3385        "unpivot": False,
3386        "using": False,
3387        "group": False,
3388        "columns": False,
3389        "include_nulls": False,
3390    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False, 'include_nulls': False}
key = 'pivot'
class Window(Condition):
3393class Window(Condition):
3394    arg_types = {
3395        "this": True,
3396        "partition_by": False,
3397        "order": False,
3398        "spec": False,
3399        "alias": False,
3400        "over": False,
3401        "first": False,
3402    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3405class WindowSpec(Expression):
3406    arg_types = {
3407        "kind": False,
3408        "start": False,
3409        "start_side": False,
3410        "end": False,
3411        "end_side": False,
3412    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3415class Where(Expression):
3416    pass
key = 'where'
class Star(Expression):
3419class Star(Expression):
3420    arg_types = {"except": False, "replace": False}
3421
3422    @property
3423    def name(self) -> str:
3424        return "*"
3425
3426    @property
3427    def output_name(self) -> str:
3428        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):
3431class Parameter(Condition):
3432    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3435class SessionParameter(Condition):
3436    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3439class Placeholder(Condition):
3440    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3443class Null(Condition):
3444    arg_types: t.Dict[str, t.Any] = {}
3445
3446    @property
3447    def name(self) -> str:
3448        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3451class Boolean(Condition):
3452    pass
key = 'boolean'
class DataTypeParam(Expression):
3455class DataTypeParam(Expression):
3456    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypeparam'
class DataType(Expression):
3459class DataType(Expression):
3460    arg_types = {
3461        "this": True,
3462        "expressions": False,
3463        "nested": False,
3464        "values": False,
3465        "prefix": False,
3466        "kind": False,
3467    }
3468
3469    class Type(AutoName):
3470        ARRAY = auto()
3471        BIGDECIMAL = auto()
3472        BIGINT = auto()
3473        BIGSERIAL = auto()
3474        BINARY = auto()
3475        BIT = auto()
3476        BOOLEAN = auto()
3477        CHAR = auto()
3478        DATE = auto()
3479        DATEMULTIRANGE = auto()
3480        DATERANGE = auto()
3481        DATETIME = auto()
3482        DATETIME64 = auto()
3483        DECIMAL = auto()
3484        DOUBLE = auto()
3485        ENUM = auto()
3486        ENUM8 = auto()
3487        ENUM16 = auto()
3488        FIXEDSTRING = auto()
3489        FLOAT = auto()
3490        GEOGRAPHY = auto()
3491        GEOMETRY = auto()
3492        HLLSKETCH = auto()
3493        HSTORE = auto()
3494        IMAGE = auto()
3495        INET = auto()
3496        INT = auto()
3497        INT128 = auto()
3498        INT256 = auto()
3499        INT4MULTIRANGE = auto()
3500        INT4RANGE = auto()
3501        INT8MULTIRANGE = auto()
3502        INT8RANGE = auto()
3503        INTERVAL = auto()
3504        IPADDRESS = auto()
3505        IPPREFIX = auto()
3506        JSON = auto()
3507        JSONB = auto()
3508        LONGBLOB = auto()
3509        LONGTEXT = auto()
3510        LOWCARDINALITY = auto()
3511        MAP = auto()
3512        MEDIUMBLOB = auto()
3513        MEDIUMINT = auto()
3514        MEDIUMTEXT = auto()
3515        MONEY = auto()
3516        NCHAR = auto()
3517        NESTED = auto()
3518        NULL = auto()
3519        NULLABLE = auto()
3520        NUMMULTIRANGE = auto()
3521        NUMRANGE = auto()
3522        NVARCHAR = auto()
3523        OBJECT = auto()
3524        ROWVERSION = auto()
3525        SERIAL = auto()
3526        SET = auto()
3527        SMALLINT = auto()
3528        SMALLMONEY = auto()
3529        SMALLSERIAL = auto()
3530        STRUCT = auto()
3531        SUPER = auto()
3532        TEXT = auto()
3533        TIME = auto()
3534        TIMETZ = auto()
3535        TIMESTAMP = auto()
3536        TIMESTAMPLTZ = auto()
3537        TIMESTAMPTZ = auto()
3538        TINYINT = auto()
3539        TSMULTIRANGE = auto()
3540        TSRANGE = auto()
3541        TSTZMULTIRANGE = auto()
3542        TSTZRANGE = auto()
3543        UBIGINT = auto()
3544        UINT = auto()
3545        UINT128 = auto()
3546        UINT256 = auto()
3547        UMEDIUMINT = auto()
3548        UNIQUEIDENTIFIER = auto()
3549        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3550        USERDEFINED = "USER-DEFINED"
3551        USMALLINT = auto()
3552        UTINYINT = auto()
3553        UUID = auto()
3554        VARBINARY = auto()
3555        VARCHAR = auto()
3556        VARIANT = auto()
3557        XML = auto()
3558        YEAR = auto()
3559
3560    TEXT_TYPES = {
3561        Type.CHAR,
3562        Type.NCHAR,
3563        Type.VARCHAR,
3564        Type.NVARCHAR,
3565        Type.TEXT,
3566    }
3567
3568    INTEGER_TYPES = {
3569        Type.INT,
3570        Type.TINYINT,
3571        Type.SMALLINT,
3572        Type.BIGINT,
3573        Type.INT128,
3574        Type.INT256,
3575    }
3576
3577    FLOAT_TYPES = {
3578        Type.FLOAT,
3579        Type.DOUBLE,
3580    }
3581
3582    NUMERIC_TYPES = {
3583        *INTEGER_TYPES,
3584        *FLOAT_TYPES,
3585    }
3586
3587    TEMPORAL_TYPES = {
3588        Type.TIME,
3589        Type.TIMETZ,
3590        Type.TIMESTAMP,
3591        Type.TIMESTAMPTZ,
3592        Type.TIMESTAMPLTZ,
3593        Type.DATE,
3594        Type.DATETIME,
3595        Type.DATETIME64,
3596    }
3597
3598    @classmethod
3599    def build(
3600        cls,
3601        dtype: str | DataType | DataType.Type,
3602        dialect: DialectType = None,
3603        udt: bool = False,
3604        **kwargs,
3605    ) -> DataType:
3606        """
3607        Constructs a DataType object.
3608
3609        Args:
3610            dtype: the data type of interest.
3611            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3612            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3613                DataType, thus creating a user-defined type.
3614            kawrgs: additional arguments to pass in the constructor of DataType.
3615
3616        Returns:
3617            The constructed DataType object.
3618        """
3619        from sqlglot import parse_one
3620
3621        if isinstance(dtype, str):
3622            if dtype.upper() == "UNKNOWN":
3623                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3624
3625            try:
3626                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3627            except ParseError:
3628                if udt:
3629                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3630                raise
3631        elif isinstance(dtype, DataType.Type):
3632            data_type_exp = DataType(this=dtype)
3633        elif isinstance(dtype, DataType):
3634            return dtype
3635        else:
3636            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3637
3638        return DataType(**{**data_type_exp.args, **kwargs})
3639
3640    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3641        """
3642        Checks whether this DataType matches one of the provided data types. Nested types or precision
3643        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3644
3645        Args:
3646            dtypes: the data types to compare this DataType to.
3647
3648        Returns:
3649            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3650        """
3651        for dtype in dtypes:
3652            other = DataType.build(dtype, udt=True)
3653
3654            if (
3655                other.expressions
3656                or self.this == DataType.Type.USERDEFINED
3657                or other.this == DataType.Type.USERDEFINED
3658            ):
3659                matches = self == other
3660            else:
3661                matches = self.this == other.this
3662
3663            if matches:
3664                return True
3665        return False
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False, 'kind': False}
TEXT_TYPES = {<Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.TEXT: 'TEXT'>, <Type.VARCHAR: 'VARCHAR'>, <Type.CHAR: 'CHAR'>}
INTEGER_TYPES = {<Type.BIGINT: 'BIGINT'>, <Type.INT256: 'INT256'>, <Type.SMALLINT: 'SMALLINT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT128: 'INT128'>, <Type.INT: 'INT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.BIGINT: 'BIGINT'>, <Type.TINYINT: 'TINYINT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>, <Type.INT128: 'INT128'>, <Type.INT256: 'INT256'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT: 'INT'>}
TEMPORAL_TYPES = {<Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.DATE: 'DATE'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIME: 'TIME'>, <Type.DATETIME: 'DATETIME'>, <Type.TIMETZ: 'TIMETZ'>, <Type.DATETIME64: 'DATETIME64'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>}
@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, udt: bool = False, **kwargs) -> sqlglot.expressions.DataType:
3598    @classmethod
3599    def build(
3600        cls,
3601        dtype: str | DataType | DataType.Type,
3602        dialect: DialectType = None,
3603        udt: bool = False,
3604        **kwargs,
3605    ) -> DataType:
3606        """
3607        Constructs a DataType object.
3608
3609        Args:
3610            dtype: the data type of interest.
3611            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3612            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3613                DataType, thus creating a user-defined type.
3614            kawrgs: additional arguments to pass in the constructor of DataType.
3615
3616        Returns:
3617            The constructed DataType object.
3618        """
3619        from sqlglot import parse_one
3620
3621        if isinstance(dtype, str):
3622            if dtype.upper() == "UNKNOWN":
3623                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3624
3625            try:
3626                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3627            except ParseError:
3628                if udt:
3629                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3630                raise
3631        elif isinstance(dtype, DataType.Type):
3632            data_type_exp = DataType(this=dtype)
3633        elif isinstance(dtype, DataType):
3634            return dtype
3635        else:
3636            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3637
3638        return DataType(**{**data_type_exp.args, **kwargs})

Constructs a DataType object.

Arguments:
  • dtype: the data type of interest.
  • dialect: the dialect to use for parsing dtype, in case it's a string.
  • udt: when set to True, dtype will be used as-is if it can't be parsed into a DataType, thus creating a user-defined type.
  • kawrgs: additional arguments to pass in the constructor of DataType.
Returns:

The constructed DataType object.

def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3640    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3641        """
3642        Checks whether this DataType matches one of the provided data types. Nested types or precision
3643        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3644
3645        Args:
3646            dtypes: the data types to compare this DataType to.
3647
3648        Returns:
3649            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3650        """
3651        for dtype in dtypes:
3652            other = DataType.build(dtype, udt=True)
3653
3654            if (
3655                other.expressions
3656                or self.this == DataType.Type.USERDEFINED
3657                or other.this == DataType.Type.USERDEFINED
3658            ):
3659                matches = self == other
3660            else:
3661                matches = self.this == other.this
3662
3663            if matches:
3664                return True
3665        return False

Checks whether this DataType matches one of the provided data types. Nested types or precision will be compared using "structural equivalence" semantics, so e.g. array != array.

Arguments:
  • dtypes: the data types to compare this DataType to.
Returns:

True, if and only if there is a type in dtypes which is equal to this DataType.

key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3469    class Type(AutoName):
3470        ARRAY = auto()
3471        BIGDECIMAL = auto()
3472        BIGINT = auto()
3473        BIGSERIAL = auto()
3474        BINARY = auto()
3475        BIT = auto()
3476        BOOLEAN = auto()
3477        CHAR = auto()
3478        DATE = auto()
3479        DATEMULTIRANGE = auto()
3480        DATERANGE = auto()
3481        DATETIME = auto()
3482        DATETIME64 = auto()
3483        DECIMAL = auto()
3484        DOUBLE = auto()
3485        ENUM = auto()
3486        ENUM8 = auto()
3487        ENUM16 = auto()
3488        FIXEDSTRING = auto()
3489        FLOAT = auto()
3490        GEOGRAPHY = auto()
3491        GEOMETRY = auto()
3492        HLLSKETCH = auto()
3493        HSTORE = auto()
3494        IMAGE = auto()
3495        INET = auto()
3496        INT = auto()
3497        INT128 = auto()
3498        INT256 = auto()
3499        INT4MULTIRANGE = auto()
3500        INT4RANGE = auto()
3501        INT8MULTIRANGE = auto()
3502        INT8RANGE = auto()
3503        INTERVAL = auto()
3504        IPADDRESS = auto()
3505        IPPREFIX = auto()
3506        JSON = auto()
3507        JSONB = auto()
3508        LONGBLOB = auto()
3509        LONGTEXT = auto()
3510        LOWCARDINALITY = auto()
3511        MAP = auto()
3512        MEDIUMBLOB = auto()
3513        MEDIUMINT = auto()
3514        MEDIUMTEXT = auto()
3515        MONEY = auto()
3516        NCHAR = auto()
3517        NESTED = auto()
3518        NULL = auto()
3519        NULLABLE = auto()
3520        NUMMULTIRANGE = auto()
3521        NUMRANGE = auto()
3522        NVARCHAR = auto()
3523        OBJECT = auto()
3524        ROWVERSION = auto()
3525        SERIAL = auto()
3526        SET = auto()
3527        SMALLINT = auto()
3528        SMALLMONEY = auto()
3529        SMALLSERIAL = auto()
3530        STRUCT = auto()
3531        SUPER = auto()
3532        TEXT = auto()
3533        TIME = auto()
3534        TIMETZ = auto()
3535        TIMESTAMP = auto()
3536        TIMESTAMPLTZ = auto()
3537        TIMESTAMPTZ = auto()
3538        TINYINT = auto()
3539        TSMULTIRANGE = auto()
3540        TSRANGE = auto()
3541        TSTZMULTIRANGE = auto()
3542        TSTZRANGE = auto()
3543        UBIGINT = auto()
3544        UINT = auto()
3545        UINT128 = auto()
3546        UINT256 = auto()
3547        UMEDIUMINT = auto()
3548        UNIQUEIDENTIFIER = auto()
3549        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3550        USERDEFINED = "USER-DEFINED"
3551        USMALLINT = auto()
3552        UTINYINT = auto()
3553        UUID = auto()
3554        VARBINARY = auto()
3555        VARCHAR = auto()
3556        VARIANT = auto()
3557        XML = auto()
3558        YEAR = 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'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
ENUM = <Type.ENUM: 'ENUM'>
ENUM8 = <Type.ENUM8: 'ENUM8'>
ENUM16 = <Type.ENUM16: 'ENUM16'>
FIXEDSTRING = <Type.FIXEDSTRING: 'FIXEDSTRING'>
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'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
IPADDRESS = <Type.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <Type.IPPREFIX: 'IPPREFIX'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
LOWCARDINALITY = <Type.LOWCARDINALITY: 'LOWCARDINALITY'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMINT = <Type.MEDIUMINT: 'MEDIUMINT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NESTED = <Type.NESTED: 'NESTED'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
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'>
TIMETZ = <Type.TIMETZ: 'TIMETZ'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UMEDIUMINT = <Type.UMEDIUMINT: 'UMEDIUMINT'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
YEAR = <Type.YEAR: 'YEAR'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3669class PseudoType(Expression):
3670    pass
key = 'pseudotype'
class ObjectIdentifier(Expression):
3674class ObjectIdentifier(Expression):
3675    pass
key = 'objectidentifier'
class SubqueryPredicate(Predicate):
3679class SubqueryPredicate(Predicate):
3680    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3683class All(SubqueryPredicate):
3684    pass
key = 'all'
class Any(SubqueryPredicate):
3687class Any(SubqueryPredicate):
3688    pass
key = 'any'
class Exists(SubqueryPredicate):
3691class Exists(SubqueryPredicate):
3692    pass
key = 'exists'
class Command(Expression):
3697class Command(Expression):
3698    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3701class Transaction(Expression):
3702    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3705class Commit(Expression):
3706    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3709class Rollback(Expression):
3710    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3713class AlterTable(Expression):
3714    arg_types = {"this": True, "actions": True, "exists": False, "only": False}
arg_types = {'this': True, 'actions': True, 'exists': False, 'only': False}
key = 'altertable'
class AddConstraint(Expression):
3717class AddConstraint(Expression):
3718    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3721class DropPartition(Expression):
3722    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3726class Binary(Condition):
3727    arg_types = {"this": True, "expression": True}
3728
3729    @property
3730    def left(self):
3731        return self.this
3732
3733    @property
3734    def right(self):
3735        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3738class Add(Binary):
3739    pass
key = 'add'
class Connector(Binary):
3742class Connector(Binary):
3743    pass
key = 'connector'
class And(Connector):
3746class And(Connector):
3747    pass
key = 'and'
class Or(Connector):
3750class Or(Connector):
3751    pass
key = 'or'
class BitwiseAnd(Binary):
3754class BitwiseAnd(Binary):
3755    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3758class BitwiseLeftShift(Binary):
3759    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3762class BitwiseOr(Binary):
3763    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3766class BitwiseRightShift(Binary):
3767    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3770class BitwiseXor(Binary):
3771    pass
key = 'bitwisexor'
class Div(Binary):
3774class Div(Binary):
3775    pass
key = 'div'
class Overlaps(Binary):
3778class Overlaps(Binary):
3779    pass
key = 'overlaps'
class Dot(Binary):
3782class Dot(Binary):
3783    @property
3784    def name(self) -> str:
3785        return self.expression.name
3786
3787    @property
3788    def output_name(self) -> str:
3789        return self.name
3790
3791    @classmethod
3792    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3793        """Build a Dot object with a sequence of expressions."""
3794        if len(expressions) < 2:
3795            raise ValueError(f"Dot requires >= 2 expressions.")
3796
3797        a, b, *expressions = expressions
3798        dot = Dot(this=a, expression=b)
3799
3800        for expression in expressions:
3801            dot = Dot(this=dot, expression=expression)
3802
3803        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:
3791    @classmethod
3792    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3793        """Build a Dot object with a sequence of expressions."""
3794        if len(expressions) < 2:
3795            raise ValueError(f"Dot requires >= 2 expressions.")
3796
3797        a, b, *expressions = expressions
3798        dot = Dot(this=a, expression=b)
3799
3800        for expression in expressions:
3801            dot = Dot(this=dot, expression=expression)
3802
3803        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3806class DPipe(Binary):
3807    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3810class SafeDPipe(DPipe):
3811    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3814class EQ(Binary, Predicate):
3815    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3818class NullSafeEQ(Binary, Predicate):
3819    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3822class NullSafeNEQ(Binary, Predicate):
3823    pass
key = 'nullsafeneq'
class Distance(Binary):
3826class Distance(Binary):
3827    pass
key = 'distance'
class Escape(Binary):
3830class Escape(Binary):
3831    pass
key = 'escape'
class Glob(Binary, Predicate):
3834class Glob(Binary, Predicate):
3835    pass
key = 'glob'
class GT(Binary, Predicate):
3838class GT(Binary, Predicate):
3839    pass
key = 'gt'
class GTE(Binary, Predicate):
3842class GTE(Binary, Predicate):
3843    pass
key = 'gte'
class ILike(Binary, Predicate):
3846class ILike(Binary, Predicate):
3847    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3850class ILikeAny(Binary, Predicate):
3851    pass
key = 'ilikeany'
class IntDiv(Binary):
3854class IntDiv(Binary):
3855    pass
key = 'intdiv'
class Is(Binary, Predicate):
3858class Is(Binary, Predicate):
3859    pass
key = 'is'
class Kwarg(Binary):
3862class Kwarg(Binary):
3863    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3866class Like(Binary, Predicate):
3867    pass
key = 'like'
class LikeAny(Binary, Predicate):
3870class LikeAny(Binary, Predicate):
3871    pass
key = 'likeany'
class LT(Binary, Predicate):
3874class LT(Binary, Predicate):
3875    pass
key = 'lt'
class LTE(Binary, Predicate):
3878class LTE(Binary, Predicate):
3879    pass
key = 'lte'
class Mod(Binary):
3882class Mod(Binary):
3883    pass
key = 'mod'
class Mul(Binary):
3886class Mul(Binary):
3887    pass
key = 'mul'
class NEQ(Binary, Predicate):
3890class NEQ(Binary, Predicate):
3891    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3894class SimilarTo(Binary, Predicate):
3895    pass
key = 'similarto'
class Slice(Binary):
3898class Slice(Binary):
3899    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3902class Sub(Binary):
3903    pass
key = 'sub'
class ArrayOverlaps(Binary):
3906class ArrayOverlaps(Binary):
3907    pass
key = 'arrayoverlaps'
class Unary(Condition):
3912class Unary(Condition):
3913    pass
key = 'unary'
class BitwiseNot(Unary):
3916class BitwiseNot(Unary):
3917    pass
key = 'bitwisenot'
class Not(Unary):
3920class Not(Unary):
3921    pass
key = 'not'
class Paren(Unary):
3924class Paren(Unary):
3925    arg_types = {"this": True, "with": False}
3926
3927    @property
3928    def output_name(self) -> str:
3929        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):
3932class Neg(Unary):
3933    pass
key = 'neg'
class Alias(Expression):
3936class Alias(Expression):
3937    arg_types = {"this": True, "alias": False}
3938
3939    @property
3940    def output_name(self) -> str:
3941        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):
3944class Aliases(Expression):
3945    arg_types = {"this": True, "expressions": True}
3946
3947    @property
3948    def aliases(self):
3949        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3952class AtTimeZone(Expression):
3953    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3956class Between(Predicate):
3957    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3960class Bracket(Condition):
3961    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3964class SafeBracket(Bracket):
3965    """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):
3968class Distinct(Expression):
3969    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3972class In(Predicate):
3973    arg_types = {
3974        "this": True,
3975        "expressions": False,
3976        "query": False,
3977        "unnest": False,
3978        "field": False,
3979        "is_global": False,
3980    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3983class TimeUnit(Expression):
3984    """Automatically converts unit arg into a var."""
3985
3986    arg_types = {"unit": False}
3987
3988    def __init__(self, **args):
3989        unit = args.get("unit")
3990        if isinstance(unit, (Column, Literal)):
3991            args["unit"] = Var(this=unit.name)
3992        elif isinstance(unit, Week):
3993            unit.set("this", Var(this=unit.this.name))
3994
3995        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3988    def __init__(self, **args):
3989        unit = args.get("unit")
3990        if isinstance(unit, (Column, Literal)):
3991            args["unit"] = Var(this=unit.name)
3992        elif isinstance(unit, Week):
3993            unit.set("this", Var(this=unit.this.name))
3994
3995        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class IntervalSpan(Expression):
4001class IntervalSpan(Expression):
4002    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'intervalspan'
class Interval(TimeUnit):
4005class Interval(TimeUnit):
4006    arg_types = {"this": False, "unit": False}
4007
4008    @property
4009    def unit(self) -> t.Optional[Var]:
4010        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
4013class IgnoreNulls(Expression):
4014    pass
key = 'ignorenulls'
class RespectNulls(Expression):
4017class RespectNulls(Expression):
4018    pass
key = 'respectnulls'
class Func(Condition):
4022class Func(Condition):
4023    """
4024    The base class for all function expressions.
4025
4026    Attributes:
4027        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
4028            treated as a variable length argument and the argument's value will be stored as a list.
4029        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
4030            for this function expression. These values are used to map this node to a name during parsing
4031            as well as to provide the function's name during SQL string generation. By default the SQL
4032            name is set to the expression's class name transformed to snake case.
4033    """
4034
4035    is_var_len_args = False
4036
4037    @classmethod
4038    def from_arg_list(cls, args):
4039        if cls.is_var_len_args:
4040            all_arg_keys = list(cls.arg_types)
4041            # If this function supports variable length argument treat the last argument as such.
4042            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4043            num_non_var = len(non_var_len_arg_keys)
4044
4045            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4046            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4047        else:
4048            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4049
4050        return cls(**args_dict)
4051
4052    @classmethod
4053    def sql_names(cls):
4054        if cls is Func:
4055            raise NotImplementedError(
4056                "SQL name is only supported by concrete function implementations"
4057            )
4058        if "_sql_names" not in cls.__dict__:
4059            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4060        return cls._sql_names
4061
4062    @classmethod
4063    def sql_name(cls):
4064        return cls.sql_names()[0]
4065
4066    @classmethod
4067    def default_parser_mappings(cls):
4068        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):
4037    @classmethod
4038    def from_arg_list(cls, args):
4039        if cls.is_var_len_args:
4040            all_arg_keys = list(cls.arg_types)
4041            # If this function supports variable length argument treat the last argument as such.
4042            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4043            num_non_var = len(non_var_len_arg_keys)
4044
4045            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4046            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4047        else:
4048            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4049
4050        return cls(**args_dict)
@classmethod
def sql_names(cls):
4052    @classmethod
4053    def sql_names(cls):
4054        if cls is Func:
4055            raise NotImplementedError(
4056                "SQL name is only supported by concrete function implementations"
4057            )
4058        if "_sql_names" not in cls.__dict__:
4059            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4060        return cls._sql_names
@classmethod
def sql_name(cls):
4062    @classmethod
4063    def sql_name(cls):
4064        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
4066    @classmethod
4067    def default_parser_mappings(cls):
4068        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
4071class AggFunc(Func):
4072    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
4075class ParameterizedAgg(AggFunc):
4076    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
4079class Abs(Func):
4080    pass
key = 'abs'
class Transform(Func):
4084class Transform(Func):
4085    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
4088class Anonymous(Func):
4089    arg_types = {"this": True, "expressions": False}
4090    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
4095class Hll(AggFunc):
4096    arg_types = {"this": True, "expressions": False}
4097    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
4100class ApproxDistinct(AggFunc):
4101    arg_types = {"this": True, "accuracy": False}
4102    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
4105class Array(Func):
4106    arg_types = {"expressions": False}
4107    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
4111class ToChar(Func):
4112    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
4115class GenerateSeries(Func):
4116    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
4119class ArrayAgg(AggFunc):
4120    pass
key = 'arrayagg'
class ArrayAll(Func):
4123class ArrayAll(Func):
4124    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4127class ArrayAny(Func):
4128    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4131class ArrayConcat(Func):
4132    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4133    arg_types = {"this": True, "expressions": False}
4134    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4137class ArrayContains(Binary, Func):
4138    pass
key = 'arraycontains'
class ArrayContained(Binary):
4141class ArrayContained(Binary):
4142    pass
key = 'arraycontained'
class ArrayFilter(Func):
4145class ArrayFilter(Func):
4146    arg_types = {"this": True, "expression": True}
4147    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4150class ArrayJoin(Func):
4151    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4154class ArraySize(Func):
4155    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4158class ArraySort(Func):
4159    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4162class ArraySum(Func):
4163    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4166class ArrayUnionAgg(AggFunc):
4167    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4170class Avg(AggFunc):
4171    pass
key = 'avg'
class AnyValue(AggFunc):
4174class AnyValue(AggFunc):
4175    arg_types = {"this": True, "having": False, "max": False, "ignore_nulls": False}
arg_types = {'this': True, 'having': False, 'max': False, 'ignore_nulls': False}
key = 'anyvalue'
class First(Func):
4178class First(Func):
4179    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4182class Last(Func):
4183    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4186class Case(Func):
4187    arg_types = {"this": False, "ifs": True, "default": False}
4188
4189    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4190        instance = maybe_copy(self, copy)
4191        instance.append(
4192            "ifs",
4193            If(
4194                this=maybe_parse(condition, copy=copy, **opts),
4195                true=maybe_parse(then, copy=copy, **opts),
4196            ),
4197        )
4198        return instance
4199
4200    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4201        instance = maybe_copy(self, copy)
4202        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4203        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:
4189    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4190        instance = maybe_copy(self, copy)
4191        instance.append(
4192            "ifs",
4193            If(
4194                this=maybe_parse(condition, copy=copy, **opts),
4195                true=maybe_parse(then, copy=copy, **opts),
4196            ),
4197        )
4198        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4200    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4201        instance = maybe_copy(self, copy)
4202        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4203        return instance
key = 'case'
class Cast(Func):
4206class Cast(Func):
4207    arg_types = {"this": True, "to": True, "format": False}
4208
4209    @property
4210    def name(self) -> str:
4211        return self.this.name
4212
4213    @property
4214    def to(self) -> DataType:
4215        return self.args["to"]
4216
4217    @property
4218    def output_name(self) -> str:
4219        return self.name
4220
4221    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4222        """
4223        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4224        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4225        array<int> != array<float>.
4226
4227        Args:
4228            dtypes: the data types to compare this Cast's DataType to.
4229
4230        Returns:
4231            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4232        """
4233        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:
4221    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4222        """
4223        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4224        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4225        array<int> != array<float>.
4226
4227        Args:
4228            dtypes: the data types to compare this Cast's DataType to.
4229
4230        Returns:
4231            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4232        """
4233        return self.to.is_type(*dtypes)

Checks whether this Cast's DataType matches one of the provided data types. Nested types like arrays or structs will be compared using "structural equivalence" semantics, so e.g. array != array.

Arguments:
  • dtypes: the data types to compare this Cast's DataType to.
Returns:

True, if and only if there is a type in dtypes which is equal to this Cast's DataType.

key = 'cast'
class TryCast(Cast):
4236class TryCast(Cast):
4237    pass
key = 'trycast'
class CastToStrType(Func):
4240class CastToStrType(Func):
4241    arg_types = {"this": True, "to": True}
arg_types = {'this': True, 'to': True}
key = 'casttostrtype'
class Collate(Binary):
4244class Collate(Binary):
4245    pass
key = 'collate'
class Ceil(Func):
4248class Ceil(Func):
4249    arg_types = {"this": True, "decimals": False}
4250    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4253class Coalesce(Func):
4254    arg_types = {"this": True, "expressions": False}
4255    is_var_len_args = True
4256    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4259class Concat(Func):
4260    arg_types = {"expressions": True}
4261    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4264class SafeConcat(Concat):
4265    pass
key = 'safeconcat'
class ConcatWs(Concat):
4268class ConcatWs(Concat):
4269    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4272class Count(AggFunc):
4273    arg_types = {"this": False, "expressions": False}
4274    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4277class CountIf(AggFunc):
4278    pass
key = 'countif'
class CurrentDate(Func):
4281class CurrentDate(Func):
4282    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4285class CurrentDatetime(Func):
4286    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4289class CurrentTime(Func):
4290    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4293class CurrentTimestamp(Func):
4294    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4297class CurrentUser(Func):
4298    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4301class DateAdd(Func, TimeUnit):
4302    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4305class DateSub(Func, TimeUnit):
4306    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4309class DateDiff(Func, TimeUnit):
4310    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4311    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4314class DateTrunc(Func):
4315    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4318class DatetimeAdd(Func, TimeUnit):
4319    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4322class DatetimeSub(Func, TimeUnit):
4323    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4326class DatetimeDiff(Func, TimeUnit):
4327    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4330class DatetimeTrunc(Func, TimeUnit):
4331    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4334class DayOfWeek(Func):
4335    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4338class DayOfMonth(Func):
4339    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4342class DayOfYear(Func):
4343    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4346class WeekOfYear(Func):
4347    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4350class MonthsBetween(Func):
4351    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4354class LastDateOfMonth(Func):
4355    pass
key = 'lastdateofmonth'
class Extract(Func):
4358class Extract(Func):
4359    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4362class TimestampAdd(Func, TimeUnit):
4363    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4366class TimestampSub(Func, TimeUnit):
4367    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4370class TimestampDiff(Func, TimeUnit):
4371    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4374class TimestampTrunc(Func, TimeUnit):
4375    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4378class TimeAdd(Func, TimeUnit):
4379    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4382class TimeSub(Func, TimeUnit):
4383    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4386class TimeDiff(Func, TimeUnit):
4387    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4390class TimeTrunc(Func, TimeUnit):
4391    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4394class DateFromParts(Func):
4395    _sql_names = ["DATEFROMPARTS"]
4396    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4399class DateStrToDate(Func):
4400    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4403class DateToDateStr(Func):
4404    pass
key = 'datetodatestr'
class DateToDi(Func):
4407class DateToDi(Func):
4408    pass
key = 'datetodi'
class Date(Func):
4412class Date(Func):
4413    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4416class Day(Func):
4417    pass
key = 'day'
class Decode(Func):
4420class Decode(Func):
4421    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4424class DiToDate(Func):
4425    pass
key = 'ditodate'
class Encode(Func):
4428class Encode(Func):
4429    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4432class Exp(Func):
4433    pass
key = 'exp'
class Explode(Func):
4436class Explode(Func):
4437    pass
key = 'explode'
class Floor(Func):
4440class Floor(Func):
4441    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4444class FromBase64(Func):
4445    pass
key = 'frombase64'
class ToBase64(Func):
4448class ToBase64(Func):
4449    pass
key = 'tobase64'
class Greatest(Func):
4452class Greatest(Func):
4453    arg_types = {"this": True, "expressions": False}
4454    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(AggFunc):
4457class GroupConcat(AggFunc):
4458    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4461class Hex(Func):
4462    pass
key = 'hex'
class Xor(Connector, Func):
4465class Xor(Connector, Func):
4466    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4469class If(Func):
4470    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4473class Initcap(Func):
4474    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4477class IsNan(Func):
4478    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class JSONKeyValue(Expression):
4481class JSONKeyValue(Expression):
4482    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4485class JSONObject(Func):
4486    arg_types = {
4487        "expressions": False,
4488        "null_handling": False,
4489        "unique_keys": False,
4490        "return_type": False,
4491        "format_json": False,
4492        "encoding": False,
4493    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4496class OpenJSONColumnDef(Expression):
4497    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):
4500class OpenJSON(Func):
4501    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4504class JSONBContains(Binary):
4505    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4508class JSONExtract(Binary, Func):
4509    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4512class JSONExtractScalar(JSONExtract):
4513    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4516class JSONBExtract(JSONExtract):
4517    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4520class JSONBExtractScalar(JSONExtract):
4521    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4524class JSONFormat(Func):
4525    arg_types = {"this": False, "options": False}
4526    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4530class JSONArrayContains(Binary, Predicate, Func):
4531    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4534class Least(Func):
4535    arg_types = {"this": True, "expressions": False}
4536    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4539class Left(Func):
4540    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4547class Length(Func):
4548    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4551class Levenshtein(Func):
4552    arg_types = {
4553        "this": True,
4554        "expression": False,
4555        "ins_cost": False,
4556        "del_cost": False,
4557        "sub_cost": False,
4558    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4561class Ln(Func):
4562    pass
key = 'ln'
class Log(Func):
4565class Log(Func):
4566    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4569class Log2(Func):
4570    pass
key = 'log2'
class Log10(Func):
4573class Log10(Func):
4574    pass
key = 'log10'
class LogicalOr(AggFunc):
4577class LogicalOr(AggFunc):
4578    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4581class LogicalAnd(AggFunc):
4582    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4585class Lower(Func):
4586    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4589class Map(Func):
4590    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4593class MapFromEntries(Func):
4594    pass
key = 'mapfromentries'
class StarMap(Func):
4597class StarMap(Func):
4598    pass
key = 'starmap'
class VarMap(Func):
4601class VarMap(Func):
4602    arg_types = {"keys": True, "values": True}
4603    is_var_len_args = True
4604
4605    @property
4606    def keys(self) -> t.List[Expression]:
4607        return self.args["keys"].expressions
4608
4609    @property
4610    def values(self) -> t.List[Expression]:
4611        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4615class MatchAgainst(Func):
4616    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4619class Max(AggFunc):
4620    arg_types = {"this": True, "expressions": False}
4621    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4624class MD5(Func):
4625    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4629class MD5Digest(Func):
4630    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4633class Min(AggFunc):
4634    arg_types = {"this": True, "expressions": False}
4635    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4638class Month(Func):
4639    pass
key = 'month'
class Nvl2(Func):
4642class Nvl2(Func):
4643    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4646class Posexplode(Func):
4647    pass
key = 'posexplode'
class Pow(Binary, Func):
4650class Pow(Binary, Func):
4651    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4654class PercentileCont(AggFunc):
4655    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4658class PercentileDisc(AggFunc):
4659    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4662class Quantile(AggFunc):
4663    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4666class ApproxQuantile(Quantile):
4667    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):
4670class RangeN(Func):
4671    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4674class ReadCSV(Func):
4675    _sql_names = ["READ_CSV"]
4676    is_var_len_args = True
4677    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4680class Reduce(Func):
4681    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):
4684class RegexpExtract(Func):
4685    arg_types = {
4686        "this": True,
4687        "expression": True,
4688        "position": False,
4689        "occurrence": False,
4690        "parameters": False,
4691        "group": False,
4692    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4695class RegexpReplace(Func):
4696    arg_types = {
4697        "this": True,
4698        "expression": True,
4699        "replacement": True,
4700        "position": False,
4701        "occurrence": False,
4702        "parameters": False,
4703    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4706class RegexpLike(Binary, Func):
4707    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4710class RegexpILike(Func):
4711    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4716class RegexpSplit(Func):
4717    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4720class Repeat(Func):
4721    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4724class Round(Func):
4725    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4728class RowNumber(Func):
4729    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4732class SafeDivide(Func):
4733    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4736class SetAgg(AggFunc):
4737    pass
key = 'setagg'
class SHA(Func):
4740class SHA(Func):
4741    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4744class SHA2(Func):
4745    _sql_names = ["SHA2"]
4746    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4749class SortArray(Func):
4750    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4753class Split(Func):
4754    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4759class Substring(Func):
4760    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4763class StandardHash(Func):
4764    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4767class StartsWith(Func):
4768    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4769    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4772class StrPosition(Func):
4773    arg_types = {
4774        "this": True,
4775        "substr": True,
4776        "position": False,
4777        "instance": False,
4778    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4781class StrToDate(Func):
4782    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4785class StrToTime(Func):
4786    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4791class StrToUnix(Func):
4792    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
4797class StrToMap(Func):
4798    arg_types = {
4799        "this": True,
4800        "pair_delim": False,
4801        "key_value_delim": False,
4802        "duplicate_resolution_callback": False,
4803    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
4806class NumberToStr(Func):
4807    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
4810class FromBase(Func):
4811    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4814class Struct(Func):
4815    arg_types = {"expressions": True}
4816    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4819class StructExtract(Func):
4820    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Stuff(Func):
4825class Stuff(Func):
4826    _sql_names = ["STUFF", "INSERT"]
4827    arg_types = {"this": True, "start": True, "length": True, "expression": True}
arg_types = {'this': True, 'start': True, 'length': True, 'expression': True}
key = 'stuff'
class Sum(AggFunc):
4830class Sum(AggFunc):
4831    pass
key = 'sum'
class Sqrt(Func):
4834class Sqrt(Func):
4835    pass
key = 'sqrt'
class Stddev(AggFunc):
4838class Stddev(AggFunc):
4839    pass
key = 'stddev'
class StddevPop(AggFunc):
4842class StddevPop(AggFunc):
4843    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4846class StddevSamp(AggFunc):
4847    pass
key = 'stddevsamp'
class TimeToStr(Func):
4850class TimeToStr(Func):
4851    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
4854class TimeToTimeStr(Func):
4855    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4858class TimeToUnix(Func):
4859    pass
key = 'timetounix'
class TimeStrToDate(Func):
4862class TimeStrToDate(Func):
4863    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4866class TimeStrToTime(Func):
4867    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4870class TimeStrToUnix(Func):
4871    pass
key = 'timestrtounix'
class Trim(Func):
4874class Trim(Func):
4875    arg_types = {
4876        "this": True,
4877        "expression": False,
4878        "position": False,
4879        "collation": False,
4880    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4883class TsOrDsAdd(Func, TimeUnit):
4884    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4887class TsOrDsToDateStr(Func):
4888    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4891class TsOrDsToDate(Func):
4892    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4895class TsOrDiToDi(Func):
4896    pass
key = 'tsorditodi'
class Unhex(Func):
4899class Unhex(Func):
4900    pass
key = 'unhex'
class UnixToStr(Func):
4903class UnixToStr(Func):
4904    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4909class UnixToTime(Func):
4910    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4911
4912    SECONDS = Literal.string("seconds")
4913    MILLIS = Literal.string("millis")
4914    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):
4917class UnixToTimeStr(Func):
4918    pass
key = 'unixtotimestr'
class Upper(Func):
4921class Upper(Func):
4922    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4925class Variance(AggFunc):
4926    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4929class VariancePop(AggFunc):
4930    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4933class Week(Func):
4934    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4937class XMLTable(Func):
4938    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):
4941class Year(Func):
4942    pass
key = 'year'
class Use(Expression):
4945class Use(Expression):
4946    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4949class Merge(Expression):
4950    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):
4953class When(Func):
4954    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):
4959class NextValueFor(Func):
4960    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.First'>, <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.IsNan'>, <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.Last'>, <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.StartsWith'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToMap'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Stuff'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.Transform'>, <class 'sqlglot.expressions.Trim'>, <class 'sqlglot.expressions.TryCast'>, <class 'sqlglot.expressions.TsOrDiToDi'>, <class 'sqlglot.expressions.TsOrDsAdd'>, <class 'sqlglot.expressions.TsOrDsToDate'>, <class 'sqlglot.expressions.TsOrDsToDateStr'>, <class 'sqlglot.expressions.Unhex'>, <class 'sqlglot.expressions.UnixToStr'>, <class 'sqlglot.expressions.UnixToTime'>, <class 'sqlglot.expressions.UnixToTimeStr'>, <class 'sqlglot.expressions.Upper'>, <class 'sqlglot.expressions.VarMap'>, <class 'sqlglot.expressions.Variance'>, <class 'sqlglot.expressions.VariancePop'>, <class 'sqlglot.expressions.Week'>, <class 'sqlglot.expressions.WeekOfYear'>, <class 'sqlglot.expressions.When'>, <class 'sqlglot.expressions.XMLTable'>, <class 'sqlglot.expressions.Xor'>, <class 'sqlglot.expressions.Year'>]
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4997def maybe_parse(
4998    sql_or_expression: ExpOrStr,
4999    *,
5000    into: t.Optional[IntoType] = None,
5001    dialect: DialectType = None,
5002    prefix: t.Optional[str] = None,
5003    copy: bool = False,
5004    **opts,
5005) -> Expression:
5006    """Gracefully handle a possible string or expression.
5007
5008    Example:
5009        >>> maybe_parse("1")
5010        (LITERAL this: 1, is_string: False)
5011        >>> maybe_parse(to_identifier("x"))
5012        (IDENTIFIER this: x, quoted: False)
5013
5014    Args:
5015        sql_or_expression: the SQL code string or an expression
5016        into: the SQLGlot Expression to parse into
5017        dialect: the dialect used to parse the input expressions (in the case that an
5018            input expression is a SQL string).
5019        prefix: a string to prefix the sql with before it gets parsed
5020            (automatically includes a space)
5021        copy: whether or not to copy the expression.
5022        **opts: other options to use to parse the input expressions (again, in the case
5023            that an input expression is a SQL string).
5024
5025    Returns:
5026        Expression: the parsed or given expression.
5027    """
5028    if isinstance(sql_or_expression, Expression):
5029        if copy:
5030            return sql_or_expression.copy()
5031        return sql_or_expression
5032
5033    if sql_or_expression is None:
5034        raise ParseError(f"SQL cannot be None")
5035
5036    import sqlglot
5037
5038    sql = str(sql_or_expression)
5039    if prefix:
5040        sql = f"{prefix} {sql}"
5041
5042    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 maybe_copy(instance, copy=True):
5055def maybe_copy(instance, copy=True):
5056    return instance.copy() if copy and instance else instance
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:
5236def union(
5237    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5238) -> Union:
5239    """
5240    Initializes a syntax tree from one UNION expression.
5241
5242    Example:
5243        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5244        'SELECT * FROM foo UNION SELECT * FROM bla'
5245
5246    Args:
5247        left: the SQL code string corresponding to the left-hand side.
5248            If an `Expression` instance is passed, it will be used as-is.
5249        right: the SQL code string corresponding to the right-hand side.
5250            If an `Expression` instance is passed, it will be used as-is.
5251        distinct: set the DISTINCT flag if and only if this is true.
5252        dialect: the dialect used to parse the input expression.
5253        opts: other options to use to parse the input expressions.
5254
5255    Returns:
5256        The new Union instance.
5257    """
5258    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5259    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5260
5261    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:
5264def intersect(
5265    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5266) -> Intersect:
5267    """
5268    Initializes a syntax tree from one INTERSECT expression.
5269
5270    Example:
5271        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5272        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5273
5274    Args:
5275        left: the SQL code string corresponding to the left-hand side.
5276            If an `Expression` instance is passed, it will be used as-is.
5277        right: the SQL code string corresponding to the right-hand side.
5278            If an `Expression` instance is passed, it will be used as-is.
5279        distinct: set the DISTINCT flag if and only if this is true.
5280        dialect: the dialect used to parse the input expression.
5281        opts: other options to use to parse the input expressions.
5282
5283    Returns:
5284        The new Intersect instance.
5285    """
5286    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5287    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5288
5289    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:
5292def except_(
5293    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5294) -> Except:
5295    """
5296    Initializes a syntax tree from one EXCEPT expression.
5297
5298    Example:
5299        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5300        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5301
5302    Args:
5303        left: the SQL code string corresponding to the left-hand side.
5304            If an `Expression` instance is passed, it will be used as-is.
5305        right: the SQL code string corresponding to the right-hand side.
5306            If an `Expression` instance is passed, it will be used as-is.
5307        distinct: set the DISTINCT flag if and only if this is true.
5308        dialect: the dialect used to parse the input expression.
5309        opts: other options to use to parse the input expressions.
5310
5311    Returns:
5312        The new Except instance.
5313    """
5314    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5315    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5316
5317    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:
5320def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5321    """
5322    Initializes a syntax tree from one or multiple SELECT expressions.
5323
5324    Example:
5325        >>> select("col1", "col2").from_("tbl").sql()
5326        'SELECT col1, col2 FROM tbl'
5327
5328    Args:
5329        *expressions: the SQL code string to parse as the expressions of a
5330            SELECT statement. If an Expression instance is passed, this is used as-is.
5331        dialect: the dialect used to parse the input expressions (in the case that an
5332            input expression is a SQL string).
5333        **opts: other options to use to parse the input expressions (again, in the case
5334            that an input expression is a SQL string).
5335
5336    Returns:
5337        Select: the syntax tree for the SELECT statement.
5338    """
5339    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:
5342def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5343    """
5344    Initializes a syntax tree from a FROM expression.
5345
5346    Example:
5347        >>> from_("tbl").select("col1", "col2").sql()
5348        'SELECT col1, col2 FROM tbl'
5349
5350    Args:
5351        *expression: the SQL code string to parse as the FROM expressions of a
5352            SELECT statement. If an Expression instance is passed, this is used as-is.
5353        dialect: the dialect used to parse the input expression (in the case that the
5354            input expression is a SQL string).
5355        **opts: other options to use to parse the input expressions (again, in the case
5356            that the input expression is a SQL string).
5357
5358    Returns:
5359        Select: the syntax tree for the SELECT statement.
5360    """
5361    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:
5364def update(
5365    table: str | Table,
5366    properties: dict,
5367    where: t.Optional[ExpOrStr] = None,
5368    from_: t.Optional[ExpOrStr] = None,
5369    dialect: DialectType = None,
5370    **opts,
5371) -> Update:
5372    """
5373    Creates an update statement.
5374
5375    Example:
5376        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5377        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5378
5379    Args:
5380        *properties: dictionary of properties to set which are
5381            auto converted to sql objects eg None -> NULL
5382        where: sql conditional parsed into a WHERE statement
5383        from_: sql statement parsed into a FROM statement
5384        dialect: the dialect used to parse the input expressions.
5385        **opts: other options to use to parse the input expressions.
5386
5387    Returns:
5388        Update: the syntax tree for the UPDATE statement.
5389    """
5390    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5391    update_expr.set(
5392        "expressions",
5393        [
5394            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5395            for k, v in properties.items()
5396        ],
5397    )
5398    if from_:
5399        update_expr.set(
5400            "from",
5401            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5402        )
5403    if isinstance(where, Condition):
5404        where = Where(this=where)
5405    if where:
5406        update_expr.set(
5407            "where",
5408            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5409        )
5410    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:
5413def delete(
5414    table: ExpOrStr,
5415    where: t.Optional[ExpOrStr] = None,
5416    returning: t.Optional[ExpOrStr] = None,
5417    dialect: DialectType = None,
5418    **opts,
5419) -> Delete:
5420    """
5421    Builds a delete statement.
5422
5423    Example:
5424        >>> delete("my_table", where="id > 1").sql()
5425        'DELETE FROM my_table WHERE id > 1'
5426
5427    Args:
5428        where: sql conditional parsed into a WHERE statement
5429        returning: sql conditional parsed into a RETURNING statement
5430        dialect: the dialect used to parse the input expressions.
5431        **opts: other options to use to parse the input expressions.
5432
5433    Returns:
5434        Delete: the syntax tree for the DELETE statement.
5435    """
5436    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5437    if where:
5438        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5439    if returning:
5440        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5441    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:
5444def insert(
5445    expression: ExpOrStr,
5446    into: ExpOrStr,
5447    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5448    overwrite: t.Optional[bool] = None,
5449    dialect: DialectType = None,
5450    copy: bool = True,
5451    **opts,
5452) -> Insert:
5453    """
5454    Builds an INSERT statement.
5455
5456    Example:
5457        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5458        'INSERT INTO tbl VALUES (1, 2, 3)'
5459
5460    Args:
5461        expression: the sql string or expression of the INSERT statement
5462        into: the tbl to insert data to.
5463        columns: optionally the table's column names.
5464        overwrite: whether to INSERT OVERWRITE or not.
5465        dialect: the dialect used to parse the input expressions.
5466        copy: whether or not to copy the expression.
5467        **opts: other options to use to parse the input expressions.
5468
5469    Returns:
5470        Insert: the syntax tree for the INSERT statement.
5471    """
5472    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5473    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5474
5475    if columns:
5476        this = _apply_list_builder(
5477            *columns,
5478            instance=Schema(this=this),
5479            arg="expressions",
5480            into=Identifier,
5481            copy=False,
5482            dialect=dialect,
5483            **opts,
5484        )
5485
5486    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:
5489def condition(
5490    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5491) -> Condition:
5492    """
5493    Initialize a logical condition expression.
5494
5495    Example:
5496        >>> condition("x=1").sql()
5497        'x = 1'
5498
5499        This is helpful for composing larger logical syntax trees:
5500        >>> where = condition("x=1")
5501        >>> where = where.and_("y=1")
5502        >>> Select().from_("tbl").select("*").where(where).sql()
5503        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5504
5505    Args:
5506        *expression: the SQL code string to parse.
5507            If an Expression instance is passed, this is used as-is.
5508        dialect: the dialect used to parse the input expression (in the case that the
5509            input expression is a SQL string).
5510        copy: Whether or not to copy `expression` (only applies to expressions).
5511        **opts: other options to use to parse the input expressions (again, in the case
5512            that the input expression is a SQL string).
5513
5514    Returns:
5515        The new Condition instance
5516    """
5517    return maybe_parse(
5518        expression,
5519        into=Condition,
5520        dialect=dialect,
5521        copy=copy,
5522        **opts,
5523    )

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:
5526def and_(
5527    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5528) -> Condition:
5529    """
5530    Combine multiple conditions with an AND logical operator.
5531
5532    Example:
5533        >>> and_("x=1", and_("y=1", "z=1")).sql()
5534        'x = 1 AND (y = 1 AND z = 1)'
5535
5536    Args:
5537        *expressions: the SQL code strings to parse.
5538            If an Expression instance is passed, this is used as-is.
5539        dialect: the dialect used to parse the input expression.
5540        copy: whether or not to copy `expressions` (only applies to Expressions).
5541        **opts: other options to use to parse the input expressions.
5542
5543    Returns:
5544        And: the new condition
5545    """
5546    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:
5549def or_(
5550    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5551) -> Condition:
5552    """
5553    Combine multiple conditions with an OR logical operator.
5554
5555    Example:
5556        >>> or_("x=1", or_("y=1", "z=1")).sql()
5557        'x = 1 OR (y = 1 OR z = 1)'
5558
5559    Args:
5560        *expressions: the SQL code strings to parse.
5561            If an Expression instance is passed, this is used as-is.
5562        dialect: the dialect used to parse the input expression.
5563        copy: whether or not to copy `expressions` (only applies to Expressions).
5564        **opts: other options to use to parse the input expressions.
5565
5566    Returns:
5567        Or: the new condition
5568    """
5569    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:
5572def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5573    """
5574    Wrap a condition with a NOT operator.
5575
5576    Example:
5577        >>> not_("this_suit='black'").sql()
5578        "NOT this_suit = 'black'"
5579
5580    Args:
5581        expression: the SQL code string to parse.
5582            If an Expression instance is passed, this is used as-is.
5583        dialect: the dialect used to parse the input expression.
5584        copy: whether to copy the expression or not.
5585        **opts: other options to use to parse the input expressions.
5586
5587    Returns:
5588        The new condition.
5589    """
5590    this = condition(
5591        expression,
5592        dialect=dialect,
5593        copy=copy,
5594        **opts,
5595    )
5596    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:
5599def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5600    """
5601    Wrap an expression in parentheses.
5602
5603    Example:
5604        >>> paren("5 + 3").sql()
5605        '(5 + 3)'
5606
5607    Args:
5608        expression: the SQL code string to parse.
5609            If an Expression instance is passed, this is used as-is.
5610        copy: whether to copy the expression or not.
5611
5612    Returns:
5613        The wrapped expression.
5614    """
5615    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):
5633def to_identifier(name, quoted=None, copy=True):
5634    """Builds an identifier.
5635
5636    Args:
5637        name: The name to turn into an identifier.
5638        quoted: Whether or not force quote the identifier.
5639        copy: Whether or not to copy a passed in Identefier node.
5640
5641    Returns:
5642        The identifier ast node.
5643    """
5644
5645    if name is None:
5646        return None
5647
5648    if isinstance(name, Identifier):
5649        identifier = maybe_copy(name, copy)
5650    elif isinstance(name, str):
5651        identifier = Identifier(
5652            this=name,
5653            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5654        )
5655    else:
5656        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5657    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:
5663def to_interval(interval: str | Literal) -> Interval:
5664    """Builds an interval expression from a string like '1 day' or '5 months'."""
5665    if isinstance(interval, Literal):
5666        if not interval.is_string:
5667            raise ValueError("Invalid interval string.")
5668
5669        interval = interval.this
5670
5671    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5672
5673    if not interval_parts:
5674        raise ValueError("Invalid interval string.")
5675
5676    return Interval(
5677        this=Literal.string(interval_parts.group(1)),
5678        unit=Var(this=interval_parts.group(2)),
5679    )

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]:
5692def to_table(
5693    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5694) -> t.Optional[Table]:
5695    """
5696    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5697    If a table is passed in then that table is returned.
5698
5699    Args:
5700        sql_path: a `[catalog].[schema].[table]` string.
5701        dialect: the source dialect according to which the table name will be parsed.
5702        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5703
5704    Returns:
5705        A table expression.
5706    """
5707    if sql_path is None or isinstance(sql_path, Table):
5708        return sql_path
5709    if not isinstance(sql_path, str):
5710        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5711
5712    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5713    if table:
5714        for k, v in kwargs.items():
5715            table.set(k, v)
5716
5717    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:
5720def to_column(sql_path: str | Column, **kwargs) -> Column:
5721    """
5722    Create a column from a `[table].[column]` sql path. Schema is optional.
5723
5724    If a column is passed in then that column is returned.
5725
5726    Args:
5727        sql_path: `[table].[column]` string
5728    Returns:
5729        Table: A column expression
5730    """
5731    if sql_path is None or isinstance(sql_path, Column):
5732        return sql_path
5733    if not isinstance(sql_path, str):
5734        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5735    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):
5738def alias_(
5739    expression: ExpOrStr,
5740    alias: str | Identifier,
5741    table: bool | t.Sequence[str | Identifier] = False,
5742    quoted: t.Optional[bool] = None,
5743    dialect: DialectType = None,
5744    copy: bool = True,
5745    **opts,
5746):
5747    """Create an Alias expression.
5748
5749    Example:
5750        >>> alias_('foo', 'bar').sql()
5751        'foo AS bar'
5752
5753        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5754        '(SELECT 1, 2) AS bar(a, b)'
5755
5756    Args:
5757        expression: the SQL code strings to parse.
5758            If an Expression instance is passed, this is used as-is.
5759        alias: the alias name to use. If the name has
5760            special characters it is quoted.
5761        table: Whether or not to create a table alias, can also be a list of columns.
5762        quoted: whether or not to quote the alias
5763        dialect: the dialect used to parse the input expression.
5764        copy: Whether or not to copy the expression.
5765        **opts: other options to use to parse the input expressions.
5766
5767    Returns:
5768        Alias: the aliased expression
5769    """
5770    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5771    alias = to_identifier(alias, quoted=quoted)
5772
5773    if table:
5774        table_alias = TableAlias(this=alias)
5775        exp.set("alias", table_alias)
5776
5777        if not isinstance(table, bool):
5778            for column in table:
5779                table_alias.append("columns", to_identifier(column, quoted=quoted))
5780
5781        return exp
5782
5783    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5784    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5785    # for the complete Window expression.
5786    #
5787    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5788
5789    if "alias" in exp.arg_types and not isinstance(exp, Window):
5790        exp.set("alias", alias)
5791        return exp
5792    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:
5795def subquery(
5796    expression: ExpOrStr,
5797    alias: t.Optional[Identifier | str] = None,
5798    dialect: DialectType = None,
5799    **opts,
5800) -> Select:
5801    """
5802    Build a subquery expression.
5803
5804    Example:
5805        >>> subquery('select x from tbl', 'bar').select('x').sql()
5806        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5807
5808    Args:
5809        expression: the SQL code strings to parse.
5810            If an Expression instance is passed, this is used as-is.
5811        alias: the alias name to use.
5812        dialect: the dialect used to parse the input expression.
5813        **opts: other options to use to parse the input expressions.
5814
5815    Returns:
5816        A new Select instance with the subquery expression included.
5817    """
5818
5819    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5820    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:
5823def column(
5824    col: str | Identifier,
5825    table: t.Optional[str | Identifier] = None,
5826    db: t.Optional[str | Identifier] = None,
5827    catalog: t.Optional[str | Identifier] = None,
5828    quoted: t.Optional[bool] = None,
5829) -> Column:
5830    """
5831    Build a Column.
5832
5833    Args:
5834        col: Column name.
5835        table: Table name.
5836        db: Database name.
5837        catalog: Catalog name.
5838        quoted: Whether to force quotes on the column's identifiers.
5839
5840    Returns:
5841        The new Column instance.
5842    """
5843    return Column(
5844        this=to_identifier(col, quoted=quoted),
5845        table=to_identifier(table, quoted=quoted),
5846        db=to_identifier(db, quoted=quoted),
5847        catalog=to_identifier(catalog, quoted=quoted),
5848    )

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:
5851def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5852    """Cast an expression to a data type.
5853
5854    Example:
5855        >>> cast('x + 1', 'int').sql()
5856        'CAST(x + 1 AS INT)'
5857
5858    Args:
5859        expression: The expression to cast.
5860        to: The datatype to cast to.
5861
5862    Returns:
5863        The new Cast instance.
5864    """
5865    expression = maybe_parse(expression, **opts)
5866    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:
5869def table_(
5870    table: Identifier | str,
5871    db: t.Optional[Identifier | str] = None,
5872    catalog: t.Optional[Identifier | str] = None,
5873    quoted: t.Optional[bool] = None,
5874    alias: t.Optional[Identifier | str] = None,
5875) -> Table:
5876    """Build a Table.
5877
5878    Args:
5879        table: Table name.
5880        db: Database name.
5881        catalog: Catalog name.
5882        quote: Whether to force quotes on the table's identifiers.
5883        alias: Table's alias.
5884
5885    Returns:
5886        The new Table instance.
5887    """
5888    return Table(
5889        this=to_identifier(table, quoted=quoted) if table else None,
5890        db=to_identifier(db, quoted=quoted) if db else None,
5891        catalog=to_identifier(catalog, quoted=quoted) if catalog else None,
5892        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5893    )

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:
5896def values(
5897    values: t.Iterable[t.Tuple[t.Any, ...]],
5898    alias: t.Optional[str] = None,
5899    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5900) -> Values:
5901    """Build VALUES statement.
5902
5903    Example:
5904        >>> values([(1, '2')]).sql()
5905        "VALUES (1, '2')"
5906
5907    Args:
5908        values: values statements that will be converted to SQL
5909        alias: optional alias
5910        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5911         If either are provided then an alias is also required.
5912
5913    Returns:
5914        Values: the Values expression object
5915    """
5916    if columns and not alias:
5917        raise ValueError("Alias is required when providing columns")
5918
5919    return Values(
5920        expressions=[convert(tup) for tup in values],
5921        alias=(
5922            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5923            if columns
5924            else (TableAlias(this=to_identifier(alias)) if alias else None)
5925        ),
5926    )

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:
5929def var(name: t.Optional[ExpOrStr]) -> Var:
5930    """Build a SQL variable.
5931
5932    Example:
5933        >>> repr(var('x'))
5934        '(VAR this: x)'
5935
5936        >>> repr(var(column('x', table='y')))
5937        '(VAR this: x)'
5938
5939    Args:
5940        name: The name of the var or an expression who's name will become the var.
5941
5942    Returns:
5943        The new variable node.
5944    """
5945    if not name:
5946        raise ValueError("Cannot convert empty name into var.")
5947
5948    if isinstance(name, Expression):
5949        name = name.name
5950    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:
5953def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5954    """Build ALTER TABLE... RENAME... expression
5955
5956    Args:
5957        old_name: The old name of the table
5958        new_name: The new name of the table
5959
5960    Returns:
5961        Alter table expression
5962    """
5963    old_table = to_table(old_name)
5964    new_table = to_table(new_name)
5965    return AlterTable(
5966        this=old_table,
5967        actions=[
5968            RenameTable(this=new_table),
5969        ],
5970    )

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:
5973def convert(value: t.Any, copy: bool = False) -> Expression:
5974    """Convert a python value into an expression object.
5975
5976    Raises an error if a conversion is not possible.
5977
5978    Args:
5979        value: A python object.
5980        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5981
5982    Returns:
5983        Expression: the equivalent expression object.
5984    """
5985    if isinstance(value, Expression):
5986        return maybe_copy(value, copy)
5987    if isinstance(value, str):
5988        return Literal.string(value)
5989    if isinstance(value, bool):
5990        return Boolean(this=value)
5991    if value is None or (isinstance(value, float) and math.isnan(value)):
5992        return NULL
5993    if isinstance(value, numbers.Number):
5994        return Literal.number(value)
5995    if isinstance(value, datetime.datetime):
5996        datetime_literal = Literal.string(
5997            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5998        )
5999        return TimeStrToTime(this=datetime_literal)
6000    if isinstance(value, datetime.date):
6001        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
6002        return DateStrToDate(this=date_literal)
6003    if isinstance(value, tuple):
6004        return Tuple(expressions=[convert(v, copy=copy) for v in value])
6005    if isinstance(value, list):
6006        return Array(expressions=[convert(v, copy=copy) for v in value])
6007    if isinstance(value, dict):
6008        return Map(
6009            keys=Array(expressions=[convert(k, copy=copy) for k in value]),
6010            values=Array(expressions=[convert(v, copy=copy) for v in value.values()]),
6011        )
6012    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:
6015def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
6016    """
6017    Replace children of an expression with the result of a lambda fun(child) -> exp.
6018    """
6019    for k, v in expression.args.items():
6020        is_list_arg = type(v) is list
6021
6022        child_nodes = v if is_list_arg else [v]
6023        new_child_nodes = []
6024
6025        for cn in child_nodes:
6026            if isinstance(cn, Expression):
6027                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
6028                    new_child_nodes.append(child_node)
6029                    child_node.parent = expression
6030                    child_node.arg_key = k
6031            else:
6032                new_child_nodes.append(cn)
6033
6034        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]:
6037def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
6038    """
6039    Return all table names referenced through columns in an expression.
6040
6041    Example:
6042        >>> import sqlglot
6043        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
6044        ['a', 'c']
6045
6046    Args:
6047        expression: expression to find table names.
6048        exclude: a table name to exclude
6049
6050    Returns:
6051        A list of unique names.
6052    """
6053    return {
6054        table
6055        for table in (column.table for column in expression.find_all(Column))
6056        if table and table != exclude
6057    }

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:
6060def table_name(table: Table | str, dialect: DialectType = None) -> str:
6061    """Get the full name of a table as a string.
6062
6063    Args:
6064        table: Table expression node or string.
6065        dialect: The dialect to generate the table name for.
6066
6067    Examples:
6068        >>> from sqlglot import exp, parse_one
6069        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
6070        'a.b.c'
6071
6072    Returns:
6073        The table name.
6074    """
6075
6076    table = maybe_parse(table, into=Table)
6077
6078    if not table:
6079        raise ValueError(f"Cannot parse {table}")
6080
6081    return ".".join(
6082        part.sql(dialect=dialect, identify=True)
6083        if not SAFE_IDENTIFIER_RE.match(part.name)
6084        else part.name
6085        for part in table.parts
6086    )

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:
6089def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
6090    """Replace all tables in expression according to the mapping.
6091
6092    Args:
6093        expression: expression node to be transformed and replaced.
6094        mapping: mapping of table names.
6095        copy: whether or not to copy the expression.
6096
6097    Examples:
6098        >>> from sqlglot import exp, parse_one
6099        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
6100        'SELECT * FROM c'
6101
6102    Returns:
6103        The mapped expression.
6104    """
6105
6106    def _replace_tables(node: Expression) -> Expression:
6107        if isinstance(node, Table):
6108            new_name = mapping.get(table_name(node))
6109            if new_name:
6110                return to_table(
6111                    new_name,
6112                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
6113                )
6114        return node
6115
6116    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:
6119def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
6120    """Replace placeholders in an expression.
6121
6122    Args:
6123        expression: expression node to be transformed and replaced.
6124        args: positional names that will substitute unnamed placeholders in the given order.
6125        kwargs: keyword arguments that will substitute named placeholders.
6126
6127    Examples:
6128        >>> from sqlglot import exp, parse_one
6129        >>> replace_placeholders(
6130        ...     parse_one("select * from :tbl where ? = ?"),
6131        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
6132        ... ).sql()
6133        "SELECT * FROM foo WHERE str_col = 'b'"
6134
6135    Returns:
6136        The mapped expression.
6137    """
6138
6139    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
6140        if isinstance(node, Placeholder):
6141            if node.name:
6142                new_name = kwargs.get(node.name)
6143                if new_name:
6144                    return convert(new_name)
6145            else:
6146                try:
6147                    return convert(next(args))
6148                except StopIteration:
6149                    pass
6150        return node
6151
6152    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:
6155def expand(
6156    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
6157) -> Expression:
6158    """Transforms an expression by expanding all referenced sources into subqueries.
6159
6160    Examples:
6161        >>> from sqlglot import parse_one
6162        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
6163        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
6164
6165        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
6166        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
6167
6168    Args:
6169        expression: The expression to expand.
6170        sources: A dictionary of name to Subqueryables.
6171        copy: Whether or not to copy the expression during transformation. Defaults to True.
6172
6173    Returns:
6174        The transformed expression.
6175    """
6176
6177    def _expand(node: Expression):
6178        if isinstance(node, Table):
6179            name = table_name(node)
6180            source = sources.get(name)
6181            if source:
6182                subquery = source.subquery(node.alias or name)
6183                subquery.comments = [f"source: {name}"]
6184                return subquery.transform(_expand, copy=False)
6185        return node
6186
6187    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:
6190def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6191    """
6192    Returns a Func expression.
6193
6194    Examples:
6195        >>> func("abs", 5).sql()
6196        'ABS(5)'
6197
6198        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6199        'CAST(5 AS DOUBLE)'
6200
6201    Args:
6202        name: the name of the function to build.
6203        args: the args used to instantiate the function of interest.
6204        dialect: the source dialect.
6205        kwargs: the kwargs used to instantiate the function of interest.
6206
6207    Note:
6208        The arguments `args` and `kwargs` are mutually exclusive.
6209
6210    Returns:
6211        An instance of the function of interest, or an anonymous function, if `name` doesn't
6212        correspond to an existing `sqlglot.expressions.Func` class.
6213    """
6214    if args and kwargs:
6215        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6216
6217    from sqlglot.dialects.dialect import Dialect
6218
6219    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6220    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6221
6222    parser = Dialect.get_or_raise(dialect)().parser()
6223    from_args_list = parser.FUNCTIONS.get(name.upper())
6224
6225    if from_args_list:
6226        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6227    else:
6228        kwargs = kwargs or {"expressions": converted}
6229        function = Anonymous(this=name, **kwargs)
6230
6231    for error_message in function.error_messages(converted):
6232        raise ValueError(error_message)
6233
6234    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:
6237def true() -> Boolean:
6238    """
6239    Returns a true Boolean expression.
6240    """
6241    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
6244def false() -> Boolean:
6245    """
6246    Returns a false Boolean expression.
6247    """
6248    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6251def null() -> Null:
6252    """
6253    Returns a Null expression.
6254    """
6255    return Null()

Returns a Null expression.

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