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

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1175class ColumnPosition(Expression):
1176    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1179class ColumnDef(Expression):
1180    arg_types = {
1181        "this": True,
1182        "kind": False,
1183        "constraints": False,
1184        "exists": False,
1185        "position": False,
1186    }
1187
1188    @property
1189    def constraints(self) -> t.List[ColumnConstraint]:
1190        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
key = 'columndef'
class AlterColumn(Expression):
1193class AlterColumn(Expression):
1194    arg_types = {
1195        "this": True,
1196        "dtype": False,
1197        "collate": False,
1198        "using": False,
1199        "default": False,
1200        "drop": False,
1201    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1204class RenameTable(Expression):
1205    pass
key = 'renametable'
class Comment(Expression):
1208class Comment(Expression):
1209    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):
1212class Comprehension(Expression):
1213    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):
1217class MergeTreeTTLAction(Expression):
1218    arg_types = {
1219        "this": True,
1220        "delete": False,
1221        "recompress": False,
1222        "to_disk": False,
1223        "to_volume": False,
1224    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1228class MergeTreeTTL(Expression):
1229    arg_types = {
1230        "expressions": True,
1231        "where": False,
1232        "group": False,
1233        "aggregates": False,
1234    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class IndexConstraintOption(Expression):
1238class IndexConstraintOption(Expression):
1239    arg_types = {
1240        "key_block_size": False,
1241        "using": False,
1242        "parser": False,
1243        "comment": False,
1244        "visible": False,
1245        "engine_attr": False,
1246        "secondary_engine_attr": False,
1247    }
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):
1250class ColumnConstraint(Expression):
1251    arg_types = {"this": False, "kind": True}
1252
1253    @property
1254    def kind(self) -> ColumnConstraintKind:
1255        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1258class ColumnConstraintKind(Expression):
1259    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1262class AutoIncrementColumnConstraint(ColumnConstraintKind):
1263    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1266class CaseSpecificColumnConstraint(ColumnConstraintKind):
1267    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1270class CharacterSetColumnConstraint(ColumnConstraintKind):
1271    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1274class CheckColumnConstraint(ColumnConstraintKind):
1275    pass
key = 'checkcolumnconstraint'
class ClusteredColumnConstraint(ColumnConstraintKind):
1278class ClusteredColumnConstraint(ColumnConstraintKind):
1279    pass
key = 'clusteredcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1282class CollateColumnConstraint(ColumnConstraintKind):
1283    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1286class CommentColumnConstraint(ColumnConstraintKind):
1287    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1290class CompressColumnConstraint(ColumnConstraintKind):
1291    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1294class DateFormatColumnConstraint(ColumnConstraintKind):
1295    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1298class DefaultColumnConstraint(ColumnConstraintKind):
1299    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1302class EncodeColumnConstraint(ColumnConstraintKind):
1303    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1306class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1307    # this: True -> ALWAYS, this: False -> BY DEFAULT
1308    arg_types = {
1309        "this": False,
1310        "expression": False,
1311        "on_null": False,
1312        "start": False,
1313        "increment": False,
1314        "minvalue": False,
1315        "maxvalue": False,
1316        "cycle": False,
1317    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class IndexColumnConstraint(ColumnConstraintKind):
1321class IndexColumnConstraint(ColumnConstraintKind):
1322    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):
1325class InlineLengthColumnConstraint(ColumnConstraintKind):
1326    pass
key = 'inlinelengthcolumnconstraint'
class NonClusteredColumnConstraint(ColumnConstraintKind):
1329class NonClusteredColumnConstraint(ColumnConstraintKind):
1330    pass
key = 'nonclusteredcolumnconstraint'
class NotForReplicationColumnConstraint(ColumnConstraintKind):
1333class NotForReplicationColumnConstraint(ColumnConstraintKind):
1334    arg_types = {}
arg_types = {}
key = 'notforreplicationcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1337class NotNullColumnConstraint(ColumnConstraintKind):
1338    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1342class OnUpdateColumnConstraint(ColumnConstraintKind):
1343    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1346class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1347    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1350class TitleColumnConstraint(ColumnConstraintKind):
1351    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1354class UniqueColumnConstraint(ColumnConstraintKind):
1355    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1358class UppercaseColumnConstraint(ColumnConstraintKind):
1359    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1362class PathColumnConstraint(ColumnConstraintKind):
1363    pass
key = 'pathcolumnconstraint'
class ComputedColumnConstraint(ColumnConstraintKind):
1368class ComputedColumnConstraint(ColumnConstraintKind):
1369    arg_types = {"this": True, "persisted": False, "not_null": False}
arg_types = {'this': True, 'persisted': False, 'not_null': False}
key = 'computedcolumnconstraint'
class Constraint(Expression):
1372class Constraint(Expression):
1373    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1376class Delete(Expression):
1377    arg_types = {
1378        "with": False,
1379        "this": False,
1380        "using": False,
1381        "where": False,
1382        "returning": False,
1383        "limit": False,
1384        "tables": False,  # Multiple-Table Syntax (MySQL)
1385    }
1386
1387    def delete(
1388        self,
1389        table: ExpOrStr,
1390        dialect: DialectType = None,
1391        copy: bool = True,
1392        **opts,
1393    ) -> Delete:
1394        """
1395        Create a DELETE expression or replace the table on an existing DELETE expression.
1396
1397        Example:
1398            >>> delete("tbl").sql()
1399            'DELETE FROM tbl'
1400
1401        Args:
1402            table: the table from which to delete.
1403            dialect: the dialect used to parse the input expression.
1404            copy: if `False`, modify this expression instance in-place.
1405            opts: other options to use to parse the input expressions.
1406
1407        Returns:
1408            Delete: the modified expression.
1409        """
1410        return _apply_builder(
1411            expression=table,
1412            instance=self,
1413            arg="this",
1414            dialect=dialect,
1415            into=Table,
1416            copy=copy,
1417            **opts,
1418        )
1419
1420    def where(
1421        self,
1422        *expressions: t.Optional[ExpOrStr],
1423        append: bool = True,
1424        dialect: DialectType = None,
1425        copy: bool = True,
1426        **opts,
1427    ) -> Delete:
1428        """
1429        Append to or set the WHERE expressions.
1430
1431        Example:
1432            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1433            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1434
1435        Args:
1436            *expressions: the SQL code strings to parse.
1437                If an `Expression` instance is passed, it will be used as-is.
1438                Multiple expressions are combined with an AND operator.
1439            append: if `True`, AND the new expressions to any existing expression.
1440                Otherwise, this resets the expression.
1441            dialect: the dialect used to parse the input expressions.
1442            copy: if `False`, modify this expression instance in-place.
1443            opts: other options to use to parse the input expressions.
1444
1445        Returns:
1446            Delete: the modified expression.
1447        """
1448        return _apply_conjunction_builder(
1449            *expressions,
1450            instance=self,
1451            arg="where",
1452            append=append,
1453            into=Where,
1454            dialect=dialect,
1455            copy=copy,
1456            **opts,
1457        )
1458
1459    def returning(
1460        self,
1461        expression: ExpOrStr,
1462        dialect: DialectType = None,
1463        copy: bool = True,
1464        **opts,
1465    ) -> Delete:
1466        """
1467        Set the RETURNING expression. Not supported by all dialects.
1468
1469        Example:
1470            >>> delete("tbl").returning("*", dialect="postgres").sql()
1471            'DELETE FROM tbl RETURNING *'
1472
1473        Args:
1474            expression: the SQL code strings to parse.
1475                If an `Expression` instance is passed, it will be used as-is.
1476            dialect: the dialect used to parse the input expressions.
1477            copy: if `False`, modify this expression instance in-place.
1478            opts: other options to use to parse the input expressions.
1479
1480        Returns:
1481            Delete: the modified expression.
1482        """
1483        return _apply_builder(
1484            expression=expression,
1485            instance=self,
1486            arg="returning",
1487            prefix="RETURNING",
1488            dialect=dialect,
1489            copy=copy,
1490            into=Returning,
1491            **opts,
1492        )
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:
1387    def delete(
1388        self,
1389        table: ExpOrStr,
1390        dialect: DialectType = None,
1391        copy: bool = True,
1392        **opts,
1393    ) -> Delete:
1394        """
1395        Create a DELETE expression or replace the table on an existing DELETE expression.
1396
1397        Example:
1398            >>> delete("tbl").sql()
1399            'DELETE FROM tbl'
1400
1401        Args:
1402            table: the table from which to delete.
1403            dialect: the dialect used to parse the input expression.
1404            copy: if `False`, modify this expression instance in-place.
1405            opts: other options to use to parse the input expressions.
1406
1407        Returns:
1408            Delete: the modified expression.
1409        """
1410        return _apply_builder(
1411            expression=table,
1412            instance=self,
1413            arg="this",
1414            dialect=dialect,
1415            into=Table,
1416            copy=copy,
1417            **opts,
1418        )

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

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

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):
1495class Drop(Expression):
1496    arg_types = {
1497        "this": False,
1498        "kind": False,
1499        "exists": False,
1500        "temporary": False,
1501        "materialized": False,
1502        "cascade": False,
1503        "constraints": False,
1504        "purge": False,
1505    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1508class Filter(Expression):
1509    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1512class Check(Expression):
1513    pass
key = 'check'
class Connect(Expression):
1517class Connect(Expression):
1518    arg_types = {"start": False, "connect": True}
arg_types = {'start': False, 'connect': True}
key = 'connect'
class Prior(Expression):
1521class Prior(Expression):
1522    pass
key = 'prior'
class Directory(Expression):
1525class Directory(Expression):
1526    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1527    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1530class ForeignKey(Expression):
1531    arg_types = {
1532        "expressions": True,
1533        "reference": False,
1534        "delete": False,
1535        "update": False,
1536    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1539class PrimaryKey(Expression):
1540    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1545class Into(Expression):
1546    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1549class From(Expression):
1550    @property
1551    def name(self) -> str:
1552        return self.this.name
1553
1554    @property
1555    def alias_or_name(self) -> str:
1556        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1559class Having(Expression):
1560    pass
key = 'having'
class Hint(Expression):
1563class Hint(Expression):
1564    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1567class JoinHint(Expression):
1568    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1571class Identifier(Expression):
1572    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1573
1574    @property
1575    def quoted(self) -> bool:
1576        return bool(self.args.get("quoted"))
1577
1578    @property
1579    def hashable_args(self) -> t.Any:
1580        return (self.this, self.quoted)
1581
1582    @property
1583    def output_name(self) -> str:
1584        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):
1587class Index(Expression):
1588    arg_types = {
1589        "this": False,
1590        "table": False,
1591        "using": False,
1592        "where": False,
1593        "columns": False,
1594        "unique": False,
1595        "primary": False,
1596        "amp": False,  # teradata
1597        "partition_by": False,  # teradata
1598    }
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):
1601class Insert(DDL):
1602    arg_types = {
1603        "with": False,
1604        "this": True,
1605        "expression": False,
1606        "conflict": False,
1607        "returning": False,
1608        "overwrite": False,
1609        "exists": False,
1610        "partition": False,
1611        "alternative": False,
1612        "where": False,
1613        "ignore": False,
1614        "by_name": False,
1615    }
1616
1617    def with_(
1618        self,
1619        alias: ExpOrStr,
1620        as_: ExpOrStr,
1621        recursive: t.Optional[bool] = None,
1622        append: bool = True,
1623        dialect: DialectType = None,
1624        copy: bool = True,
1625        **opts,
1626    ) -> Insert:
1627        """
1628        Append to or set the common table expressions.
1629
1630        Example:
1631            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1632            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1633
1634        Args:
1635            alias: the SQL code string to parse as the table name.
1636                If an `Expression` instance is passed, this is used as-is.
1637            as_: the SQL code string to parse as the table expression.
1638                If an `Expression` instance is passed, it will be used as-is.
1639            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1640            append: if `True`, add to any existing expressions.
1641                Otherwise, this resets the expressions.
1642            dialect: the dialect used to parse the input expression.
1643            copy: if `False`, modify this expression instance in-place.
1644            opts: other options to use to parse the input expressions.
1645
1646        Returns:
1647            The modified expression.
1648        """
1649        return _apply_cte_builder(
1650            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1651        )
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:
1617    def with_(
1618        self,
1619        alias: ExpOrStr,
1620        as_: ExpOrStr,
1621        recursive: t.Optional[bool] = None,
1622        append: bool = True,
1623        dialect: DialectType = None,
1624        copy: bool = True,
1625        **opts,
1626    ) -> Insert:
1627        """
1628        Append to or set the common table expressions.
1629
1630        Example:
1631            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1632            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1633
1634        Args:
1635            alias: the SQL code string to parse as the table name.
1636                If an `Expression` instance is passed, this is used as-is.
1637            as_: the SQL code string to parse as the table expression.
1638                If an `Expression` instance is passed, it will be used as-is.
1639            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1640            append: if `True`, add to any existing expressions.
1641                Otherwise, this resets the expressions.
1642            dialect: the dialect used to parse the input expression.
1643            copy: if `False`, modify this expression instance in-place.
1644            opts: other options to use to parse the input expressions.
1645
1646        Returns:
1647            The modified expression.
1648        """
1649        return _apply_cte_builder(
1650            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1651        )

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):
1654class OnConflict(Expression):
1655    arg_types = {
1656        "duplicate": False,
1657        "expressions": False,
1658        "nothing": False,
1659        "key": False,
1660        "constraint": False,
1661    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1664class Returning(Expression):
1665    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1669class Introducer(Expression):
1670    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1674class National(Expression):
1675    pass
key = 'national'
class LoadData(Expression):
1678class LoadData(Expression):
1679    arg_types = {
1680        "this": True,
1681        "local": False,
1682        "overwrite": False,
1683        "inpath": True,
1684        "partition": False,
1685        "input_format": False,
1686        "serde": False,
1687    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1690class Partition(Expression):
1691    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1694class Fetch(Expression):
1695    arg_types = {
1696        "direction": False,
1697        "count": False,
1698        "percent": False,
1699        "with_ties": False,
1700    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1703class Group(Expression):
1704    arg_types = {
1705        "expressions": False,
1706        "grouping_sets": False,
1707        "cube": False,
1708        "rollup": False,
1709        "totals": False,
1710        "all": False,
1711    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1714class Lambda(Expression):
1715    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1718class Limit(Expression):
1719    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1722class Literal(Condition):
1723    arg_types = {"this": True, "is_string": True}
1724
1725    @property
1726    def hashable_args(self) -> t.Any:
1727        return (self.this, self.args.get("is_string"))
1728
1729    @classmethod
1730    def number(cls, number) -> Literal:
1731        return cls(this=str(number), is_string=False)
1732
1733    @classmethod
1734    def string(cls, string) -> Literal:
1735        return cls(this=str(string), is_string=True)
1736
1737    @property
1738    def output_name(self) -> str:
1739        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1729    @classmethod
1730    def number(cls, number) -> Literal:
1731        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1733    @classmethod
1734    def string(cls, string) -> Literal:
1735        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):
1742class Join(Expression):
1743    arg_types = {
1744        "this": True,
1745        "on": False,
1746        "side": False,
1747        "kind": False,
1748        "using": False,
1749        "method": False,
1750        "global": False,
1751        "hint": False,
1752    }
1753
1754    @property
1755    def method(self) -> str:
1756        return self.text("method").upper()
1757
1758    @property
1759    def kind(self) -> str:
1760        return self.text("kind").upper()
1761
1762    @property
1763    def side(self) -> str:
1764        return self.text("side").upper()
1765
1766    @property
1767    def hint(self) -> str:
1768        return self.text("hint").upper()
1769
1770    @property
1771    def alias_or_name(self) -> str:
1772        return self.this.alias_or_name
1773
1774    def on(
1775        self,
1776        *expressions: t.Optional[ExpOrStr],
1777        append: bool = True,
1778        dialect: DialectType = None,
1779        copy: bool = True,
1780        **opts,
1781    ) -> Join:
1782        """
1783        Append to or set the ON expressions.
1784
1785        Example:
1786            >>> import sqlglot
1787            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1788            'JOIN x ON y = 1'
1789
1790        Args:
1791            *expressions: the SQL code strings to parse.
1792                If an `Expression` instance is passed, it will be used as-is.
1793                Multiple expressions are combined with an AND operator.
1794            append: if `True`, AND the new expressions to any existing expression.
1795                Otherwise, this resets the expression.
1796            dialect: the dialect used to parse the input expressions.
1797            copy: if `False`, modify this expression instance in-place.
1798            opts: other options to use to parse the input expressions.
1799
1800        Returns:
1801            The modified Join expression.
1802        """
1803        join = _apply_conjunction_builder(
1804            *expressions,
1805            instance=self,
1806            arg="on",
1807            append=append,
1808            dialect=dialect,
1809            copy=copy,
1810            **opts,
1811        )
1812
1813        if join.kind == "CROSS":
1814            join.set("kind", None)
1815
1816        return join
1817
1818    def using(
1819        self,
1820        *expressions: t.Optional[ExpOrStr],
1821        append: bool = True,
1822        dialect: DialectType = None,
1823        copy: bool = True,
1824        **opts,
1825    ) -> Join:
1826        """
1827        Append to or set the USING expressions.
1828
1829        Example:
1830            >>> import sqlglot
1831            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1832            'JOIN x USING (foo, bla)'
1833
1834        Args:
1835            *expressions: the SQL code strings to parse.
1836                If an `Expression` instance is passed, it will be used as-is.
1837            append: if `True`, concatenate the new expressions to the existing "using" list.
1838                Otherwise, this resets the expression.
1839            dialect: the dialect used to parse the input expressions.
1840            copy: if `False`, modify this expression instance in-place.
1841            opts: other options to use to parse the input expressions.
1842
1843        Returns:
1844            The modified Join expression.
1845        """
1846        join = _apply_list_builder(
1847            *expressions,
1848            instance=self,
1849            arg="using",
1850            append=append,
1851            dialect=dialect,
1852            copy=copy,
1853            **opts,
1854        )
1855
1856        if join.kind == "CROSS":
1857            join.set("kind", None)
1858
1859        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:
1774    def on(
1775        self,
1776        *expressions: t.Optional[ExpOrStr],
1777        append: bool = True,
1778        dialect: DialectType = None,
1779        copy: bool = True,
1780        **opts,
1781    ) -> Join:
1782        """
1783        Append to or set the ON expressions.
1784
1785        Example:
1786            >>> import sqlglot
1787            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1788            'JOIN x ON y = 1'
1789
1790        Args:
1791            *expressions: the SQL code strings to parse.
1792                If an `Expression` instance is passed, it will be used as-is.
1793                Multiple expressions are combined with an AND operator.
1794            append: if `True`, AND the new expressions to any existing expression.
1795                Otherwise, this resets the expression.
1796            dialect: the dialect used to parse the input expressions.
1797            copy: if `False`, modify this expression instance in-place.
1798            opts: other options to use to parse the input expressions.
1799
1800        Returns:
1801            The modified Join expression.
1802        """
1803        join = _apply_conjunction_builder(
1804            *expressions,
1805            instance=self,
1806            arg="on",
1807            append=append,
1808            dialect=dialect,
1809            copy=copy,
1810            **opts,
1811        )
1812
1813        if join.kind == "CROSS":
1814            join.set("kind", None)
1815
1816        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:
1818    def using(
1819        self,
1820        *expressions: t.Optional[ExpOrStr],
1821        append: bool = True,
1822        dialect: DialectType = None,
1823        copy: bool = True,
1824        **opts,
1825    ) -> Join:
1826        """
1827        Append to or set the USING expressions.
1828
1829        Example:
1830            >>> import sqlglot
1831            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1832            'JOIN x USING (foo, bla)'
1833
1834        Args:
1835            *expressions: the SQL code strings to parse.
1836                If an `Expression` instance is passed, it will be used as-is.
1837            append: if `True`, concatenate the new expressions to the existing "using" list.
1838                Otherwise, this resets the expression.
1839            dialect: the dialect used to parse the input expressions.
1840            copy: if `False`, modify this expression instance in-place.
1841            opts: other options to use to parse the input expressions.
1842
1843        Returns:
1844            The modified Join expression.
1845        """
1846        join = _apply_list_builder(
1847            *expressions,
1848            instance=self,
1849            arg="using",
1850            append=append,
1851            dialect=dialect,
1852            copy=copy,
1853            **opts,
1854        )
1855
1856        if join.kind == "CROSS":
1857            join.set("kind", None)
1858
1859        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):
1862class Lateral(UDTF):
1863    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):
1866class MatchRecognize(Expression):
1867    arg_types = {
1868        "partition_by": False,
1869        "order": False,
1870        "measures": False,
1871        "rows": False,
1872        "after": False,
1873        "pattern": False,
1874        "define": False,
1875        "alias": False,
1876    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1881class Final(Expression):
1882    pass
key = 'final'
class Offset(Expression):
1885class Offset(Expression):
1886    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1889class Order(Expression):
1890    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1895class Cluster(Order):
1896    pass
key = 'cluster'
class Distribute(Order):
1899class Distribute(Order):
1900    pass
key = 'distribute'
class Sort(Order):
1903class Sort(Order):
1904    pass
key = 'sort'
class Ordered(Expression):
1907class Ordered(Expression):
1908    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1911class Property(Expression):
1912    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1915class AlgorithmProperty(Property):
1916    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1919class AutoIncrementProperty(Property):
1920    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1923class BlockCompressionProperty(Property):
1924    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):
1927class CharacterSetProperty(Property):
1928    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1931class ChecksumProperty(Property):
1932    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1935class CollateProperty(Property):
1936    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1939class CopyGrantsProperty(Property):
1940    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1943class DataBlocksizeProperty(Property):
1944    arg_types = {
1945        "size": False,
1946        "units": False,
1947        "minimum": False,
1948        "maximum": False,
1949        "default": False,
1950    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1953class DefinerProperty(Property):
1954    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1957class DistKeyProperty(Property):
1958    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1961class DistStyleProperty(Property):
1962    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1965class EngineProperty(Property):
1966    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
1969class HeapProperty(Property):
1970    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
1973class ToTableProperty(Property):
1974    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1977class ExecuteAsProperty(Property):
1978    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1981class ExternalProperty(Property):
1982    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1985class FallbackProperty(Property):
1986    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1989class FileFormatProperty(Property):
1990    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1993class FreespaceProperty(Property):
1994    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1997class InputOutputFormat(Expression):
1998    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
2001class IsolatedLoadingProperty(Property):
2002    arg_types = {
2003        "no": True,
2004        "concurrent": True,
2005        "for_all": True,
2006        "for_insert": True,
2007        "for_none": True,
2008    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
2011class JournalProperty(Property):
2012    arg_types = {
2013        "no": False,
2014        "dual": False,
2015        "before": False,
2016        "local": False,
2017        "after": False,
2018    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
2021class LanguageProperty(Property):
2022    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
2026class ClusteredByProperty(Property):
2027    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
2030class DictProperty(Property):
2031    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2034class DictSubProperty(Property):
2035    pass
key = 'dictsubproperty'
class DictRange(Property):
2038class DictRange(Property):
2039    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2044class OnCluster(Property):
2045    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2048class LikeProperty(Property):
2049    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2052class LocationProperty(Property):
2053    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2056class LockingProperty(Property):
2057    arg_types = {
2058        "this": False,
2059        "kind": True,
2060        "for_or_in": True,
2061        "lock_type": True,
2062        "override": False,
2063    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2066class LogProperty(Property):
2067    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2070class MaterializedProperty(Property):
2071    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2074class MergeBlockRatioProperty(Property):
2075    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):
2078class NoPrimaryIndexProperty(Property):
2079    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnProperty(Property):
2082class OnProperty(Property):
2083    arg_types = {"this": True}
arg_types = {'this': True}
key = 'onproperty'
class OnCommitProperty(Property):
2086class OnCommitProperty(Property):
2087    arg_types = {"delete": False}
arg_types = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2090class PartitionedByProperty(Property):
2091    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2094class ReturnsProperty(Property):
2095    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2098class RowFormatProperty(Property):
2099    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2102class RowFormatDelimitedProperty(Property):
2103    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2104    arg_types = {
2105        "fields": False,
2106        "escaped": False,
2107        "collection_items": False,
2108        "map_keys": False,
2109        "lines": False,
2110        "null": False,
2111        "serde": False,
2112    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2115class RowFormatSerdeProperty(Property):
2116    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2120class QueryTransform(Expression):
2121    arg_types = {
2122        "expressions": True,
2123        "command_script": True,
2124        "schema": False,
2125        "row_format_before": False,
2126        "record_writer": False,
2127        "row_format_after": False,
2128        "record_reader": False,
2129    }
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):
2132class SchemaCommentProperty(Property):
2133    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2136class SerdeProperties(Property):
2137    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2140class SetProperty(Property):
2141    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2144class SettingsProperty(Property):
2145    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2148class SortKeyProperty(Property):
2149    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2152class SqlSecurityProperty(Property):
2153    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2156class StabilityProperty(Property):
2157    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2160class TemporaryProperty(Property):
2161    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2164class TransientProperty(Property):
2165    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2168class VolatileProperty(Property):
2169    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2172class WithDataProperty(Property):
2173    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2176class WithJournalTableProperty(Property):
2177    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2180class Properties(Expression):
2181    arg_types = {"expressions": True}
2182
2183    NAME_TO_PROPERTY = {
2184        "ALGORITHM": AlgorithmProperty,
2185        "AUTO_INCREMENT": AutoIncrementProperty,
2186        "CHARACTER SET": CharacterSetProperty,
2187        "CLUSTERED_BY": ClusteredByProperty,
2188        "COLLATE": CollateProperty,
2189        "COMMENT": SchemaCommentProperty,
2190        "DEFINER": DefinerProperty,
2191        "DISTKEY": DistKeyProperty,
2192        "DISTSTYLE": DistStyleProperty,
2193        "ENGINE": EngineProperty,
2194        "EXECUTE AS": ExecuteAsProperty,
2195        "FORMAT": FileFormatProperty,
2196        "LANGUAGE": LanguageProperty,
2197        "LOCATION": LocationProperty,
2198        "PARTITIONED_BY": PartitionedByProperty,
2199        "RETURNS": ReturnsProperty,
2200        "ROW_FORMAT": RowFormatProperty,
2201        "SORTKEY": SortKeyProperty,
2202    }
2203
2204    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2205
2206    # CREATE property locations
2207    # Form: schema specified
2208    #   create [POST_CREATE]
2209    #     table a [POST_NAME]
2210    #     (b int) [POST_SCHEMA]
2211    #     with ([POST_WITH])
2212    #     index (b) [POST_INDEX]
2213    #
2214    # Form: alias selection
2215    #   create [POST_CREATE]
2216    #     table a [POST_NAME]
2217    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2218    #     index (c) [POST_INDEX]
2219    class Location(AutoName):
2220        POST_CREATE = auto()
2221        POST_NAME = auto()
2222        POST_SCHEMA = auto()
2223        POST_WITH = auto()
2224        POST_ALIAS = auto()
2225        POST_EXPRESSION = auto()
2226        POST_INDEX = auto()
2227        UNSUPPORTED = auto()
2228
2229    @classmethod
2230    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2231        expressions = []
2232        for key, value in properties_dict.items():
2233            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2234            if property_cls:
2235                expressions.append(property_cls(this=convert(value)))
2236            else:
2237                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2238
2239        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:
2229    @classmethod
2230    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2231        expressions = []
2232        for key, value in properties_dict.items():
2233            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2234            if property_cls:
2235                expressions.append(property_cls(this=convert(value)))
2236            else:
2237                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2238
2239        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2219    class Location(AutoName):
2220        POST_CREATE = auto()
2221        POST_NAME = auto()
2222        POST_SCHEMA = auto()
2223        POST_WITH = auto()
2224        POST_ALIAS = auto()
2225        POST_EXPRESSION = auto()
2226        POST_INDEX = auto()
2227        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):
2242class Qualify(Expression):
2243    pass
key = 'qualify'
class Return(Expression):
2247class Return(Expression):
2248    pass
key = 'return'
class Reference(Expression):
2251class Reference(Expression):
2252    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2255class Tuple(Expression):
2256    arg_types = {"expressions": False}
2257
2258    def isin(
2259        self,
2260        *expressions: t.Any,
2261        query: t.Optional[ExpOrStr] = None,
2262        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2263        copy: bool = True,
2264        **opts,
2265    ) -> In:
2266        return In(
2267            this=maybe_copy(self, copy),
2268            expressions=[convert(e, copy=copy) for e in expressions],
2269            query=maybe_parse(query, copy=copy, **opts) if query else None,
2270            unnest=Unnest(
2271                expressions=[
2272                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2273                ]
2274            )
2275            if unnest
2276            else None,
2277        )
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:
2258    def isin(
2259        self,
2260        *expressions: t.Any,
2261        query: t.Optional[ExpOrStr] = None,
2262        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2263        copy: bool = True,
2264        **opts,
2265    ) -> In:
2266        return In(
2267            this=maybe_copy(self, copy),
2268            expressions=[convert(e, copy=copy) for e in expressions],
2269            query=maybe_parse(query, copy=copy, **opts) if query else None,
2270            unnest=Unnest(
2271                expressions=[
2272                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2273                ]
2274            )
2275            if unnest
2276            else None,
2277        )
key = 'tuple'
class Subqueryable(Unionable):
2280class Subqueryable(Unionable):
2281    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2282        """
2283        Convert this expression to an aliased expression that can be used as a Subquery.
2284
2285        Example:
2286            >>> subquery = Select().select("x").from_("tbl").subquery()
2287            >>> Select().select("x").from_(subquery).sql()
2288            'SELECT x FROM (SELECT x FROM tbl)'
2289
2290        Args:
2291            alias (str | Identifier): an optional alias for the subquery
2292            copy (bool): if `False`, modify this expression instance in-place.
2293
2294        Returns:
2295            Alias: the subquery
2296        """
2297        instance = maybe_copy(self, copy)
2298        if not isinstance(alias, Expression):
2299            alias = TableAlias(this=to_identifier(alias)) if alias else None
2300
2301        return Subquery(this=instance, alias=alias)
2302
2303    def limit(
2304        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2305    ) -> Select:
2306        raise NotImplementedError
2307
2308    @property
2309    def ctes(self):
2310        with_ = self.args.get("with")
2311        if not with_:
2312            return []
2313        return with_.expressions
2314
2315    @property
2316    def selects(self) -> t.List[Expression]:
2317        raise NotImplementedError("Subqueryable objects must implement `selects`")
2318
2319    @property
2320    def named_selects(self) -> t.List[str]:
2321        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2322
2323    def select(
2324        self,
2325        *expressions: t.Optional[ExpOrStr],
2326        append: bool = True,
2327        dialect: DialectType = None,
2328        copy: bool = True,
2329        **opts,
2330    ) -> Subqueryable:
2331        raise NotImplementedError("Subqueryable objects must implement `select`")
2332
2333    def with_(
2334        self,
2335        alias: ExpOrStr,
2336        as_: ExpOrStr,
2337        recursive: t.Optional[bool] = None,
2338        append: bool = True,
2339        dialect: DialectType = None,
2340        copy: bool = True,
2341        **opts,
2342    ) -> Subqueryable:
2343        """
2344        Append to or set the common table expressions.
2345
2346        Example:
2347            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2348            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2349
2350        Args:
2351            alias: the SQL code string to parse as the table name.
2352                If an `Expression` instance is passed, this is used as-is.
2353            as_: the SQL code string to parse as the table expression.
2354                If an `Expression` instance is passed, it will be used as-is.
2355            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2356            append: if `True`, add to any existing expressions.
2357                Otherwise, this resets the expressions.
2358            dialect: the dialect used to parse the input expression.
2359            copy: if `False`, modify this expression instance in-place.
2360            opts: other options to use to parse the input expressions.
2361
2362        Returns:
2363            The modified expression.
2364        """
2365        return _apply_cte_builder(
2366            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2367        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2281    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2282        """
2283        Convert this expression to an aliased expression that can be used as a Subquery.
2284
2285        Example:
2286            >>> subquery = Select().select("x").from_("tbl").subquery()
2287            >>> Select().select("x").from_(subquery).sql()
2288            'SELECT x FROM (SELECT x FROM tbl)'
2289
2290        Args:
2291            alias (str | Identifier): an optional alias for the subquery
2292            copy (bool): if `False`, modify this expression instance in-place.
2293
2294        Returns:
2295            Alias: the subquery
2296        """
2297        instance = maybe_copy(self, copy)
2298        if not isinstance(alias, Expression):
2299            alias = TableAlias(this=to_identifier(alias)) if alias else None
2300
2301        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:
2303    def limit(
2304        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2305    ) -> Select:
2306        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:
2323    def select(
2324        self,
2325        *expressions: t.Optional[ExpOrStr],
2326        append: bool = True,
2327        dialect: DialectType = None,
2328        copy: bool = True,
2329        **opts,
2330    ) -> Subqueryable:
2331        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:
2333    def with_(
2334        self,
2335        alias: ExpOrStr,
2336        as_: ExpOrStr,
2337        recursive: t.Optional[bool] = None,
2338        append: bool = True,
2339        dialect: DialectType = None,
2340        copy: bool = True,
2341        **opts,
2342    ) -> Subqueryable:
2343        """
2344        Append to or set the common table expressions.
2345
2346        Example:
2347            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2348            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2349
2350        Args:
2351            alias: the SQL code string to parse as the table name.
2352                If an `Expression` instance is passed, this is used as-is.
2353            as_: the SQL code string to parse as the table expression.
2354                If an `Expression` instance is passed, it will be used as-is.
2355            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2356            append: if `True`, add to any existing expressions.
2357                Otherwise, this resets the expressions.
2358            dialect: the dialect used to parse the input expression.
2359            copy: if `False`, modify this expression instance in-place.
2360            opts: other options to use to parse the input expressions.
2361
2362        Returns:
2363            The modified expression.
2364        """
2365        return _apply_cte_builder(
2366            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2367        )

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):
2395class WithTableHint(Expression):
2396    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2400class IndexTableHint(Expression):
2401    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2404class Table(Expression):
2405    arg_types = {
2406        "this": True,
2407        "alias": False,
2408        "db": False,
2409        "catalog": False,
2410        "laterals": False,
2411        "joins": False,
2412        "pivots": False,
2413        "hints": False,
2414        "system_time": False,
2415    }
2416
2417    @property
2418    def name(self) -> str:
2419        if isinstance(self.this, Func):
2420            return ""
2421        return self.this.name
2422
2423    @property
2424    def db(self) -> str:
2425        return self.text("db")
2426
2427    @property
2428    def catalog(self) -> str:
2429        return self.text("catalog")
2430
2431    @property
2432    def selects(self) -> t.List[Expression]:
2433        return []
2434
2435    @property
2436    def named_selects(self) -> t.List[str]:
2437        return []
2438
2439    @property
2440    def parts(self) -> t.List[Identifier]:
2441        """Return the parts of a table in order catalog, db, table."""
2442        parts: t.List[Identifier] = []
2443
2444        for arg in ("catalog", "db", "this"):
2445            part = self.args.get(arg)
2446
2447            if isinstance(part, Identifier):
2448                parts.append(part)
2449            elif isinstance(part, Dot):
2450                parts.extend(part.flatten())
2451
2452        return parts
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False}
name: str
db: str
catalog: str
named_selects: List[str]

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

key = 'table'
class SystemTime(Expression):
2456class SystemTime(Expression):
2457    arg_types = {
2458        "this": False,
2459        "expression": False,
2460        "kind": True,
2461    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2464class Union(Subqueryable):
2465    arg_types = {
2466        "with": False,
2467        "this": True,
2468        "expression": True,
2469        "distinct": False,
2470        "by_name": False,
2471        **QUERY_MODIFIERS,
2472    }
2473
2474    def limit(
2475        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2476    ) -> Select:
2477        """
2478        Set the LIMIT expression.
2479
2480        Example:
2481            >>> select("1").union(select("1")).limit(1).sql()
2482            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2483
2484        Args:
2485            expression: the SQL code string to parse.
2486                This can also be an integer.
2487                If a `Limit` instance is passed, this is used as-is.
2488                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2489            dialect: the dialect used to parse the input expression.
2490            copy: if `False`, modify this expression instance in-place.
2491            opts: other options to use to parse the input expressions.
2492
2493        Returns:
2494            The limited subqueryable.
2495        """
2496        return (
2497            select("*")
2498            .from_(self.subquery(alias="_l_0", copy=copy))
2499            .limit(expression, dialect=dialect, copy=False, **opts)
2500        )
2501
2502    def select(
2503        self,
2504        *expressions: t.Optional[ExpOrStr],
2505        append: bool = True,
2506        dialect: DialectType = None,
2507        copy: bool = True,
2508        **opts,
2509    ) -> Union:
2510        """Append to or set the SELECT of the union recursively.
2511
2512        Example:
2513            >>> from sqlglot import parse_one
2514            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2515            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2516
2517        Args:
2518            *expressions: the SQL code strings to parse.
2519                If an `Expression` instance is passed, it will be used as-is.
2520            append: if `True`, add to any existing expressions.
2521                Otherwise, this resets the expressions.
2522            dialect: the dialect used to parse the input expressions.
2523            copy: if `False`, modify this expression instance in-place.
2524            opts: other options to use to parse the input expressions.
2525
2526        Returns:
2527            Union: the modified expression.
2528        """
2529        this = self.copy() if copy else self
2530        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2531        this.expression.unnest().select(
2532            *expressions, append=append, dialect=dialect, copy=False, **opts
2533        )
2534        return this
2535
2536    @property
2537    def named_selects(self) -> t.List[str]:
2538        return self.this.unnest().named_selects
2539
2540    @property
2541    def is_star(self) -> bool:
2542        return self.this.is_star or self.expression.is_star
2543
2544    @property
2545    def selects(self) -> t.List[Expression]:
2546        return self.this.unnest().selects
2547
2548    @property
2549    def left(self):
2550        return self.this
2551
2552    @property
2553    def right(self):
2554        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:
2474    def limit(
2475        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2476    ) -> Select:
2477        """
2478        Set the LIMIT expression.
2479
2480        Example:
2481            >>> select("1").union(select("1")).limit(1).sql()
2482            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2483
2484        Args:
2485            expression: the SQL code string to parse.
2486                This can also be an integer.
2487                If a `Limit` instance is passed, this is used as-is.
2488                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2489            dialect: the dialect used to parse the input expression.
2490            copy: if `False`, modify this expression instance in-place.
2491            opts: other options to use to parse the input expressions.
2492
2493        Returns:
2494            The limited subqueryable.
2495        """
2496        return (
2497            select("*")
2498            .from_(self.subquery(alias="_l_0", copy=copy))
2499            .limit(expression, dialect=dialect, copy=False, **opts)
2500        )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Returns the first non subquery.

def unwrap(self) -> sqlglot.expressions.Subquery:
3316    def unwrap(self) -> Subquery:
3317        expression = self
3318        while expression.same_parent and expression.is_wrapper:
3319            expression = t.cast(Subquery, expression.parent)
3320        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):
3342class TableSample(Expression):
3343    arg_types = {
3344        "this": False,
3345        "method": False,
3346        "bucket_numerator": False,
3347        "bucket_denominator": False,
3348        "bucket_field": False,
3349        "percent": False,
3350        "rows": False,
3351        "size": False,
3352        "seed": False,
3353        "kind": False,
3354    }
arg_types = {'this': False, 'method': False, 'bucket_numerator': False, 'bucket_denominator': False, 'bucket_field': False, 'percent': False, 'rows': False, 'size': False, 'seed': False, 'kind': False}
key = 'tablesample'
class Tag(Expression):
3357class Tag(Expression):
3358    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3359
3360    arg_types = {
3361        "this": False,
3362        "prefix": False,
3363        "postfix": False,
3364    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3369class Pivot(Expression):
3370    arg_types = {
3371        "this": False,
3372        "alias": False,
3373        "expressions": True,
3374        "field": False,
3375        "unpivot": False,
3376        "using": False,
3377        "group": False,
3378        "columns": False,
3379        "include_nulls": False,
3380    }
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):
3383class Window(Condition):
3384    arg_types = {
3385        "this": True,
3386        "partition_by": False,
3387        "order": False,
3388        "spec": False,
3389        "alias": False,
3390        "over": False,
3391        "first": False,
3392    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3395class WindowSpec(Expression):
3396    arg_types = {
3397        "kind": False,
3398        "start": False,
3399        "start_side": False,
3400        "end": False,
3401        "end_side": False,
3402    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3405class Where(Expression):
3406    pass
key = 'where'
class Star(Expression):
3409class Star(Expression):
3410    arg_types = {"except": False, "replace": False}
3411
3412    @property
3413    def name(self) -> str:
3414        return "*"
3415
3416    @property
3417    def output_name(self) -> str:
3418        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):
3421class Parameter(Condition):
3422    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3425class SessionParameter(Condition):
3426    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3429class Placeholder(Condition):
3430    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3433class Null(Condition):
3434    arg_types: t.Dict[str, t.Any] = {}
3435
3436    @property
3437    def name(self) -> str:
3438        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3441class Boolean(Condition):
3442    pass
key = 'boolean'
class DataTypeParam(Expression):
3445class DataTypeParam(Expression):
3446    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypeparam'
class DataType(Expression):
3449class DataType(Expression):
3450    arg_types = {
3451        "this": True,
3452        "expressions": False,
3453        "nested": False,
3454        "values": False,
3455        "prefix": False,
3456        "kind": False,
3457    }
3458
3459    class Type(AutoName):
3460        ARRAY = auto()
3461        BIGDECIMAL = auto()
3462        BIGINT = auto()
3463        BIGSERIAL = auto()
3464        BINARY = auto()
3465        BIT = auto()
3466        BOOLEAN = auto()
3467        CHAR = auto()
3468        DATE = auto()
3469        DATEMULTIRANGE = auto()
3470        DATERANGE = auto()
3471        DATETIME = auto()
3472        DATETIME64 = auto()
3473        DECIMAL = auto()
3474        DOUBLE = auto()
3475        ENUM = auto()
3476        ENUM8 = auto()
3477        ENUM16 = auto()
3478        FIXEDSTRING = auto()
3479        FLOAT = auto()
3480        GEOGRAPHY = auto()
3481        GEOMETRY = auto()
3482        HLLSKETCH = auto()
3483        HSTORE = auto()
3484        IMAGE = auto()
3485        INET = auto()
3486        INT = auto()
3487        INT128 = auto()
3488        INT256 = auto()
3489        INT4MULTIRANGE = auto()
3490        INT4RANGE = auto()
3491        INT8MULTIRANGE = auto()
3492        INT8RANGE = auto()
3493        INTERVAL = auto()
3494        IPADDRESS = auto()
3495        IPPREFIX = auto()
3496        JSON = auto()
3497        JSONB = auto()
3498        LONGBLOB = auto()
3499        LONGTEXT = auto()
3500        LOWCARDINALITY = auto()
3501        MAP = auto()
3502        MEDIUMBLOB = auto()
3503        MEDIUMINT = auto()
3504        MEDIUMTEXT = auto()
3505        MONEY = auto()
3506        NCHAR = auto()
3507        NESTED = auto()
3508        NULL = auto()
3509        NULLABLE = auto()
3510        NUMMULTIRANGE = auto()
3511        NUMRANGE = auto()
3512        NVARCHAR = auto()
3513        OBJECT = auto()
3514        ROWVERSION = auto()
3515        SERIAL = auto()
3516        SET = auto()
3517        SMALLINT = auto()
3518        SMALLMONEY = auto()
3519        SMALLSERIAL = auto()
3520        STRUCT = auto()
3521        SUPER = auto()
3522        TEXT = auto()
3523        TIME = auto()
3524        TIMETZ = auto()
3525        TIMESTAMP = auto()
3526        TIMESTAMPLTZ = auto()
3527        TIMESTAMPTZ = auto()
3528        TINYINT = auto()
3529        TSMULTIRANGE = auto()
3530        TSRANGE = auto()
3531        TSTZMULTIRANGE = auto()
3532        TSTZRANGE = auto()
3533        UBIGINT = auto()
3534        UINT = auto()
3535        UINT128 = auto()
3536        UINT256 = auto()
3537        UNIQUEIDENTIFIER = auto()
3538        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3539        USERDEFINED = "USER-DEFINED"
3540        USMALLINT = auto()
3541        UTINYINT = auto()
3542        UUID = auto()
3543        VARBINARY = auto()
3544        VARCHAR = auto()
3545        VARIANT = auto()
3546        XML = auto()
3547        YEAR = auto()
3548
3549    TEXT_TYPES = {
3550        Type.CHAR,
3551        Type.NCHAR,
3552        Type.VARCHAR,
3553        Type.NVARCHAR,
3554        Type.TEXT,
3555    }
3556
3557    INTEGER_TYPES = {
3558        Type.INT,
3559        Type.TINYINT,
3560        Type.SMALLINT,
3561        Type.BIGINT,
3562        Type.INT128,
3563        Type.INT256,
3564    }
3565
3566    FLOAT_TYPES = {
3567        Type.FLOAT,
3568        Type.DOUBLE,
3569    }
3570
3571    NUMERIC_TYPES = {
3572        *INTEGER_TYPES,
3573        *FLOAT_TYPES,
3574    }
3575
3576    TEMPORAL_TYPES = {
3577        Type.TIME,
3578        Type.TIMETZ,
3579        Type.TIMESTAMP,
3580        Type.TIMESTAMPTZ,
3581        Type.TIMESTAMPLTZ,
3582        Type.DATE,
3583        Type.DATETIME,
3584        Type.DATETIME64,
3585    }
3586
3587    @classmethod
3588    def build(
3589        cls,
3590        dtype: str | DataType | DataType.Type,
3591        dialect: DialectType = None,
3592        udt: bool = False,
3593        **kwargs,
3594    ) -> DataType:
3595        """
3596        Constructs a DataType object.
3597
3598        Args:
3599            dtype: the data type of interest.
3600            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3601            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3602                DataType, thus creating a user-defined type.
3603            kawrgs: additional arguments to pass in the constructor of DataType.
3604
3605        Returns:
3606            The constructed DataType object.
3607        """
3608        from sqlglot import parse_one
3609
3610        if isinstance(dtype, str):
3611            if dtype.upper() == "UNKNOWN":
3612                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3613
3614            try:
3615                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3616            except ParseError:
3617                if udt:
3618                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3619                raise
3620        elif isinstance(dtype, DataType.Type):
3621            data_type_exp = DataType(this=dtype)
3622        elif isinstance(dtype, DataType):
3623            return dtype
3624        else:
3625            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3626
3627        return DataType(**{**data_type_exp.args, **kwargs})
3628
3629    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3630        """
3631        Checks whether this DataType matches one of the provided data types. Nested types or precision
3632        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3633
3634        Args:
3635            dtypes: the data types to compare this DataType to.
3636
3637        Returns:
3638            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3639        """
3640        for dtype in dtypes:
3641            other = DataType.build(dtype, udt=True)
3642
3643            if (
3644                other.expressions
3645                or self.this == DataType.Type.USERDEFINED
3646                or other.this == DataType.Type.USERDEFINED
3647            ):
3648                matches = self == other
3649            else:
3650                matches = self.this == other.this
3651
3652            if matches:
3653                return True
3654        return False
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False, 'kind': False}
TEXT_TYPES = {<Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.TEXT: 'TEXT'>}
INTEGER_TYPES = {<Type.INT128: 'INT128'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT256: 'INT256'>, <Type.INT: 'INT'>, <Type.BIGINT: 'BIGINT'>, <Type.TINYINT: 'TINYINT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.SMALLINT: 'SMALLINT'>, <Type.INT256: 'INT256'>, <Type.INT128: 'INT128'>, <Type.INT: 'INT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.BIGINT: 'BIGINT'>, <Type.TINYINT: 'TINYINT'>, <Type.FLOAT: 'FLOAT'>}
TEMPORAL_TYPES = {<Type.TIME: 'TIME'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.DATE: 'DATE'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATETIME64: 'DATETIME64'>, <Type.DATETIME: 'DATETIME'>, <Type.TIMETZ: 'TIMETZ'>}
@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:
3587    @classmethod
3588    def build(
3589        cls,
3590        dtype: str | DataType | DataType.Type,
3591        dialect: DialectType = None,
3592        udt: bool = False,
3593        **kwargs,
3594    ) -> DataType:
3595        """
3596        Constructs a DataType object.
3597
3598        Args:
3599            dtype: the data type of interest.
3600            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3601            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3602                DataType, thus creating a user-defined type.
3603            kawrgs: additional arguments to pass in the constructor of DataType.
3604
3605        Returns:
3606            The constructed DataType object.
3607        """
3608        from sqlglot import parse_one
3609
3610        if isinstance(dtype, str):
3611            if dtype.upper() == "UNKNOWN":
3612                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3613
3614            try:
3615                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3616            except ParseError:
3617                if udt:
3618                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3619                raise
3620        elif isinstance(dtype, DataType.Type):
3621            data_type_exp = DataType(this=dtype)
3622        elif isinstance(dtype, DataType):
3623            return dtype
3624        else:
3625            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3626
3627        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:
3629    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3630        """
3631        Checks whether this DataType matches one of the provided data types. Nested types or precision
3632        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3633
3634        Args:
3635            dtypes: the data types to compare this DataType to.
3636
3637        Returns:
3638            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3639        """
3640        for dtype in dtypes:
3641            other = DataType.build(dtype, udt=True)
3642
3643            if (
3644                other.expressions
3645                or self.this == DataType.Type.USERDEFINED
3646                or other.this == DataType.Type.USERDEFINED
3647            ):
3648                matches = self == other
3649            else:
3650                matches = self.this == other.this
3651
3652            if matches:
3653                return True
3654        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):
3459    class Type(AutoName):
3460        ARRAY = auto()
3461        BIGDECIMAL = auto()
3462        BIGINT = auto()
3463        BIGSERIAL = auto()
3464        BINARY = auto()
3465        BIT = auto()
3466        BOOLEAN = auto()
3467        CHAR = auto()
3468        DATE = auto()
3469        DATEMULTIRANGE = auto()
3470        DATERANGE = auto()
3471        DATETIME = auto()
3472        DATETIME64 = auto()
3473        DECIMAL = auto()
3474        DOUBLE = auto()
3475        ENUM = auto()
3476        ENUM8 = auto()
3477        ENUM16 = auto()
3478        FIXEDSTRING = auto()
3479        FLOAT = auto()
3480        GEOGRAPHY = auto()
3481        GEOMETRY = auto()
3482        HLLSKETCH = auto()
3483        HSTORE = auto()
3484        IMAGE = auto()
3485        INET = auto()
3486        INT = auto()
3487        INT128 = auto()
3488        INT256 = auto()
3489        INT4MULTIRANGE = auto()
3490        INT4RANGE = auto()
3491        INT8MULTIRANGE = auto()
3492        INT8RANGE = auto()
3493        INTERVAL = auto()
3494        IPADDRESS = auto()
3495        IPPREFIX = auto()
3496        JSON = auto()
3497        JSONB = auto()
3498        LONGBLOB = auto()
3499        LONGTEXT = auto()
3500        LOWCARDINALITY = auto()
3501        MAP = auto()
3502        MEDIUMBLOB = auto()
3503        MEDIUMINT = auto()
3504        MEDIUMTEXT = auto()
3505        MONEY = auto()
3506        NCHAR = auto()
3507        NESTED = auto()
3508        NULL = auto()
3509        NULLABLE = auto()
3510        NUMMULTIRANGE = auto()
3511        NUMRANGE = auto()
3512        NVARCHAR = auto()
3513        OBJECT = auto()
3514        ROWVERSION = auto()
3515        SERIAL = auto()
3516        SET = auto()
3517        SMALLINT = auto()
3518        SMALLMONEY = auto()
3519        SMALLSERIAL = auto()
3520        STRUCT = auto()
3521        SUPER = auto()
3522        TEXT = auto()
3523        TIME = auto()
3524        TIMETZ = auto()
3525        TIMESTAMP = auto()
3526        TIMESTAMPLTZ = auto()
3527        TIMESTAMPTZ = auto()
3528        TINYINT = auto()
3529        TSMULTIRANGE = auto()
3530        TSRANGE = auto()
3531        TSTZMULTIRANGE = auto()
3532        TSTZRANGE = auto()
3533        UBIGINT = auto()
3534        UINT = auto()
3535        UINT128 = auto()
3536        UINT256 = auto()
3537        UNIQUEIDENTIFIER = auto()
3538        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3539        USERDEFINED = "USER-DEFINED"
3540        USMALLINT = auto()
3541        UTINYINT = auto()
3542        UUID = auto()
3543        VARBINARY = auto()
3544        VARCHAR = auto()
3545        VARIANT = auto()
3546        XML = auto()
3547        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'>
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):
3658class PseudoType(Expression):
3659    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3663class SubqueryPredicate(Predicate):
3664    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3667class All(SubqueryPredicate):
3668    pass
key = 'all'
class Any(SubqueryPredicate):
3671class Any(SubqueryPredicate):
3672    pass
key = 'any'
class Exists(SubqueryPredicate):
3675class Exists(SubqueryPredicate):
3676    pass
key = 'exists'
class Command(Expression):
3681class Command(Expression):
3682    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3685class Transaction(Expression):
3686    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3689class Commit(Expression):
3690    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3693class Rollback(Expression):
3694    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3697class AlterTable(Expression):
3698    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3701class AddConstraint(Expression):
3702    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3705class DropPartition(Expression):
3706    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3710class Binary(Condition):
3711    arg_types = {"this": True, "expression": True}
3712
3713    @property
3714    def left(self):
3715        return self.this
3716
3717    @property
3718    def right(self):
3719        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3722class Add(Binary):
3723    pass
key = 'add'
class Connector(Binary):
3726class Connector(Binary):
3727    pass
key = 'connector'
class And(Connector):
3730class And(Connector):
3731    pass
key = 'and'
class Or(Connector):
3734class Or(Connector):
3735    pass
key = 'or'
class BitwiseAnd(Binary):
3738class BitwiseAnd(Binary):
3739    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3742class BitwiseLeftShift(Binary):
3743    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3746class BitwiseOr(Binary):
3747    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3750class BitwiseRightShift(Binary):
3751    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3754class BitwiseXor(Binary):
3755    pass
key = 'bitwisexor'
class Div(Binary):
3758class Div(Binary):
3759    pass
key = 'div'
class Overlaps(Binary):
3762class Overlaps(Binary):
3763    pass
key = 'overlaps'
class Dot(Binary):
3766class Dot(Binary):
3767    @property
3768    def name(self) -> str:
3769        return self.expression.name
3770
3771    @property
3772    def output_name(self) -> str:
3773        return self.name
3774
3775    @classmethod
3776    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3777        """Build a Dot object with a sequence of expressions."""
3778        if len(expressions) < 2:
3779            raise ValueError(f"Dot requires >= 2 expressions.")
3780
3781        a, b, *expressions = expressions
3782        dot = Dot(this=a, expression=b)
3783
3784        for expression in expressions:
3785            dot = Dot(this=dot, expression=expression)
3786
3787        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:
3775    @classmethod
3776    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3777        """Build a Dot object with a sequence of expressions."""
3778        if len(expressions) < 2:
3779            raise ValueError(f"Dot requires >= 2 expressions.")
3780
3781        a, b, *expressions = expressions
3782        dot = Dot(this=a, expression=b)
3783
3784        for expression in expressions:
3785            dot = Dot(this=dot, expression=expression)
3786
3787        return dot

Build a Dot object with a sequence of expressions.

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

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

key = 'kwarg'
class Like(Binary, Predicate):
3850class Like(Binary, Predicate):
3851    pass
key = 'like'
class LikeAny(Binary, Predicate):
3854class LikeAny(Binary, Predicate):
3855    pass
key = 'likeany'
class LT(Binary, Predicate):
3858class LT(Binary, Predicate):
3859    pass
key = 'lt'
class LTE(Binary, Predicate):
3862class LTE(Binary, Predicate):
3863    pass
key = 'lte'
class Mod(Binary):
3866class Mod(Binary):
3867    pass
key = 'mod'
class Mul(Binary):
3870class Mul(Binary):
3871    pass
key = 'mul'
class NEQ(Binary, Predicate):
3874class NEQ(Binary, Predicate):
3875    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3878class SimilarTo(Binary, Predicate):
3879    pass
key = 'similarto'
class Slice(Binary):
3882class Slice(Binary):
3883    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3886class Sub(Binary):
3887    pass
key = 'sub'
class ArrayOverlaps(Binary):
3890class ArrayOverlaps(Binary):
3891    pass
key = 'arrayoverlaps'
class Unary(Condition):
3896class Unary(Condition):
3897    pass
key = 'unary'
class BitwiseNot(Unary):
3900class BitwiseNot(Unary):
3901    pass
key = 'bitwisenot'
class Not(Unary):
3904class Not(Unary):
3905    pass
key = 'not'
class Paren(Unary):
3908class Paren(Unary):
3909    arg_types = {"this": True, "with": False}
3910
3911    @property
3912    def output_name(self) -> str:
3913        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):
3916class Neg(Unary):
3917    pass
key = 'neg'
class Alias(Expression):
3920class Alias(Expression):
3921    arg_types = {"this": True, "alias": False}
3922
3923    @property
3924    def output_name(self) -> str:
3925        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):
3928class Aliases(Expression):
3929    arg_types = {"this": True, "expressions": True}
3930
3931    @property
3932    def aliases(self):
3933        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3936class AtTimeZone(Expression):
3937    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3940class Between(Predicate):
3941    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3944class Bracket(Condition):
3945    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3948class SafeBracket(Bracket):
3949    """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):
3952class Distinct(Expression):
3953    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3956class In(Predicate):
3957    arg_types = {
3958        "this": True,
3959        "expressions": False,
3960        "query": False,
3961        "unnest": False,
3962        "field": False,
3963        "is_global": False,
3964    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3967class TimeUnit(Expression):
3968    """Automatically converts unit arg into a var."""
3969
3970    arg_types = {"unit": False}
3971
3972    def __init__(self, **args):
3973        unit = args.get("unit")
3974        if isinstance(unit, (Column, Literal)):
3975            args["unit"] = Var(this=unit.name)
3976        elif isinstance(unit, Week):
3977            unit.set("this", Var(this=unit.this.name))
3978
3979        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3972    def __init__(self, **args):
3973        unit = args.get("unit")
3974        if isinstance(unit, (Column, Literal)):
3975            args["unit"] = Var(this=unit.name)
3976        elif isinstance(unit, Week):
3977            unit.set("this", Var(this=unit.this.name))
3978
3979        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class IntervalYearToMonthSpan(Expression):
3984class IntervalYearToMonthSpan(Expression):
3985    arg_types = {}
arg_types = {}
key = 'intervalyeartomonthspan'
class IntervalDayToSecondSpan(Expression):
3990class IntervalDayToSecondSpan(Expression):
3991    arg_types = {}
arg_types = {}
key = 'intervaldaytosecondspan'
class Interval(TimeUnit):
3994class Interval(TimeUnit):
3995    arg_types = {"this": False, "unit": False}
3996
3997    @property
3998    def unit(self) -> t.Optional[Var]:
3999        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
4002class IgnoreNulls(Expression):
4003    pass
key = 'ignorenulls'
class RespectNulls(Expression):
4006class RespectNulls(Expression):
4007    pass
key = 'respectnulls'
class Func(Condition):
4011class Func(Condition):
4012    """
4013    The base class for all function expressions.
4014
4015    Attributes:
4016        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
4017            treated as a variable length argument and the argument's value will be stored as a list.
4018        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
4019            for this function expression. These values are used to map this node to a name during parsing
4020            as well as to provide the function's name during SQL string generation. By default the SQL
4021            name is set to the expression's class name transformed to snake case.
4022    """
4023
4024    is_var_len_args = False
4025
4026    @classmethod
4027    def from_arg_list(cls, args):
4028        if cls.is_var_len_args:
4029            all_arg_keys = list(cls.arg_types)
4030            # If this function supports variable length argument treat the last argument as such.
4031            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4032            num_non_var = len(non_var_len_arg_keys)
4033
4034            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4035            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4036        else:
4037            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4038
4039        return cls(**args_dict)
4040
4041    @classmethod
4042    def sql_names(cls):
4043        if cls is Func:
4044            raise NotImplementedError(
4045                "SQL name is only supported by concrete function implementations"
4046            )
4047        if "_sql_names" not in cls.__dict__:
4048            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4049        return cls._sql_names
4050
4051    @classmethod
4052    def sql_name(cls):
4053        return cls.sql_names()[0]
4054
4055    @classmethod
4056    def default_parser_mappings(cls):
4057        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):
4026    @classmethod
4027    def from_arg_list(cls, args):
4028        if cls.is_var_len_args:
4029            all_arg_keys = list(cls.arg_types)
4030            # If this function supports variable length argument treat the last argument as such.
4031            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4032            num_non_var = len(non_var_len_arg_keys)
4033
4034            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4035            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4036        else:
4037            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4038
4039        return cls(**args_dict)
@classmethod
def sql_names(cls):
4041    @classmethod
4042    def sql_names(cls):
4043        if cls is Func:
4044            raise NotImplementedError(
4045                "SQL name is only supported by concrete function implementations"
4046            )
4047        if "_sql_names" not in cls.__dict__:
4048            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4049        return cls._sql_names
@classmethod
def sql_name(cls):
4051    @classmethod
4052    def sql_name(cls):
4053        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
4055    @classmethod
4056    def default_parser_mappings(cls):
4057        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
4060class AggFunc(Func):
4061    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
4064class ParameterizedAgg(AggFunc):
4065    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
4068class Abs(Func):
4069    pass
key = 'abs'
class Transform(Func):
4073class Transform(Func):
4074    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
4077class Anonymous(Func):
4078    arg_types = {"this": True, "expressions": False}
4079    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
4084class Hll(AggFunc):
4085    arg_types = {"this": True, "expressions": False}
4086    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
4089class ApproxDistinct(AggFunc):
4090    arg_types = {"this": True, "accuracy": False}
4091    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
4094class Array(Func):
4095    arg_types = {"expressions": False}
4096    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
4100class ToChar(Func):
4101    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
4104class GenerateSeries(Func):
4105    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
4108class ArrayAgg(AggFunc):
4109    pass
key = 'arrayagg'
class ArrayAll(Func):
4112class ArrayAll(Func):
4113    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4116class ArrayAny(Func):
4117    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4120class ArrayConcat(Func):
4121    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4122    arg_types = {"this": True, "expressions": False}
4123    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4126class ArrayContains(Binary, Func):
4127    pass
key = 'arraycontains'
class ArrayContained(Binary):
4130class ArrayContained(Binary):
4131    pass
key = 'arraycontained'
class ArrayFilter(Func):
4134class ArrayFilter(Func):
4135    arg_types = {"this": True, "expression": True}
4136    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4139class ArrayJoin(Func):
4140    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4143class ArraySize(Func):
4144    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4147class ArraySort(Func):
4148    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4151class ArraySum(Func):
4152    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4155class ArrayUnionAgg(AggFunc):
4156    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4159class Avg(AggFunc):
4160    pass
key = 'avg'
class AnyValue(AggFunc):
4163class AnyValue(AggFunc):
4164    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):
4167class First(Func):
4168    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4171class Last(Func):
4172    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4175class Case(Func):
4176    arg_types = {"this": False, "ifs": True, "default": False}
4177
4178    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4179        instance = maybe_copy(self, copy)
4180        instance.append(
4181            "ifs",
4182            If(
4183                this=maybe_parse(condition, copy=copy, **opts),
4184                true=maybe_parse(then, copy=copy, **opts),
4185            ),
4186        )
4187        return instance
4188
4189    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4190        instance = maybe_copy(self, copy)
4191        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4192        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:
4178    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4179        instance = maybe_copy(self, copy)
4180        instance.append(
4181            "ifs",
4182            If(
4183                this=maybe_parse(condition, copy=copy, **opts),
4184                true=maybe_parse(then, copy=copy, **opts),
4185            ),
4186        )
4187        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4189    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4190        instance = maybe_copy(self, copy)
4191        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4192        return instance
key = 'case'
class Cast(Func):
4195class Cast(Func):
4196    arg_types = {"this": True, "to": True, "format": False}
4197
4198    @property
4199    def name(self) -> str:
4200        return self.this.name
4201
4202    @property
4203    def to(self) -> DataType:
4204        return self.args["to"]
4205
4206    @property
4207    def output_name(self) -> str:
4208        return self.name
4209
4210    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4211        """
4212        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4213        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4214        array<int> != array<float>.
4215
4216        Args:
4217            dtypes: the data types to compare this Cast's DataType to.
4218
4219        Returns:
4220            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4221        """
4222        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:
4210    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4211        """
4212        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4213        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4214        array<int> != array<float>.
4215
4216        Args:
4217            dtypes: the data types to compare this Cast's DataType to.
4218
4219        Returns:
4220            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4221        """
4222        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):
4225class TryCast(Cast):
4226    pass
key = 'trycast'
class CastToStrType(Func):
4229class CastToStrType(Func):
4230    arg_types = {"this": True, "to": True}
arg_types = {'this': True, 'to': True}
key = 'casttostrtype'
class Collate(Binary):
4233class Collate(Binary):
4234    pass
key = 'collate'
class Ceil(Func):
4237class Ceil(Func):
4238    arg_types = {"this": True, "decimals": False}
4239    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4242class Coalesce(Func):
4243    arg_types = {"this": True, "expressions": False}
4244    is_var_len_args = True
4245    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4248class Concat(Func):
4249    arg_types = {"expressions": True}
4250    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4253class SafeConcat(Concat):
4254    pass
key = 'safeconcat'
class ConcatWs(Concat):
4257class ConcatWs(Concat):
4258    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4261class Count(AggFunc):
4262    arg_types = {"this": False, "expressions": False}
4263    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4266class CountIf(AggFunc):
4267    pass
key = 'countif'
class CurrentDate(Func):
4270class CurrentDate(Func):
4271    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4274class CurrentDatetime(Func):
4275    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4278class CurrentTime(Func):
4279    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4282class CurrentTimestamp(Func):
4283    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4286class CurrentUser(Func):
4287    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4290class DateAdd(Func, TimeUnit):
4291    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4294class DateSub(Func, TimeUnit):
4295    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4298class DateDiff(Func, TimeUnit):
4299    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4300    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4303class DateTrunc(Func):
4304    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4307class DatetimeAdd(Func, TimeUnit):
4308    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4311class DatetimeSub(Func, TimeUnit):
4312    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4315class DatetimeDiff(Func, TimeUnit):
4316    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4319class DatetimeTrunc(Func, TimeUnit):
4320    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4323class DayOfWeek(Func):
4324    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4327class DayOfMonth(Func):
4328    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4331class DayOfYear(Func):
4332    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4335class WeekOfYear(Func):
4336    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4339class MonthsBetween(Func):
4340    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4343class LastDateOfMonth(Func):
4344    pass
key = 'lastdateofmonth'
class Extract(Func):
4347class Extract(Func):
4348    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4351class TimestampAdd(Func, TimeUnit):
4352    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4355class TimestampSub(Func, TimeUnit):
4356    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4359class TimestampDiff(Func, TimeUnit):
4360    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4363class TimestampTrunc(Func, TimeUnit):
4364    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4367class TimeAdd(Func, TimeUnit):
4368    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4371class TimeSub(Func, TimeUnit):
4372    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4375class TimeDiff(Func, TimeUnit):
4376    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4379class TimeTrunc(Func, TimeUnit):
4380    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4383class DateFromParts(Func):
4384    _sql_names = ["DATEFROMPARTS"]
4385    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4388class DateStrToDate(Func):
4389    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4392class DateToDateStr(Func):
4393    pass
key = 'datetodatestr'
class DateToDi(Func):
4396class DateToDi(Func):
4397    pass
key = 'datetodi'
class Date(Func):
4401class Date(Func):
4402    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4405class Day(Func):
4406    pass
key = 'day'
class Decode(Func):
4409class Decode(Func):
4410    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4413class DiToDate(Func):
4414    pass
key = 'ditodate'
class Encode(Func):
4417class Encode(Func):
4418    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4421class Exp(Func):
4422    pass
key = 'exp'
class Explode(Func):
4425class Explode(Func):
4426    pass
key = 'explode'
class Floor(Func):
4429class Floor(Func):
4430    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4433class FromBase64(Func):
4434    pass
key = 'frombase64'
class ToBase64(Func):
4437class ToBase64(Func):
4438    pass
key = 'tobase64'
class Greatest(Func):
4441class Greatest(Func):
4442    arg_types = {"this": True, "expressions": False}
4443    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4446class GroupConcat(Func):
4447    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4450class Hex(Func):
4451    pass
key = 'hex'
class Xor(Connector, Func):
4454class Xor(Connector, Func):
4455    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4458class If(Func):
4459    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4462class Initcap(Func):
4463    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4466class IsNan(Func):
4467    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class JSONKeyValue(Expression):
4470class JSONKeyValue(Expression):
4471    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4474class JSONObject(Func):
4475    arg_types = {
4476        "expressions": False,
4477        "null_handling": False,
4478        "unique_keys": False,
4479        "return_type": False,
4480        "format_json": False,
4481        "encoding": False,
4482    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4485class OpenJSONColumnDef(Expression):
4486    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):
4489class OpenJSON(Func):
4490    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4493class JSONBContains(Binary):
4494    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4497class JSONExtract(Binary, Func):
4498    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4501class JSONExtractScalar(JSONExtract):
4502    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4505class JSONBExtract(JSONExtract):
4506    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4509class JSONBExtractScalar(JSONExtract):
4510    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4513class JSONFormat(Func):
4514    arg_types = {"this": False, "options": False}
4515    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4519class JSONArrayContains(Binary, Predicate, Func):
4520    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4523class Least(Func):
4524    arg_types = {"this": True, "expressions": False}
4525    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4528class Left(Func):
4529    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4536class Length(Func):
4537    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4540class Levenshtein(Func):
4541    arg_types = {
4542        "this": True,
4543        "expression": False,
4544        "ins_cost": False,
4545        "del_cost": False,
4546        "sub_cost": False,
4547    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4550class Ln(Func):
4551    pass
key = 'ln'
class Log(Func):
4554class Log(Func):
4555    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4558class Log2(Func):
4559    pass
key = 'log2'
class Log10(Func):
4562class Log10(Func):
4563    pass
key = 'log10'
class LogicalOr(AggFunc):
4566class LogicalOr(AggFunc):
4567    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4570class LogicalAnd(AggFunc):
4571    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4574class Lower(Func):
4575    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4578class Map(Func):
4579    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4582class MapFromEntries(Func):
4583    pass
key = 'mapfromentries'
class StarMap(Func):
4586class StarMap(Func):
4587    pass
key = 'starmap'
class VarMap(Func):
4590class VarMap(Func):
4591    arg_types = {"keys": True, "values": True}
4592    is_var_len_args = True
4593
4594    @property
4595    def keys(self) -> t.List[Expression]:
4596        return self.args["keys"].expressions
4597
4598    @property
4599    def values(self) -> t.List[Expression]:
4600        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4604class MatchAgainst(Func):
4605    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4608class Max(AggFunc):
4609    arg_types = {"this": True, "expressions": False}
4610    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4613class MD5(Func):
4614    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4618class MD5Digest(Func):
4619    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4622class Min(AggFunc):
4623    arg_types = {"this": True, "expressions": False}
4624    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4627class Month(Func):
4628    pass
key = 'month'
class Nvl2(Func):
4631class Nvl2(Func):
4632    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4635class Posexplode(Func):
4636    pass
key = 'posexplode'
class Pow(Binary, Func):
4639class Pow(Binary, Func):
4640    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4643class PercentileCont(AggFunc):
4644    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4647class PercentileDisc(AggFunc):
4648    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4651class Quantile(AggFunc):
4652    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4655class ApproxQuantile(Quantile):
4656    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):
4659class RangeN(Func):
4660    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4663class ReadCSV(Func):
4664    _sql_names = ["READ_CSV"]
4665    is_var_len_args = True
4666    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4669class Reduce(Func):
4670    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):
4673class RegexpExtract(Func):
4674    arg_types = {
4675        "this": True,
4676        "expression": True,
4677        "position": False,
4678        "occurrence": False,
4679        "parameters": False,
4680        "group": False,
4681    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4684class RegexpReplace(Func):
4685    arg_types = {
4686        "this": True,
4687        "expression": True,
4688        "replacement": True,
4689        "position": False,
4690        "occurrence": False,
4691        "parameters": False,
4692    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4695class RegexpLike(Binary, Func):
4696    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4699class RegexpILike(Func):
4700    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4705class RegexpSplit(Func):
4706    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4709class Repeat(Func):
4710    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4713class Round(Func):
4714    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4717class RowNumber(Func):
4718    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4721class SafeDivide(Func):
4722    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4725class SetAgg(AggFunc):
4726    pass
key = 'setagg'
class SHA(Func):
4729class SHA(Func):
4730    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4733class SHA2(Func):
4734    _sql_names = ["SHA2"]
4735    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4738class SortArray(Func):
4739    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4742class Split(Func):
4743    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4748class Substring(Func):
4749    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4752class StandardHash(Func):
4753    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4756class StartsWith(Func):
4757    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4758    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4761class StrPosition(Func):
4762    arg_types = {
4763        "this": True,
4764        "substr": True,
4765        "position": False,
4766        "instance": False,
4767    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4770class StrToDate(Func):
4771    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4774class StrToTime(Func):
4775    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4780class StrToUnix(Func):
4781    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
4786class StrToMap(Func):
4787    arg_types = {
4788        "this": True,
4789        "pair_delim": False,
4790        "key_value_delim": False,
4791        "duplicate_resolution_callback": False,
4792    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
4795class NumberToStr(Func):
4796    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
4799class FromBase(Func):
4800    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4803class Struct(Func):
4804    arg_types = {"expressions": True}
4805    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4808class StructExtract(Func):
4809    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Stuff(Func):
4814class Stuff(Func):
4815    _sql_names = ["STUFF", "INSERT"]
4816    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):
4819class Sum(AggFunc):
4820    pass
key = 'sum'
class Sqrt(Func):
4823class Sqrt(Func):
4824    pass
key = 'sqrt'
class Stddev(AggFunc):
4827class Stddev(AggFunc):
4828    pass
key = 'stddev'
class StddevPop(AggFunc):
4831class StddevPop(AggFunc):
4832    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4835class StddevSamp(AggFunc):
4836    pass
key = 'stddevsamp'
class TimeToStr(Func):
4839class TimeToStr(Func):
4840    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
4843class TimeToTimeStr(Func):
4844    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4847class TimeToUnix(Func):
4848    pass
key = 'timetounix'
class TimeStrToDate(Func):
4851class TimeStrToDate(Func):
4852    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4855class TimeStrToTime(Func):
4856    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4859class TimeStrToUnix(Func):
4860    pass
key = 'timestrtounix'
class Trim(Func):
4863class Trim(Func):
4864    arg_types = {
4865        "this": True,
4866        "expression": False,
4867        "position": False,
4868        "collation": False,
4869    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4872class TsOrDsAdd(Func, TimeUnit):
4873    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4876class TsOrDsToDateStr(Func):
4877    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4880class TsOrDsToDate(Func):
4881    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4884class TsOrDiToDi(Func):
4885    pass
key = 'tsorditodi'
class Unhex(Func):
4888class Unhex(Func):
4889    pass
key = 'unhex'
class UnixToStr(Func):
4892class UnixToStr(Func):
4893    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4898class UnixToTime(Func):
4899    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4900
4901    SECONDS = Literal.string("seconds")
4902    MILLIS = Literal.string("millis")
4903    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):
4906class UnixToTimeStr(Func):
4907    pass
key = 'unixtotimestr'
class Upper(Func):
4910class Upper(Func):
4911    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4914class Variance(AggFunc):
4915    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4918class VariancePop(AggFunc):
4919    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4922class Week(Func):
4923    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4926class XMLTable(Func):
4927    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):
4930class Year(Func):
4931    pass
key = 'year'
class Use(Expression):
4934class Use(Expression):
4935    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4938class Merge(Expression):
4939    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):
4942class When(Func):
4943    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):
4948class NextValueFor(Func):
4949    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:
4986def maybe_parse(
4987    sql_or_expression: ExpOrStr,
4988    *,
4989    into: t.Optional[IntoType] = None,
4990    dialect: DialectType = None,
4991    prefix: t.Optional[str] = None,
4992    copy: bool = False,
4993    **opts,
4994) -> Expression:
4995    """Gracefully handle a possible string or expression.
4996
4997    Example:
4998        >>> maybe_parse("1")
4999        (LITERAL this: 1, is_string: False)
5000        >>> maybe_parse(to_identifier("x"))
5001        (IDENTIFIER this: x, quoted: False)
5002
5003    Args:
5004        sql_or_expression: the SQL code string or an expression
5005        into: the SQLGlot Expression to parse into
5006        dialect: the dialect used to parse the input expressions (in the case that an
5007            input expression is a SQL string).
5008        prefix: a string to prefix the sql with before it gets parsed
5009            (automatically includes a space)
5010        copy: whether or not to copy the expression.
5011        **opts: other options to use to parse the input expressions (again, in the case
5012            that an input expression is a SQL string).
5013
5014    Returns:
5015        Expression: the parsed or given expression.
5016    """
5017    if isinstance(sql_or_expression, Expression):
5018        if copy:
5019            return sql_or_expression.copy()
5020        return sql_or_expression
5021
5022    if sql_or_expression is None:
5023        raise ParseError(f"SQL cannot be None")
5024
5025    import sqlglot
5026
5027    sql = str(sql_or_expression)
5028    if prefix:
5029        sql = f"{prefix} {sql}"
5030
5031    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):
5044def maybe_copy(instance, copy=True):
5045    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:
5225def union(
5226    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5227) -> Union:
5228    """
5229    Initializes a syntax tree from one UNION expression.
5230
5231    Example:
5232        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5233        'SELECT * FROM foo UNION SELECT * FROM bla'
5234
5235    Args:
5236        left: the SQL code string corresponding to the left-hand side.
5237            If an `Expression` instance is passed, it will be used as-is.
5238        right: the SQL code string corresponding to the right-hand side.
5239            If an `Expression` instance is passed, it will be used as-is.
5240        distinct: set the DISTINCT flag if and only if this is true.
5241        dialect: the dialect used to parse the input expression.
5242        opts: other options to use to parse the input expressions.
5243
5244    Returns:
5245        The new Union instance.
5246    """
5247    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5248    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5249
5250    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:
5253def intersect(
5254    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5255) -> Intersect:
5256    """
5257    Initializes a syntax tree from one INTERSECT expression.
5258
5259    Example:
5260        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5261        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5262
5263    Args:
5264        left: the SQL code string corresponding to the left-hand side.
5265            If an `Expression` instance is passed, it will be used as-is.
5266        right: the SQL code string corresponding to the right-hand side.
5267            If an `Expression` instance is passed, it will be used as-is.
5268        distinct: set the DISTINCT flag if and only if this is true.
5269        dialect: the dialect used to parse the input expression.
5270        opts: other options to use to parse the input expressions.
5271
5272    Returns:
5273        The new Intersect instance.
5274    """
5275    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5276    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5277
5278    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:
5281def except_(
5282    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5283) -> Except:
5284    """
5285    Initializes a syntax tree from one EXCEPT expression.
5286
5287    Example:
5288        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5289        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5290
5291    Args:
5292        left: the SQL code string corresponding to the left-hand side.
5293            If an `Expression` instance is passed, it will be used as-is.
5294        right: the SQL code string corresponding to the right-hand side.
5295            If an `Expression` instance is passed, it will be used as-is.
5296        distinct: set the DISTINCT flag if and only if this is true.
5297        dialect: the dialect used to parse the input expression.
5298        opts: other options to use to parse the input expressions.
5299
5300    Returns:
5301        The new Except instance.
5302    """
5303    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5304    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5305
5306    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:
5309def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5310    """
5311    Initializes a syntax tree from one or multiple SELECT expressions.
5312
5313    Example:
5314        >>> select("col1", "col2").from_("tbl").sql()
5315        'SELECT col1, col2 FROM tbl'
5316
5317    Args:
5318        *expressions: the SQL code string to parse as the expressions of a
5319            SELECT statement. If an Expression instance is passed, this is used as-is.
5320        dialect: the dialect used to parse the input expressions (in the case that an
5321            input expression is a SQL string).
5322        **opts: other options to use to parse the input expressions (again, in the case
5323            that an input expression is a SQL string).
5324
5325    Returns:
5326        Select: the syntax tree for the SELECT statement.
5327    """
5328    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:
5331def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5332    """
5333    Initializes a syntax tree from a FROM expression.
5334
5335    Example:
5336        >>> from_("tbl").select("col1", "col2").sql()
5337        'SELECT col1, col2 FROM tbl'
5338
5339    Args:
5340        *expression: the SQL code string to parse as the FROM expressions of a
5341            SELECT statement. If an Expression instance is passed, this is used as-is.
5342        dialect: the dialect used to parse the input expression (in the case that the
5343            input expression is a SQL string).
5344        **opts: other options to use to parse the input expressions (again, in the case
5345            that the input expression is a SQL string).
5346
5347    Returns:
5348        Select: the syntax tree for the SELECT statement.
5349    """
5350    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:
5353def update(
5354    table: str | Table,
5355    properties: dict,
5356    where: t.Optional[ExpOrStr] = None,
5357    from_: t.Optional[ExpOrStr] = None,
5358    dialect: DialectType = None,
5359    **opts,
5360) -> Update:
5361    """
5362    Creates an update statement.
5363
5364    Example:
5365        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5366        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5367
5368    Args:
5369        *properties: dictionary of properties to set which are
5370            auto converted to sql objects eg None -> NULL
5371        where: sql conditional parsed into a WHERE statement
5372        from_: sql statement parsed into a FROM statement
5373        dialect: the dialect used to parse the input expressions.
5374        **opts: other options to use to parse the input expressions.
5375
5376    Returns:
5377        Update: the syntax tree for the UPDATE statement.
5378    """
5379    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5380    update_expr.set(
5381        "expressions",
5382        [
5383            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5384            for k, v in properties.items()
5385        ],
5386    )
5387    if from_:
5388        update_expr.set(
5389            "from",
5390            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5391        )
5392    if isinstance(where, Condition):
5393        where = Where(this=where)
5394    if where:
5395        update_expr.set(
5396            "where",
5397            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5398        )
5399    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:
5402def delete(
5403    table: ExpOrStr,
5404    where: t.Optional[ExpOrStr] = None,
5405    returning: t.Optional[ExpOrStr] = None,
5406    dialect: DialectType = None,
5407    **opts,
5408) -> Delete:
5409    """
5410    Builds a delete statement.
5411
5412    Example:
5413        >>> delete("my_table", where="id > 1").sql()
5414        'DELETE FROM my_table WHERE id > 1'
5415
5416    Args:
5417        where: sql conditional parsed into a WHERE statement
5418        returning: sql conditional parsed into a RETURNING statement
5419        dialect: the dialect used to parse the input expressions.
5420        **opts: other options to use to parse the input expressions.
5421
5422    Returns:
5423        Delete: the syntax tree for the DELETE statement.
5424    """
5425    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5426    if where:
5427        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5428    if returning:
5429        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5430    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:
5433def insert(
5434    expression: ExpOrStr,
5435    into: ExpOrStr,
5436    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5437    overwrite: t.Optional[bool] = None,
5438    dialect: DialectType = None,
5439    copy: bool = True,
5440    **opts,
5441) -> Insert:
5442    """
5443    Builds an INSERT statement.
5444
5445    Example:
5446        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5447        'INSERT INTO tbl VALUES (1, 2, 3)'
5448
5449    Args:
5450        expression: the sql string or expression of the INSERT statement
5451        into: the tbl to insert data to.
5452        columns: optionally the table's column names.
5453        overwrite: whether to INSERT OVERWRITE or not.
5454        dialect: the dialect used to parse the input expressions.
5455        copy: whether or not to copy the expression.
5456        **opts: other options to use to parse the input expressions.
5457
5458    Returns:
5459        Insert: the syntax tree for the INSERT statement.
5460    """
5461    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5462    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5463
5464    if columns:
5465        this = _apply_list_builder(
5466            *columns,
5467            instance=Schema(this=this),
5468            arg="expressions",
5469            into=Identifier,
5470            copy=False,
5471            dialect=dialect,
5472            **opts,
5473        )
5474
5475    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:
5478def condition(
5479    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5480) -> Condition:
5481    """
5482    Initialize a logical condition expression.
5483
5484    Example:
5485        >>> condition("x=1").sql()
5486        'x = 1'
5487
5488        This is helpful for composing larger logical syntax trees:
5489        >>> where = condition("x=1")
5490        >>> where = where.and_("y=1")
5491        >>> Select().from_("tbl").select("*").where(where).sql()
5492        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5493
5494    Args:
5495        *expression: the SQL code string to parse.
5496            If an Expression instance is passed, this is used as-is.
5497        dialect: the dialect used to parse the input expression (in the case that the
5498            input expression is a SQL string).
5499        copy: Whether or not to copy `expression` (only applies to expressions).
5500        **opts: other options to use to parse the input expressions (again, in the case
5501            that the input expression is a SQL string).
5502
5503    Returns:
5504        The new Condition instance
5505    """
5506    return maybe_parse(
5507        expression,
5508        into=Condition,
5509        dialect=dialect,
5510        copy=copy,
5511        **opts,
5512    )

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:
5515def and_(
5516    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5517) -> Condition:
5518    """
5519    Combine multiple conditions with an AND logical operator.
5520
5521    Example:
5522        >>> and_("x=1", and_("y=1", "z=1")).sql()
5523        'x = 1 AND (y = 1 AND z = 1)'
5524
5525    Args:
5526        *expressions: the SQL code strings to parse.
5527            If an Expression instance is passed, this is used as-is.
5528        dialect: the dialect used to parse the input expression.
5529        copy: whether or not to copy `expressions` (only applies to Expressions).
5530        **opts: other options to use to parse the input expressions.
5531
5532    Returns:
5533        And: the new condition
5534    """
5535    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:
5538def or_(
5539    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5540) -> Condition:
5541    """
5542    Combine multiple conditions with an OR logical operator.
5543
5544    Example:
5545        >>> or_("x=1", or_("y=1", "z=1")).sql()
5546        'x = 1 OR (y = 1 OR z = 1)'
5547
5548    Args:
5549        *expressions: the SQL code strings to parse.
5550            If an Expression instance is passed, this is used as-is.
5551        dialect: the dialect used to parse the input expression.
5552        copy: whether or not to copy `expressions` (only applies to Expressions).
5553        **opts: other options to use to parse the input expressions.
5554
5555    Returns:
5556        Or: the new condition
5557    """
5558    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:
5561def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5562    """
5563    Wrap a condition with a NOT operator.
5564
5565    Example:
5566        >>> not_("this_suit='black'").sql()
5567        "NOT this_suit = 'black'"
5568
5569    Args:
5570        expression: the SQL code string to parse.
5571            If an Expression instance is passed, this is used as-is.
5572        dialect: the dialect used to parse the input expression.
5573        copy: whether to copy the expression or not.
5574        **opts: other options to use to parse the input expressions.
5575
5576    Returns:
5577        The new condition.
5578    """
5579    this = condition(
5580        expression,
5581        dialect=dialect,
5582        copy=copy,
5583        **opts,
5584    )
5585    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:
5588def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5589    """
5590    Wrap an expression in parentheses.
5591
5592    Example:
5593        >>> paren("5 + 3").sql()
5594        '(5 + 3)'
5595
5596    Args:
5597        expression: the SQL code string to parse.
5598            If an Expression instance is passed, this is used as-is.
5599        copy: whether to copy the expression or not.
5600
5601    Returns:
5602        The wrapped expression.
5603    """
5604    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):
5622def to_identifier(name, quoted=None, copy=True):
5623    """Builds an identifier.
5624
5625    Args:
5626        name: The name to turn into an identifier.
5627        quoted: Whether or not force quote the identifier.
5628        copy: Whether or not to copy a passed in Identefier node.
5629
5630    Returns:
5631        The identifier ast node.
5632    """
5633
5634    if name is None:
5635        return None
5636
5637    if isinstance(name, Identifier):
5638        identifier = maybe_copy(name, copy)
5639    elif isinstance(name, str):
5640        identifier = Identifier(
5641            this=name,
5642            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5643        )
5644    else:
5645        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5646    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:
5652def to_interval(interval: str | Literal) -> Interval:
5653    """Builds an interval expression from a string like '1 day' or '5 months'."""
5654    if isinstance(interval, Literal):
5655        if not interval.is_string:
5656            raise ValueError("Invalid interval string.")
5657
5658        interval = interval.this
5659
5660    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5661
5662    if not interval_parts:
5663        raise ValueError("Invalid interval string.")
5664
5665    return Interval(
5666        this=Literal.string(interval_parts.group(1)),
5667        unit=Var(this=interval_parts.group(2)),
5668    )

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

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

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

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

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

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

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

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
6233def false() -> Boolean:
6234    """
6235    Returns a false Boolean expression.
6236    """
6237    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6240def null() -> Null:
6241    """
6242    Returns a Null expression.
6243    """
6244    return Null()

Returns a Null expression.

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