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

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1174class ColumnPosition(Expression):
1175    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
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 []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
key = 'columndef'
class AlterColumn(Expression):
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    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1203class RenameTable(Expression):
1204    pass
key = 'renametable'
class Comment(Expression):
1207class Comment(Expression):
1208    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
arg_types = {'this': True, 'kind': True, 'expression': True, 'exists': False}
key = 'comment'
class MergeTreeTTLAction(Expression):
1212class MergeTreeTTLAction(Expression):
1213    arg_types = {
1214        "this": True,
1215        "delete": False,
1216        "recompress": False,
1217        "to_disk": False,
1218        "to_volume": False,
1219    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1223class MergeTreeTTL(Expression):
1224    arg_types = {
1225        "expressions": True,
1226        "where": False,
1227        "group": False,
1228        "aggregates": False,
1229    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class IndexConstraintOption(Expression):
1233class IndexConstraintOption(Expression):
1234    arg_types = {
1235        "key_block_size": False,
1236        "using": False,
1237        "parser": False,
1238        "comment": False,
1239        "visible": False,
1240        "engine_attr": False,
1241        "secondary_engine_attr": False,
1242    }
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):
1245class ColumnConstraint(Expression):
1246    arg_types = {"this": False, "kind": True}
1247
1248    @property
1249    def kind(self) -> ColumnConstraintKind:
1250        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1253class ColumnConstraintKind(Expression):
1254    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1257class AutoIncrementColumnConstraint(ColumnConstraintKind):
1258    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1261class CaseSpecificColumnConstraint(ColumnConstraintKind):
1262    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1265class CharacterSetColumnConstraint(ColumnConstraintKind):
1266    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1269class CheckColumnConstraint(ColumnConstraintKind):
1270    pass
key = 'checkcolumnconstraint'
class ClusteredColumnConstraint(ColumnConstraintKind):
1273class ClusteredColumnConstraint(ColumnConstraintKind):
1274    pass
key = 'clusteredcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1277class CollateColumnConstraint(ColumnConstraintKind):
1278    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1281class CommentColumnConstraint(ColumnConstraintKind):
1282    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1285class CompressColumnConstraint(ColumnConstraintKind):
1286    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1289class DateFormatColumnConstraint(ColumnConstraintKind):
1290    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1293class DefaultColumnConstraint(ColumnConstraintKind):
1294    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1297class EncodeColumnConstraint(ColumnConstraintKind):
1298    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1301class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1302    # this: True -> ALWAYS, this: False -> BY DEFAULT
1303    arg_types = {
1304        "this": False,
1305        "expression": False,
1306        "on_null": False,
1307        "start": False,
1308        "increment": False,
1309        "minvalue": False,
1310        "maxvalue": False,
1311        "cycle": False,
1312    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class IndexColumnConstraint(ColumnConstraintKind):
1316class IndexColumnConstraint(ColumnConstraintKind):
1317    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):
1320class InlineLengthColumnConstraint(ColumnConstraintKind):
1321    pass
key = 'inlinelengthcolumnconstraint'
class NotForReplicationColumnConstraint(ColumnConstraintKind):
1324class NotForReplicationColumnConstraint(ColumnConstraintKind):
1325    arg_types = {}
arg_types = {}
key = 'notforreplicationcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1328class NotNullColumnConstraint(ColumnConstraintKind):
1329    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1333class OnUpdateColumnConstraint(ColumnConstraintKind):
1334    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1337class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1338    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1341class TitleColumnConstraint(ColumnConstraintKind):
1342    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1345class UniqueColumnConstraint(ColumnConstraintKind):
1346    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1349class UppercaseColumnConstraint(ColumnConstraintKind):
1350    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1353class PathColumnConstraint(ColumnConstraintKind):
1354    pass
key = 'pathcolumnconstraint'
class ComputedColumnConstraint(ColumnConstraintKind):
1359class ComputedColumnConstraint(ColumnConstraintKind):
1360    arg_types = {"this": True, "persisted": False, "not_null": False}
arg_types = {'this': True, 'persisted': False, 'not_null': False}
key = 'computedcolumnconstraint'
class Constraint(Expression):
1363class Constraint(Expression):
1364    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1367class Delete(Expression):
1368    arg_types = {
1369        "with": False,
1370        "this": False,
1371        "using": False,
1372        "where": False,
1373        "returning": False,
1374        "limit": False,
1375        "tables": False,  # Multiple-Table Syntax (MySQL)
1376    }
1377
1378    def delete(
1379        self,
1380        table: ExpOrStr,
1381        dialect: DialectType = None,
1382        copy: bool = True,
1383        **opts,
1384    ) -> Delete:
1385        """
1386        Create a DELETE expression or replace the table on an existing DELETE expression.
1387
1388        Example:
1389            >>> delete("tbl").sql()
1390            'DELETE FROM tbl'
1391
1392        Args:
1393            table: the table from which to delete.
1394            dialect: the dialect used to parse the input expression.
1395            copy: if `False`, modify this expression instance in-place.
1396            opts: other options to use to parse the input expressions.
1397
1398        Returns:
1399            Delete: the modified expression.
1400        """
1401        return _apply_builder(
1402            expression=table,
1403            instance=self,
1404            arg="this",
1405            dialect=dialect,
1406            into=Table,
1407            copy=copy,
1408            **opts,
1409        )
1410
1411    def where(
1412        self,
1413        *expressions: t.Optional[ExpOrStr],
1414        append: bool = True,
1415        dialect: DialectType = None,
1416        copy: bool = True,
1417        **opts,
1418    ) -> Delete:
1419        """
1420        Append to or set the WHERE expressions.
1421
1422        Example:
1423            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1424            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1425
1426        Args:
1427            *expressions: the SQL code strings to parse.
1428                If an `Expression` instance is passed, it will be used as-is.
1429                Multiple expressions are combined with an AND operator.
1430            append: if `True`, AND the new expressions to any existing expression.
1431                Otherwise, this resets the expression.
1432            dialect: the dialect used to parse the input expressions.
1433            copy: if `False`, modify this expression instance in-place.
1434            opts: other options to use to parse the input expressions.
1435
1436        Returns:
1437            Delete: the modified expression.
1438        """
1439        return _apply_conjunction_builder(
1440            *expressions,
1441            instance=self,
1442            arg="where",
1443            append=append,
1444            into=Where,
1445            dialect=dialect,
1446            copy=copy,
1447            **opts,
1448        )
1449
1450    def returning(
1451        self,
1452        expression: ExpOrStr,
1453        dialect: DialectType = None,
1454        copy: bool = True,
1455        **opts,
1456    ) -> Delete:
1457        """
1458        Set the RETURNING expression. Not supported by all dialects.
1459
1460        Example:
1461            >>> delete("tbl").returning("*", dialect="postgres").sql()
1462            'DELETE FROM tbl RETURNING *'
1463
1464        Args:
1465            expression: the SQL code strings to parse.
1466                If an `Expression` instance is passed, it will be used as-is.
1467            dialect: the dialect used to parse the input expressions.
1468            copy: if `False`, modify this expression instance in-place.
1469            opts: other options to use to parse the input expressions.
1470
1471        Returns:
1472            Delete: the modified expression.
1473        """
1474        return _apply_builder(
1475            expression=expression,
1476            instance=self,
1477            arg="returning",
1478            prefix="RETURNING",
1479            dialect=dialect,
1480            copy=copy,
1481            into=Returning,
1482            **opts,
1483        )
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:
1378    def delete(
1379        self,
1380        table: ExpOrStr,
1381        dialect: DialectType = None,
1382        copy: bool = True,
1383        **opts,
1384    ) -> Delete:
1385        """
1386        Create a DELETE expression or replace the table on an existing DELETE expression.
1387
1388        Example:
1389            >>> delete("tbl").sql()
1390            'DELETE FROM tbl'
1391
1392        Args:
1393            table: the table from which to delete.
1394            dialect: the dialect used to parse the input expression.
1395            copy: if `False`, modify this expression instance in-place.
1396            opts: other options to use to parse the input expressions.
1397
1398        Returns:
1399            Delete: the modified expression.
1400        """
1401        return _apply_builder(
1402            expression=table,
1403            instance=self,
1404            arg="this",
1405            dialect=dialect,
1406            into=Table,
1407            copy=copy,
1408            **opts,
1409        )

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

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

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):
1486class Drop(Expression):
1487    arg_types = {
1488        "this": False,
1489        "kind": False,
1490        "exists": False,
1491        "temporary": False,
1492        "materialized": False,
1493        "cascade": False,
1494        "constraints": False,
1495        "purge": False,
1496    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1499class Filter(Expression):
1500    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1503class Check(Expression):
1504    pass
key = 'check'
class Directory(Expression):
1507class Directory(Expression):
1508    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1509    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1512class ForeignKey(Expression):
1513    arg_types = {
1514        "expressions": True,
1515        "reference": False,
1516        "delete": False,
1517        "update": False,
1518    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1521class PrimaryKey(Expression):
1522    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1527class Into(Expression):
1528    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1531class From(Expression):
1532    @property
1533    def name(self) -> str:
1534        return self.this.name
1535
1536    @property
1537    def alias_or_name(self) -> str:
1538        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1541class Having(Expression):
1542    pass
key = 'having'
class Hint(Expression):
1545class Hint(Expression):
1546    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1549class JoinHint(Expression):
1550    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1553class Identifier(Expression):
1554    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1555
1556    @property
1557    def quoted(self) -> bool:
1558        return bool(self.args.get("quoted"))
1559
1560    @property
1561    def hashable_args(self) -> t.Any:
1562        return (self.this, self.quoted)
1563
1564    @property
1565    def output_name(self) -> str:
1566        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):
1569class Index(Expression):
1570    arg_types = {
1571        "this": False,
1572        "table": False,
1573        "using": False,
1574        "where": False,
1575        "columns": False,
1576        "unique": False,
1577        "primary": False,
1578        "amp": False,  # teradata
1579        "partition_by": False,  # teradata
1580    }
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):
1583class Insert(DDL):
1584    arg_types = {
1585        "with": False,
1586        "this": True,
1587        "expression": False,
1588        "conflict": False,
1589        "returning": False,
1590        "overwrite": False,
1591        "exists": False,
1592        "partition": False,
1593        "alternative": False,
1594        "where": False,
1595        "ignore": False,
1596    }
1597
1598    def with_(
1599        self,
1600        alias: ExpOrStr,
1601        as_: ExpOrStr,
1602        recursive: t.Optional[bool] = None,
1603        append: bool = True,
1604        dialect: DialectType = None,
1605        copy: bool = True,
1606        **opts,
1607    ) -> Insert:
1608        """
1609        Append to or set the common table expressions.
1610
1611        Example:
1612            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1613            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1614
1615        Args:
1616            alias: the SQL code string to parse as the table name.
1617                If an `Expression` instance is passed, this is used as-is.
1618            as_: the SQL code string to parse as the table expression.
1619                If an `Expression` instance is passed, it will be used as-is.
1620            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1621            append: if `True`, add to any existing expressions.
1622                Otherwise, this resets the expressions.
1623            dialect: the dialect used to parse the input expression.
1624            copy: if `False`, modify this expression instance in-place.
1625            opts: other options to use to parse the input expressions.
1626
1627        Returns:
1628            The modified expression.
1629        """
1630        return _apply_cte_builder(
1631            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1632        )
arg_types = {'with': False, 'this': True, 'expression': False, 'conflict': False, 'returning': False, 'overwrite': False, 'exists': False, 'partition': False, 'alternative': False, 'where': False, 'ignore': False}
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Insert:
1598    def with_(
1599        self,
1600        alias: ExpOrStr,
1601        as_: ExpOrStr,
1602        recursive: t.Optional[bool] = None,
1603        append: bool = True,
1604        dialect: DialectType = None,
1605        copy: bool = True,
1606        **opts,
1607    ) -> Insert:
1608        """
1609        Append to or set the common table expressions.
1610
1611        Example:
1612            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1613            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1614
1615        Args:
1616            alias: the SQL code string to parse as the table name.
1617                If an `Expression` instance is passed, this is used as-is.
1618            as_: the SQL code string to parse as the table expression.
1619                If an `Expression` instance is passed, it will be used as-is.
1620            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1621            append: if `True`, add to any existing expressions.
1622                Otherwise, this resets the expressions.
1623            dialect: the dialect used to parse the input expression.
1624            copy: if `False`, modify this expression instance in-place.
1625            opts: other options to use to parse the input expressions.
1626
1627        Returns:
1628            The modified expression.
1629        """
1630        return _apply_cte_builder(
1631            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1632        )

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):
1635class OnConflict(Expression):
1636    arg_types = {
1637        "duplicate": False,
1638        "expressions": False,
1639        "nothing": False,
1640        "key": False,
1641        "constraint": False,
1642    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1645class Returning(Expression):
1646    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1650class Introducer(Expression):
1651    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1655class National(Expression):
1656    pass
key = 'national'
class LoadData(Expression):
1659class LoadData(Expression):
1660    arg_types = {
1661        "this": True,
1662        "local": False,
1663        "overwrite": False,
1664        "inpath": True,
1665        "partition": False,
1666        "input_format": False,
1667        "serde": False,
1668    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1671class Partition(Expression):
1672    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1675class Fetch(Expression):
1676    arg_types = {
1677        "direction": False,
1678        "count": False,
1679        "percent": False,
1680        "with_ties": False,
1681    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1684class Group(Expression):
1685    arg_types = {
1686        "expressions": False,
1687        "grouping_sets": False,
1688        "cube": False,
1689        "rollup": False,
1690        "totals": False,
1691        "all": False,
1692    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1695class Lambda(Expression):
1696    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1699class Limit(Expression):
1700    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1703class Literal(Condition):
1704    arg_types = {"this": True, "is_string": True}
1705
1706    @property
1707    def hashable_args(self) -> t.Any:
1708        return (self.this, self.args.get("is_string"))
1709
1710    @classmethod
1711    def number(cls, number) -> Literal:
1712        return cls(this=str(number), is_string=False)
1713
1714    @classmethod
1715    def string(cls, string) -> Literal:
1716        return cls(this=str(string), is_string=True)
1717
1718    @property
1719    def output_name(self) -> str:
1720        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1710    @classmethod
1711    def number(cls, number) -> Literal:
1712        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1714    @classmethod
1715    def string(cls, string) -> Literal:
1716        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):
1723class Join(Expression):
1724    arg_types = {
1725        "this": True,
1726        "on": False,
1727        "side": False,
1728        "kind": False,
1729        "using": False,
1730        "method": False,
1731        "global": False,
1732        "hint": False,
1733    }
1734
1735    @property
1736    def method(self) -> str:
1737        return self.text("method").upper()
1738
1739    @property
1740    def kind(self) -> str:
1741        return self.text("kind").upper()
1742
1743    @property
1744    def side(self) -> str:
1745        return self.text("side").upper()
1746
1747    @property
1748    def hint(self) -> str:
1749        return self.text("hint").upper()
1750
1751    @property
1752    def alias_or_name(self) -> str:
1753        return self.this.alias_or_name
1754
1755    def on(
1756        self,
1757        *expressions: t.Optional[ExpOrStr],
1758        append: bool = True,
1759        dialect: DialectType = None,
1760        copy: bool = True,
1761        **opts,
1762    ) -> Join:
1763        """
1764        Append to or set the ON expressions.
1765
1766        Example:
1767            >>> import sqlglot
1768            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1769            'JOIN x ON y = 1'
1770
1771        Args:
1772            *expressions: the SQL code strings to parse.
1773                If an `Expression` instance is passed, it will be used as-is.
1774                Multiple expressions are combined with an AND operator.
1775            append: if `True`, AND the new expressions to any existing expression.
1776                Otherwise, this resets the expression.
1777            dialect: the dialect used to parse the input expressions.
1778            copy: if `False`, modify this expression instance in-place.
1779            opts: other options to use to parse the input expressions.
1780
1781        Returns:
1782            The modified Join expression.
1783        """
1784        join = _apply_conjunction_builder(
1785            *expressions,
1786            instance=self,
1787            arg="on",
1788            append=append,
1789            dialect=dialect,
1790            copy=copy,
1791            **opts,
1792        )
1793
1794        if join.kind == "CROSS":
1795            join.set("kind", None)
1796
1797        return join
1798
1799    def using(
1800        self,
1801        *expressions: t.Optional[ExpOrStr],
1802        append: bool = True,
1803        dialect: DialectType = None,
1804        copy: bool = True,
1805        **opts,
1806    ) -> Join:
1807        """
1808        Append to or set the USING expressions.
1809
1810        Example:
1811            >>> import sqlglot
1812            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1813            'JOIN x USING (foo, bla)'
1814
1815        Args:
1816            *expressions: the SQL code strings to parse.
1817                If an `Expression` instance is passed, it will be used as-is.
1818            append: if `True`, concatenate the new expressions to the existing "using" list.
1819                Otherwise, this resets the expression.
1820            dialect: the dialect used to parse the input expressions.
1821            copy: if `False`, modify this expression instance in-place.
1822            opts: other options to use to parse the input expressions.
1823
1824        Returns:
1825            The modified Join expression.
1826        """
1827        join = _apply_list_builder(
1828            *expressions,
1829            instance=self,
1830            arg="using",
1831            append=append,
1832            dialect=dialect,
1833            copy=copy,
1834            **opts,
1835        )
1836
1837        if join.kind == "CROSS":
1838            join.set("kind", None)
1839
1840        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:
1755    def on(
1756        self,
1757        *expressions: t.Optional[ExpOrStr],
1758        append: bool = True,
1759        dialect: DialectType = None,
1760        copy: bool = True,
1761        **opts,
1762    ) -> Join:
1763        """
1764        Append to or set the ON expressions.
1765
1766        Example:
1767            >>> import sqlglot
1768            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1769            'JOIN x ON y = 1'
1770
1771        Args:
1772            *expressions: the SQL code strings to parse.
1773                If an `Expression` instance is passed, it will be used as-is.
1774                Multiple expressions are combined with an AND operator.
1775            append: if `True`, AND the new expressions to any existing expression.
1776                Otherwise, this resets the expression.
1777            dialect: the dialect used to parse the input expressions.
1778            copy: if `False`, modify this expression instance in-place.
1779            opts: other options to use to parse the input expressions.
1780
1781        Returns:
1782            The modified Join expression.
1783        """
1784        join = _apply_conjunction_builder(
1785            *expressions,
1786            instance=self,
1787            arg="on",
1788            append=append,
1789            dialect=dialect,
1790            copy=copy,
1791            **opts,
1792        )
1793
1794        if join.kind == "CROSS":
1795            join.set("kind", None)
1796
1797        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:
1799    def using(
1800        self,
1801        *expressions: t.Optional[ExpOrStr],
1802        append: bool = True,
1803        dialect: DialectType = None,
1804        copy: bool = True,
1805        **opts,
1806    ) -> Join:
1807        """
1808        Append to or set the USING expressions.
1809
1810        Example:
1811            >>> import sqlglot
1812            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1813            'JOIN x USING (foo, bla)'
1814
1815        Args:
1816            *expressions: the SQL code strings to parse.
1817                If an `Expression` instance is passed, it will be used as-is.
1818            append: if `True`, concatenate the new expressions to the existing "using" list.
1819                Otherwise, this resets the expression.
1820            dialect: the dialect used to parse the input expressions.
1821            copy: if `False`, modify this expression instance in-place.
1822            opts: other options to use to parse the input expressions.
1823
1824        Returns:
1825            The modified Join expression.
1826        """
1827        join = _apply_list_builder(
1828            *expressions,
1829            instance=self,
1830            arg="using",
1831            append=append,
1832            dialect=dialect,
1833            copy=copy,
1834            **opts,
1835        )
1836
1837        if join.kind == "CROSS":
1838            join.set("kind", None)
1839
1840        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):
1843class Lateral(UDTF):
1844    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):
1847class MatchRecognize(Expression):
1848    arg_types = {
1849        "partition_by": False,
1850        "order": False,
1851        "measures": False,
1852        "rows": False,
1853        "after": False,
1854        "pattern": False,
1855        "define": False,
1856        "alias": False,
1857    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1862class Final(Expression):
1863    pass
key = 'final'
class Offset(Expression):
1866class Offset(Expression):
1867    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1870class Order(Expression):
1871    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1876class Cluster(Order):
1877    pass
key = 'cluster'
class Distribute(Order):
1880class Distribute(Order):
1881    pass
key = 'distribute'
class Sort(Order):
1884class Sort(Order):
1885    pass
key = 'sort'
class Ordered(Expression):
1888class Ordered(Expression):
1889    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1892class Property(Expression):
1893    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1896class AlgorithmProperty(Property):
1897    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1900class AutoIncrementProperty(Property):
1901    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1904class BlockCompressionProperty(Property):
1905    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):
1908class CharacterSetProperty(Property):
1909    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1912class ChecksumProperty(Property):
1913    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1916class CollateProperty(Property):
1917    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1920class CopyGrantsProperty(Property):
1921    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1924class DataBlocksizeProperty(Property):
1925    arg_types = {
1926        "size": False,
1927        "units": False,
1928        "minimum": False,
1929        "maximum": False,
1930        "default": False,
1931    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1934class DefinerProperty(Property):
1935    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1938class DistKeyProperty(Property):
1939    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1942class DistStyleProperty(Property):
1943    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1946class EngineProperty(Property):
1947    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
1950class HeapProperty(Property):
1951    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
1954class ToTableProperty(Property):
1955    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1958class ExecuteAsProperty(Property):
1959    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1962class ExternalProperty(Property):
1963    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1966class FallbackProperty(Property):
1967    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1970class FileFormatProperty(Property):
1971    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1974class FreespaceProperty(Property):
1975    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1978class InputOutputFormat(Expression):
1979    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1982class IsolatedLoadingProperty(Property):
1983    arg_types = {
1984        "no": True,
1985        "concurrent": True,
1986        "for_all": True,
1987        "for_insert": True,
1988        "for_none": True,
1989    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1992class JournalProperty(Property):
1993    arg_types = {
1994        "no": False,
1995        "dual": False,
1996        "before": False,
1997        "local": False,
1998        "after": False,
1999    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
2002class LanguageProperty(Property):
2003    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
2007class ClusteredByProperty(Property):
2008    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
2011class DictProperty(Property):
2012    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2015class DictSubProperty(Property):
2016    pass
key = 'dictsubproperty'
class DictRange(Property):
2019class DictRange(Property):
2020    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2025class OnCluster(Property):
2026    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2029class LikeProperty(Property):
2030    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2033class LocationProperty(Property):
2034    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2037class LockingProperty(Property):
2038    arg_types = {
2039        "this": False,
2040        "kind": True,
2041        "for_or_in": True,
2042        "lock_type": True,
2043        "override": False,
2044    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2047class LogProperty(Property):
2048    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2051class MaterializedProperty(Property):
2052    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2055class MergeBlockRatioProperty(Property):
2056    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):
2059class NoPrimaryIndexProperty(Property):
2060    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnProperty(Property):
2063class OnProperty(Property):
2064    arg_types = {"this": True}
arg_types = {'this': True}
key = 'onproperty'
class OnCommitProperty(Property):
2067class OnCommitProperty(Property):
2068    arg_types = {"delete": False}
arg_types = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2071class PartitionedByProperty(Property):
2072    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2075class ReturnsProperty(Property):
2076    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2079class RowFormatProperty(Property):
2080    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2083class RowFormatDelimitedProperty(Property):
2084    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2085    arg_types = {
2086        "fields": False,
2087        "escaped": False,
2088        "collection_items": False,
2089        "map_keys": False,
2090        "lines": False,
2091        "null": False,
2092        "serde": False,
2093    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2096class RowFormatSerdeProperty(Property):
2097    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2101class QueryTransform(Expression):
2102    arg_types = {
2103        "expressions": True,
2104        "command_script": True,
2105        "schema": False,
2106        "row_format_before": False,
2107        "record_writer": False,
2108        "row_format_after": False,
2109        "record_reader": False,
2110    }
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):
2113class SchemaCommentProperty(Property):
2114    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2117class SerdeProperties(Property):
2118    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2121class SetProperty(Property):
2122    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2125class SettingsProperty(Property):
2126    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2129class SortKeyProperty(Property):
2130    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2133class SqlSecurityProperty(Property):
2134    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2137class StabilityProperty(Property):
2138    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2141class TemporaryProperty(Property):
2142    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2145class TransientProperty(Property):
2146    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2149class VolatileProperty(Property):
2150    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2153class WithDataProperty(Property):
2154    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2157class WithJournalTableProperty(Property):
2158    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2161class Properties(Expression):
2162    arg_types = {"expressions": True}
2163
2164    NAME_TO_PROPERTY = {
2165        "ALGORITHM": AlgorithmProperty,
2166        "AUTO_INCREMENT": AutoIncrementProperty,
2167        "CHARACTER SET": CharacterSetProperty,
2168        "CLUSTERED_BY": ClusteredByProperty,
2169        "COLLATE": CollateProperty,
2170        "COMMENT": SchemaCommentProperty,
2171        "DEFINER": DefinerProperty,
2172        "DISTKEY": DistKeyProperty,
2173        "DISTSTYLE": DistStyleProperty,
2174        "ENGINE": EngineProperty,
2175        "EXECUTE AS": ExecuteAsProperty,
2176        "FORMAT": FileFormatProperty,
2177        "LANGUAGE": LanguageProperty,
2178        "LOCATION": LocationProperty,
2179        "PARTITIONED_BY": PartitionedByProperty,
2180        "RETURNS": ReturnsProperty,
2181        "ROW_FORMAT": RowFormatProperty,
2182        "SORTKEY": SortKeyProperty,
2183    }
2184
2185    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2186
2187    # CREATE property locations
2188    # Form: schema specified
2189    #   create [POST_CREATE]
2190    #     table a [POST_NAME]
2191    #     (b int) [POST_SCHEMA]
2192    #     with ([POST_WITH])
2193    #     index (b) [POST_INDEX]
2194    #
2195    # Form: alias selection
2196    #   create [POST_CREATE]
2197    #     table a [POST_NAME]
2198    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2199    #     index (c) [POST_INDEX]
2200    class Location(AutoName):
2201        POST_CREATE = auto()
2202        POST_NAME = auto()
2203        POST_SCHEMA = auto()
2204        POST_WITH = auto()
2205        POST_ALIAS = auto()
2206        POST_EXPRESSION = auto()
2207        POST_INDEX = auto()
2208        UNSUPPORTED = auto()
2209
2210    @classmethod
2211    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2212        expressions = []
2213        for key, value in properties_dict.items():
2214            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2215            if property_cls:
2216                expressions.append(property_cls(this=convert(value)))
2217            else:
2218                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2219
2220        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:
2210    @classmethod
2211    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2212        expressions = []
2213        for key, value in properties_dict.items():
2214            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2215            if property_cls:
2216                expressions.append(property_cls(this=convert(value)))
2217            else:
2218                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2219
2220        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2200    class Location(AutoName):
2201        POST_CREATE = auto()
2202        POST_NAME = auto()
2203        POST_SCHEMA = auto()
2204        POST_WITH = auto()
2205        POST_ALIAS = auto()
2206        POST_EXPRESSION = auto()
2207        POST_INDEX = auto()
2208        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):
2223class Qualify(Expression):
2224    pass
key = 'qualify'
class Return(Expression):
2228class Return(Expression):
2229    pass
key = 'return'
class Reference(Expression):
2232class Reference(Expression):
2233    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2236class Tuple(Expression):
2237    arg_types = {"expressions": False}
2238
2239    def isin(
2240        self,
2241        *expressions: t.Any,
2242        query: t.Optional[ExpOrStr] = None,
2243        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2244        copy: bool = True,
2245        **opts,
2246    ) -> In:
2247        return In(
2248            this=maybe_copy(self, copy),
2249            expressions=[convert(e, copy=copy) for e in expressions],
2250            query=maybe_parse(query, copy=copy, **opts) if query else None,
2251            unnest=Unnest(
2252                expressions=[
2253                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2254                ]
2255            )
2256            if unnest
2257            else None,
2258        )
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:
2239    def isin(
2240        self,
2241        *expressions: t.Any,
2242        query: t.Optional[ExpOrStr] = None,
2243        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2244        copy: bool = True,
2245        **opts,
2246    ) -> In:
2247        return In(
2248            this=maybe_copy(self, copy),
2249            expressions=[convert(e, copy=copy) for e in expressions],
2250            query=maybe_parse(query, copy=copy, **opts) if query else None,
2251            unnest=Unnest(
2252                expressions=[
2253                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2254                ]
2255            )
2256            if unnest
2257            else None,
2258        )
key = 'tuple'
class Subqueryable(Unionable):
2261class Subqueryable(Unionable):
2262    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2263        """
2264        Convert this expression to an aliased expression that can be used as a Subquery.
2265
2266        Example:
2267            >>> subquery = Select().select("x").from_("tbl").subquery()
2268            >>> Select().select("x").from_(subquery).sql()
2269            'SELECT x FROM (SELECT x FROM tbl)'
2270
2271        Args:
2272            alias (str | Identifier): an optional alias for the subquery
2273            copy (bool): if `False`, modify this expression instance in-place.
2274
2275        Returns:
2276            Alias: the subquery
2277        """
2278        instance = maybe_copy(self, copy)
2279        if not isinstance(alias, Expression):
2280            alias = TableAlias(this=to_identifier(alias)) if alias else None
2281
2282        return Subquery(this=instance, alias=alias)
2283
2284    def limit(
2285        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2286    ) -> Select:
2287        raise NotImplementedError
2288
2289    @property
2290    def ctes(self):
2291        with_ = self.args.get("with")
2292        if not with_:
2293            return []
2294        return with_.expressions
2295
2296    @property
2297    def selects(self) -> t.List[Expression]:
2298        raise NotImplementedError("Subqueryable objects must implement `selects`")
2299
2300    @property
2301    def named_selects(self) -> t.List[str]:
2302        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2303
2304    def select(
2305        self,
2306        *expressions: t.Optional[ExpOrStr],
2307        append: bool = True,
2308        dialect: DialectType = None,
2309        copy: bool = True,
2310        **opts,
2311    ) -> Subqueryable:
2312        raise NotImplementedError("Subqueryable objects must implement `select`")
2313
2314    def with_(
2315        self,
2316        alias: ExpOrStr,
2317        as_: ExpOrStr,
2318        recursive: t.Optional[bool] = None,
2319        append: bool = True,
2320        dialect: DialectType = None,
2321        copy: bool = True,
2322        **opts,
2323    ) -> Subqueryable:
2324        """
2325        Append to or set the common table expressions.
2326
2327        Example:
2328            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2329            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2330
2331        Args:
2332            alias: the SQL code string to parse as the table name.
2333                If an `Expression` instance is passed, this is used as-is.
2334            as_: the SQL code string to parse as the table expression.
2335                If an `Expression` instance is passed, it will be used as-is.
2336            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2337            append: if `True`, add to any existing expressions.
2338                Otherwise, this resets the expressions.
2339            dialect: the dialect used to parse the input expression.
2340            copy: if `False`, modify this expression instance in-place.
2341            opts: other options to use to parse the input expressions.
2342
2343        Returns:
2344            The modified expression.
2345        """
2346        return _apply_cte_builder(
2347            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2348        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2262    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2263        """
2264        Convert this expression to an aliased expression that can be used as a Subquery.
2265
2266        Example:
2267            >>> subquery = Select().select("x").from_("tbl").subquery()
2268            >>> Select().select("x").from_(subquery).sql()
2269            'SELECT x FROM (SELECT x FROM tbl)'
2270
2271        Args:
2272            alias (str | Identifier): an optional alias for the subquery
2273            copy (bool): if `False`, modify this expression instance in-place.
2274
2275        Returns:
2276            Alias: the subquery
2277        """
2278        instance = maybe_copy(self, copy)
2279        if not isinstance(alias, Expression):
2280            alias = TableAlias(this=to_identifier(alias)) if alias else None
2281
2282        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:
2284    def limit(
2285        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2286    ) -> Select:
2287        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:
2304    def select(
2305        self,
2306        *expressions: t.Optional[ExpOrStr],
2307        append: bool = True,
2308        dialect: DialectType = None,
2309        copy: bool = True,
2310        **opts,
2311    ) -> Subqueryable:
2312        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:
2314    def with_(
2315        self,
2316        alias: ExpOrStr,
2317        as_: ExpOrStr,
2318        recursive: t.Optional[bool] = None,
2319        append: bool = True,
2320        dialect: DialectType = None,
2321        copy: bool = True,
2322        **opts,
2323    ) -> Subqueryable:
2324        """
2325        Append to or set the common table expressions.
2326
2327        Example:
2328            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2329            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2330
2331        Args:
2332            alias: the SQL code string to parse as the table name.
2333                If an `Expression` instance is passed, this is used as-is.
2334            as_: the SQL code string to parse as the table expression.
2335                If an `Expression` instance is passed, it will be used as-is.
2336            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2337            append: if `True`, add to any existing expressions.
2338                Otherwise, this resets the expressions.
2339            dialect: the dialect used to parse the input expression.
2340            copy: if `False`, modify this expression instance in-place.
2341            opts: other options to use to parse the input expressions.
2342
2343        Returns:
2344            The modified expression.
2345        """
2346        return _apply_cte_builder(
2347            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2348        )

Append to or set the common table expressions.

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

The modified expression.

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

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

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

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

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

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

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:
2795    def limit(
2796        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2797    ) -> Select:
2798        """
2799        Set the LIMIT expression.
2800
2801        Example:
2802            >>> Select().from_("tbl").select("x").limit(10).sql()
2803            'SELECT x FROM tbl LIMIT 10'
2804
2805        Args:
2806            expression: the SQL code string to parse.
2807                This can also be an integer.
2808                If a `Limit` instance is passed, this is used as-is.
2809                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2810            dialect: the dialect used to parse the input expression.
2811            copy: if `False`, modify this expression instance in-place.
2812            opts: other options to use to parse the input expressions.
2813
2814        Returns:
2815            Select: the modified expression.
2816        """
2817        return _apply_builder(
2818            expression=expression,
2819            instance=self,
2820            arg="limit",
2821            into=Limit,
2822            prefix="LIMIT",
2823            dialect=dialect,
2824            copy=copy,
2825            **opts,
2826        )

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

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:
2861    def select(
2862        self,
2863        *expressions: t.Optional[ExpOrStr],
2864        append: bool = True,
2865        dialect: DialectType = None,
2866        copy: bool = True,
2867        **opts,
2868    ) -> Select:
2869        """
2870        Append to or set the SELECT expressions.
2871
2872        Example:
2873            >>> Select().select("x", "y").sql()
2874            'SELECT x, y'
2875
2876        Args:
2877            *expressions: the SQL code strings to parse.
2878                If an `Expression` instance is passed, it will be used as-is.
2879            append: if `True`, add to any existing expressions.
2880                Otherwise, this resets the expressions.
2881            dialect: the dialect used to parse the input expressions.
2882            copy: if `False`, modify this expression instance in-place.
2883            opts: other options to use to parse the input expressions.
2884
2885        Returns:
2886            The modified Select expression.
2887        """
2888        return _apply_list_builder(
2889            *expressions,
2890            instance=self,
2891            arg="expressions",
2892            append=append,
2893            dialect=dialect,
2894            copy=copy,
2895            **opts,
2896        )

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:
2898    def lateral(
2899        self,
2900        *expressions: t.Optional[ExpOrStr],
2901        append: bool = True,
2902        dialect: DialectType = None,
2903        copy: bool = True,
2904        **opts,
2905    ) -> Select:
2906        """
2907        Append to or set the LATERAL expressions.
2908
2909        Example:
2910            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2911            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2912
2913        Args:
2914            *expressions: the SQL code strings to parse.
2915                If an `Expression` instance is passed, it will be used as-is.
2916            append: if `True`, add to any existing expressions.
2917                Otherwise, this resets the expressions.
2918            dialect: the dialect used to parse the input expressions.
2919            copy: if `False`, modify this expression instance in-place.
2920            opts: other options to use to parse the input expressions.
2921
2922        Returns:
2923            The modified Select expression.
2924        """
2925        return _apply_list_builder(
2926            *expressions,
2927            instance=self,
2928            arg="laterals",
2929            append=append,
2930            into=Lateral,
2931            prefix="LATERAL VIEW",
2932            dialect=dialect,
2933            copy=copy,
2934            **opts,
2935        )

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

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:
3035    def where(
3036        self,
3037        *expressions: t.Optional[ExpOrStr],
3038        append: bool = True,
3039        dialect: DialectType = None,
3040        copy: bool = True,
3041        **opts,
3042    ) -> Select:
3043        """
3044        Append to or set the WHERE expressions.
3045
3046        Example:
3047            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3048            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3049
3050        Args:
3051            *expressions: the SQL code strings to parse.
3052                If an `Expression` instance is passed, it will be used as-is.
3053                Multiple expressions are combined with an AND operator.
3054            append: if `True`, AND the new expressions to any existing expression.
3055                Otherwise, this resets the expression.
3056            dialect: the dialect used to parse the input expressions.
3057            copy: if `False`, modify this expression instance in-place.
3058            opts: other options to use to parse the input expressions.
3059
3060        Returns:
3061            Select: the modified expression.
3062        """
3063        return _apply_conjunction_builder(
3064            *expressions,
3065            instance=self,
3066            arg="where",
3067            append=append,
3068            into=Where,
3069            dialect=dialect,
3070            copy=copy,
3071            **opts,
3072        )

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:
3074    def having(
3075        self,
3076        *expressions: t.Optional[ExpOrStr],
3077        append: bool = True,
3078        dialect: DialectType = None,
3079        copy: bool = True,
3080        **opts,
3081    ) -> Select:
3082        """
3083        Append to or set the HAVING expressions.
3084
3085        Example:
3086            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3087            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3088
3089        Args:
3090            *expressions: the SQL code strings to parse.
3091                If an `Expression` instance is passed, it will be used as-is.
3092                Multiple expressions are combined with an AND operator.
3093            append: if `True`, AND the new expressions to any existing expression.
3094                Otherwise, this resets the expression.
3095            dialect: the dialect used to parse the input expressions.
3096            copy: if `False`, modify this expression instance in-place.
3097            opts: other options to use to parse the input expressions.
3098
3099        Returns:
3100            The modified Select expression.
3101        """
3102        return _apply_conjunction_builder(
3103            *expressions,
3104            instance=self,
3105            arg="having",
3106            append=append,
3107            into=Having,
3108            dialect=dialect,
3109            copy=copy,
3110            **opts,
3111        )

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

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:
3218    def lock(self, update: bool = True, copy: bool = True) -> Select:
3219        """
3220        Set the locking read mode for this expression.
3221
3222        Examples:
3223            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3224            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3225
3226            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3227            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3228
3229        Args:
3230            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3231            copy: if `False`, modify this expression instance in-place.
3232
3233        Returns:
3234            The modified expression.
3235        """
3236        inst = maybe_copy(self, copy)
3237        inst.set("locks", [Lock(update=update)])
3238
3239        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:
3241    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3242        """
3243        Set hints for this expression.
3244
3245        Examples:
3246            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3247            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3248
3249        Args:
3250            hints: The SQL code strings to parse as the hints.
3251                If an `Expression` instance is passed, it will be used as-is.
3252            dialect: The dialect used to parse the hints.
3253            copy: If `False`, modify this expression instance in-place.
3254
3255        Returns:
3256            The modified expression.
3257        """
3258        inst = maybe_copy(self, copy)
3259        inst.set(
3260            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3261        )
3262
3263        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):
3278class Subquery(DerivedTable, Unionable):
3279    arg_types = {
3280        "this": True,
3281        "alias": False,
3282        "with": False,
3283        **QUERY_MODIFIERS,
3284    }
3285
3286    def unnest(self):
3287        """
3288        Returns the first non subquery.
3289        """
3290        expression = self
3291        while isinstance(expression, Subquery):
3292            expression = expression.this
3293        return expression
3294
3295    def unwrap(self) -> Subquery:
3296        expression = self
3297        while expression.same_parent and expression.is_wrapper:
3298            expression = t.cast(Subquery, expression.parent)
3299        return expression
3300
3301    @property
3302    def is_wrapper(self) -> bool:
3303        """
3304        Whether this Subquery acts as a simple wrapper around another expression.
3305
3306        SELECT * FROM (((SELECT * FROM t)))
3307                      ^
3308                      This corresponds to a "wrapper" Subquery node
3309        """
3310        return all(v is None for k, v in self.args.items() if k != "this")
3311
3312    @property
3313    def is_star(self) -> bool:
3314        return self.this.is_star
3315
3316    @property
3317    def output_name(self) -> str:
3318        return self.alias
arg_types = {'this': True, 'alias': False, 'with': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def unnest(self):
3286    def unnest(self):
3287        """
3288        Returns the first non subquery.
3289        """
3290        expression = self
3291        while isinstance(expression, Subquery):
3292            expression = expression.this
3293        return expression

Returns the first non subquery.

def unwrap(self) -> sqlglot.expressions.Subquery:
3295    def unwrap(self) -> Subquery:
3296        expression = self
3297        while expression.same_parent and expression.is_wrapper:
3298            expression = t.cast(Subquery, expression.parent)
3299        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):
3321class TableSample(Expression):
3322    arg_types = {
3323        "this": False,
3324        "method": False,
3325        "bucket_numerator": False,
3326        "bucket_denominator": False,
3327        "bucket_field": False,
3328        "percent": False,
3329        "rows": False,
3330        "size": False,
3331        "seed": False,
3332        "kind": False,
3333    }
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):
3336class Tag(Expression):
3337    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3338
3339    arg_types = {
3340        "this": False,
3341        "prefix": False,
3342        "postfix": False,
3343    }

Tags are used for generating arbitrary sql like SELECT x.

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

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3769class DPipe(Binary):
3770    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3773class SafeDPipe(DPipe):
3774    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3777class EQ(Binary, Predicate):
3778    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3781class NullSafeEQ(Binary, Predicate):
3782    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3785class NullSafeNEQ(Binary, Predicate):
3786    pass
key = 'nullsafeneq'
class Distance(Binary):
3789class Distance(Binary):
3790    pass
key = 'distance'
class Escape(Binary):
3793class Escape(Binary):
3794    pass
key = 'escape'
class Glob(Binary, Predicate):
3797class Glob(Binary, Predicate):
3798    pass
key = 'glob'
class GT(Binary, Predicate):
3801class GT(Binary, Predicate):
3802    pass
key = 'gt'
class GTE(Binary, Predicate):
3805class GTE(Binary, Predicate):
3806    pass
key = 'gte'
class ILike(Binary, Predicate):
3809class ILike(Binary, Predicate):
3810    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3813class ILikeAny(Binary, Predicate):
3814    pass
key = 'ilikeany'
class IntDiv(Binary):
3817class IntDiv(Binary):
3818    pass
key = 'intdiv'
class Is(Binary, Predicate):
3821class Is(Binary, Predicate):
3822    pass
key = 'is'
class Kwarg(Binary):
3825class Kwarg(Binary):
3826    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3829class Like(Binary, Predicate):
3830    pass
key = 'like'
class LikeAny(Binary, Predicate):
3833class LikeAny(Binary, Predicate):
3834    pass
key = 'likeany'
class LT(Binary, Predicate):
3837class LT(Binary, Predicate):
3838    pass
key = 'lt'
class LTE(Binary, Predicate):
3841class LTE(Binary, Predicate):
3842    pass
key = 'lte'
class Mod(Binary):
3845class Mod(Binary):
3846    pass
key = 'mod'
class Mul(Binary):
3849class Mul(Binary):
3850    pass
key = 'mul'
class NEQ(Binary, Predicate):
3853class NEQ(Binary, Predicate):
3854    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3857class SimilarTo(Binary, Predicate):
3858    pass
key = 'similarto'
class Slice(Binary):
3861class Slice(Binary):
3862    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3865class Sub(Binary):
3866    pass
key = 'sub'
class ArrayOverlaps(Binary):
3869class ArrayOverlaps(Binary):
3870    pass
key = 'arrayoverlaps'
class Unary(Condition):
3875class Unary(Condition):
3876    pass
key = 'unary'
class BitwiseNot(Unary):
3879class BitwiseNot(Unary):
3880    pass
key = 'bitwisenot'
class Not(Unary):
3883class Not(Unary):
3884    pass
key = 'not'
class Paren(Unary):
3887class Paren(Unary):
3888    arg_types = {"this": True, "with": False}
3889
3890    @property
3891    def output_name(self) -> str:
3892        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):
3895class Neg(Unary):
3896    pass
key = 'neg'
class Alias(Expression):
3899class Alias(Expression):
3900    arg_types = {"this": True, "alias": False}
3901
3902    @property
3903    def output_name(self) -> str:
3904        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):
3907class Aliases(Expression):
3908    arg_types = {"this": True, "expressions": True}
3909
3910    @property
3911    def aliases(self):
3912        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3915class AtTimeZone(Expression):
3916    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3919class Between(Predicate):
3920    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3923class Bracket(Condition):
3924    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3927class SafeBracket(Bracket):
3928    """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):
3931class Distinct(Expression):
3932    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3935class In(Predicate):
3936    arg_types = {
3937        "this": True,
3938        "expressions": False,
3939        "query": False,
3940        "unnest": False,
3941        "field": False,
3942        "is_global": False,
3943    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3946class TimeUnit(Expression):
3947    """Automatically converts unit arg into a var."""
3948
3949    arg_types = {"unit": False}
3950
3951    def __init__(self, **args):
3952        unit = args.get("unit")
3953        if isinstance(unit, (Column, Literal)):
3954            args["unit"] = Var(this=unit.name)
3955        elif isinstance(unit, Week):
3956            unit.set("this", Var(this=unit.this.name))
3957
3958        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3951    def __init__(self, **args):
3952        unit = args.get("unit")
3953        if isinstance(unit, (Column, Literal)):
3954            args["unit"] = Var(this=unit.name)
3955        elif isinstance(unit, Week):
3956            unit.set("this", Var(this=unit.this.name))
3957
3958        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class IntervalYearToMonthSpan(Expression):
3963class IntervalYearToMonthSpan(Expression):
3964    arg_types = {}
arg_types = {}
key = 'intervalyeartomonthspan'
class IntervalDayToSecondSpan(Expression):
3969class IntervalDayToSecondSpan(Expression):
3970    arg_types = {}
arg_types = {}
key = 'intervaldaytosecondspan'
class Interval(TimeUnit):
3973class Interval(TimeUnit):
3974    arg_types = {"this": False, "unit": False}
3975
3976    @property
3977    def unit(self) -> t.Optional[Var]:
3978        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3981class IgnoreNulls(Expression):
3982    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3985class RespectNulls(Expression):
3986    pass
key = 'respectnulls'
class Func(Condition):
3990class Func(Condition):
3991    """
3992    The base class for all function expressions.
3993
3994    Attributes:
3995        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3996            treated as a variable length argument and the argument's value will be stored as a list.
3997        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3998            for this function expression. These values are used to map this node to a name during parsing
3999            as well as to provide the function's name during SQL string generation. By default the SQL
4000            name is set to the expression's class name transformed to snake case.
4001    """
4002
4003    is_var_len_args = False
4004
4005    @classmethod
4006    def from_arg_list(cls, args):
4007        if cls.is_var_len_args:
4008            all_arg_keys = list(cls.arg_types)
4009            # If this function supports variable length argument treat the last argument as such.
4010            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4011            num_non_var = len(non_var_len_arg_keys)
4012
4013            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4014            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4015        else:
4016            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4017
4018        return cls(**args_dict)
4019
4020    @classmethod
4021    def sql_names(cls):
4022        if cls is Func:
4023            raise NotImplementedError(
4024                "SQL name is only supported by concrete function implementations"
4025            )
4026        if "_sql_names" not in cls.__dict__:
4027            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4028        return cls._sql_names
4029
4030    @classmethod
4031    def sql_name(cls):
4032        return cls.sql_names()[0]
4033
4034    @classmethod
4035    def default_parser_mappings(cls):
4036        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):
4005    @classmethod
4006    def from_arg_list(cls, args):
4007        if cls.is_var_len_args:
4008            all_arg_keys = list(cls.arg_types)
4009            # If this function supports variable length argument treat the last argument as such.
4010            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4011            num_non_var = len(non_var_len_arg_keys)
4012
4013            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4014            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4015        else:
4016            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4017
4018        return cls(**args_dict)
@classmethod
def sql_names(cls):
4020    @classmethod
4021    def sql_names(cls):
4022        if cls is Func:
4023            raise NotImplementedError(
4024                "SQL name is only supported by concrete function implementations"
4025            )
4026        if "_sql_names" not in cls.__dict__:
4027            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4028        return cls._sql_names
@classmethod
def sql_name(cls):
4030    @classmethod
4031    def sql_name(cls):
4032        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
4034    @classmethod
4035    def default_parser_mappings(cls):
4036        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
4039class AggFunc(Func):
4040    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
4043class ParameterizedAgg(AggFunc):
4044    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
4047class Abs(Func):
4048    pass
key = 'abs'
class Transform(Func):
4052class Transform(Func):
4053    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
4056class Anonymous(Func):
4057    arg_types = {"this": True, "expressions": False}
4058    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
4063class Hll(AggFunc):
4064    arg_types = {"this": True, "expressions": False}
4065    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
4068class ApproxDistinct(AggFunc):
4069    arg_types = {"this": True, "accuracy": False}
4070    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
4073class Array(Func):
4074    arg_types = {"expressions": False}
4075    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
4079class ToChar(Func):
4080    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
4083class GenerateSeries(Func):
4084    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
4087class ArrayAgg(AggFunc):
4088    pass
key = 'arrayagg'
class ArrayAll(Func):
4091class ArrayAll(Func):
4092    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4095class ArrayAny(Func):
4096    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4099class ArrayConcat(Func):
4100    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4101    arg_types = {"this": True, "expressions": False}
4102    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4105class ArrayContains(Binary, Func):
4106    pass
key = 'arraycontains'
class ArrayContained(Binary):
4109class ArrayContained(Binary):
4110    pass
key = 'arraycontained'
class ArrayFilter(Func):
4113class ArrayFilter(Func):
4114    arg_types = {"this": True, "expression": True}
4115    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4118class ArrayJoin(Func):
4119    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4122class ArraySize(Func):
4123    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4126class ArraySort(Func):
4127    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4130class ArraySum(Func):
4131    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4134class ArrayUnionAgg(AggFunc):
4135    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4138class Avg(AggFunc):
4139    pass
key = 'avg'
class AnyValue(AggFunc):
4142class AnyValue(AggFunc):
4143    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):
4146class First(Func):
4147    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4150class Last(Func):
4151    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4154class Case(Func):
4155    arg_types = {"this": False, "ifs": True, "default": False}
4156
4157    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4158        instance = maybe_copy(self, copy)
4159        instance.append(
4160            "ifs",
4161            If(
4162                this=maybe_parse(condition, copy=copy, **opts),
4163                true=maybe_parse(then, copy=copy, **opts),
4164            ),
4165        )
4166        return instance
4167
4168    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4169        instance = maybe_copy(self, copy)
4170        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4171        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:
4157    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4158        instance = maybe_copy(self, copy)
4159        instance.append(
4160            "ifs",
4161            If(
4162                this=maybe_parse(condition, copy=copy, **opts),
4163                true=maybe_parse(then, copy=copy, **opts),
4164            ),
4165        )
4166        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4168    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4169        instance = maybe_copy(self, copy)
4170        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4171        return instance
key = 'case'
class Cast(Func):
4174class Cast(Func):
4175    arg_types = {"this": True, "to": True, "format": False}
4176
4177    @property
4178    def name(self) -> str:
4179        return self.this.name
4180
4181    @property
4182    def to(self) -> DataType:
4183        return self.args["to"]
4184
4185    @property
4186    def output_name(self) -> str:
4187        return self.name
4188
4189    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4190        """
4191        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4192        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4193        array<int> != array<float>.
4194
4195        Args:
4196            dtypes: the data types to compare this Cast's DataType to.
4197
4198        Returns:
4199            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4200        """
4201        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:
4189    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4190        """
4191        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4192        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4193        array<int> != array<float>.
4194
4195        Args:
4196            dtypes: the data types to compare this Cast's DataType to.
4197
4198        Returns:
4199            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4200        """
4201        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):
4204class TryCast(Cast):
4205    pass
key = 'trycast'
class CastToStrType(Func):
4208class CastToStrType(Func):
4209    arg_types = {"this": True, "to": True}
arg_types = {'this': True, 'to': True}
key = 'casttostrtype'
class Collate(Binary):
4212class Collate(Binary):
4213    pass
key = 'collate'
class Ceil(Func):
4216class Ceil(Func):
4217    arg_types = {"this": True, "decimals": False}
4218    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4221class Coalesce(Func):
4222    arg_types = {"this": True, "expressions": False}
4223    is_var_len_args = True
4224    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4227class Concat(Func):
4228    arg_types = {"expressions": True}
4229    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4232class SafeConcat(Concat):
4233    pass
key = 'safeconcat'
class ConcatWs(Concat):
4236class ConcatWs(Concat):
4237    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4240class Count(AggFunc):
4241    arg_types = {"this": False, "expressions": False}
4242    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4245class CountIf(AggFunc):
4246    pass
key = 'countif'
class CurrentDate(Func):
4249class CurrentDate(Func):
4250    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4253class CurrentDatetime(Func):
4254    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4257class CurrentTime(Func):
4258    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4261class CurrentTimestamp(Func):
4262    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4265class CurrentUser(Func):
4266    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4269class DateAdd(Func, TimeUnit):
4270    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4273class DateSub(Func, TimeUnit):
4274    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4277class DateDiff(Func, TimeUnit):
4278    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4279    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4282class DateTrunc(Func):
4283    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4286class DatetimeAdd(Func, TimeUnit):
4287    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4290class DatetimeSub(Func, TimeUnit):
4291    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4294class DatetimeDiff(Func, TimeUnit):
4295    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4298class DatetimeTrunc(Func, TimeUnit):
4299    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4302class DayOfWeek(Func):
4303    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4306class DayOfMonth(Func):
4307    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4310class DayOfYear(Func):
4311    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4314class WeekOfYear(Func):
4315    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4318class MonthsBetween(Func):
4319    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4322class LastDateOfMonth(Func):
4323    pass
key = 'lastdateofmonth'
class Extract(Func):
4326class Extract(Func):
4327    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4330class TimestampAdd(Func, TimeUnit):
4331    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4334class TimestampSub(Func, TimeUnit):
4335    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4338class TimestampDiff(Func, TimeUnit):
4339    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4342class TimestampTrunc(Func, TimeUnit):
4343    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4346class TimeAdd(Func, TimeUnit):
4347    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4350class TimeSub(Func, TimeUnit):
4351    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4354class TimeDiff(Func, TimeUnit):
4355    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4358class TimeTrunc(Func, TimeUnit):
4359    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4362class DateFromParts(Func):
4363    _sql_names = ["DATEFROMPARTS"]
4364    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4367class DateStrToDate(Func):
4368    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4371class DateToDateStr(Func):
4372    pass
key = 'datetodatestr'
class DateToDi(Func):
4375class DateToDi(Func):
4376    pass
key = 'datetodi'
class Date(Func):
4380class Date(Func):
4381    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4384class Day(Func):
4385    pass
key = 'day'
class Decode(Func):
4388class Decode(Func):
4389    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4392class DiToDate(Func):
4393    pass
key = 'ditodate'
class Encode(Func):
4396class Encode(Func):
4397    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4400class Exp(Func):
4401    pass
key = 'exp'
class Explode(Func):
4404class Explode(Func):
4405    pass
key = 'explode'
class Floor(Func):
4408class Floor(Func):
4409    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4412class FromBase64(Func):
4413    pass
key = 'frombase64'
class ToBase64(Func):
4416class ToBase64(Func):
4417    pass
key = 'tobase64'
class Greatest(Func):
4420class Greatest(Func):
4421    arg_types = {"this": True, "expressions": False}
4422    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4425class GroupConcat(Func):
4426    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4429class Hex(Func):
4430    pass
key = 'hex'
class Xor(Connector, Func):
4433class Xor(Connector, Func):
4434    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4437class If(Func):
4438    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4441class Initcap(Func):
4442    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4445class IsNan(Func):
4446    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class JSONKeyValue(Expression):
4449class JSONKeyValue(Expression):
4450    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4453class JSONObject(Func):
4454    arg_types = {
4455        "expressions": False,
4456        "null_handling": False,
4457        "unique_keys": False,
4458        "return_type": False,
4459        "format_json": False,
4460        "encoding": False,
4461    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4464class OpenJSONColumnDef(Expression):
4465    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):
4468class OpenJSON(Func):
4469    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4472class JSONBContains(Binary):
4473    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4476class JSONExtract(Binary, Func):
4477    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4480class JSONExtractScalar(JSONExtract):
4481    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4484class JSONBExtract(JSONExtract):
4485    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4488class JSONBExtractScalar(JSONExtract):
4489    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4492class JSONFormat(Func):
4493    arg_types = {"this": False, "options": False}
4494    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4498class JSONArrayContains(Binary, Predicate, Func):
4499    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4502class Least(Func):
4503    arg_types = {"this": True, "expressions": False}
4504    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4507class Left(Func):
4508    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4515class Length(Func):
4516    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4519class Levenshtein(Func):
4520    arg_types = {
4521        "this": True,
4522        "expression": False,
4523        "ins_cost": False,
4524        "del_cost": False,
4525        "sub_cost": False,
4526    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4529class Ln(Func):
4530    pass
key = 'ln'
class Log(Func):
4533class Log(Func):
4534    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4537class Log2(Func):
4538    pass
key = 'log2'
class Log10(Func):
4541class Log10(Func):
4542    pass
key = 'log10'
class LogicalOr(AggFunc):
4545class LogicalOr(AggFunc):
4546    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4549class LogicalAnd(AggFunc):
4550    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4553class Lower(Func):
4554    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4557class Map(Func):
4558    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4561class MapFromEntries(Func):
4562    pass
key = 'mapfromentries'
class StarMap(Func):
4565class StarMap(Func):
4566    pass
key = 'starmap'
class VarMap(Func):
4569class VarMap(Func):
4570    arg_types = {"keys": True, "values": True}
4571    is_var_len_args = True
4572
4573    @property
4574    def keys(self) -> t.List[Expression]:
4575        return self.args["keys"].expressions
4576
4577    @property
4578    def values(self) -> t.List[Expression]:
4579        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4583class MatchAgainst(Func):
4584    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4587class Max(AggFunc):
4588    arg_types = {"this": True, "expressions": False}
4589    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4592class MD5(Func):
4593    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4597class MD5Digest(Func):
4598    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4601class Min(AggFunc):
4602    arg_types = {"this": True, "expressions": False}
4603    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4606class Month(Func):
4607    pass
key = 'month'
class Nvl2(Func):
4610class Nvl2(Func):
4611    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4614class Posexplode(Func):
4615    pass
key = 'posexplode'
class Pow(Binary, Func):
4618class Pow(Binary, Func):
4619    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4622class PercentileCont(AggFunc):
4623    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4626class PercentileDisc(AggFunc):
4627    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4630class Quantile(AggFunc):
4631    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4634class ApproxQuantile(Quantile):
4635    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):
4638class RangeN(Func):
4639    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4642class ReadCSV(Func):
4643    _sql_names = ["READ_CSV"]
4644    is_var_len_args = True
4645    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4648class Reduce(Func):
4649    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):
4652class RegexpExtract(Func):
4653    arg_types = {
4654        "this": True,
4655        "expression": True,
4656        "position": False,
4657        "occurrence": False,
4658        "parameters": False,
4659        "group": False,
4660    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4663class RegexpReplace(Func):
4664    arg_types = {
4665        "this": True,
4666        "expression": True,
4667        "replacement": True,
4668        "position": False,
4669        "occurrence": False,
4670        "parameters": False,
4671    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4674class RegexpLike(Binary, Func):
4675    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4678class RegexpILike(Func):
4679    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4684class RegexpSplit(Func):
4685    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4688class Repeat(Func):
4689    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4692class Round(Func):
4693    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4696class RowNumber(Func):
4697    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4700class SafeDivide(Func):
4701    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4704class SetAgg(AggFunc):
4705    pass
key = 'setagg'
class SHA(Func):
4708class SHA(Func):
4709    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4712class SHA2(Func):
4713    _sql_names = ["SHA2"]
4714    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4717class SortArray(Func):
4718    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4721class Split(Func):
4722    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4727class Substring(Func):
4728    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4731class StandardHash(Func):
4732    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4735class StartsWith(Func):
4736    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4737    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4740class StrPosition(Func):
4741    arg_types = {
4742        "this": True,
4743        "substr": True,
4744        "position": False,
4745        "instance": False,
4746    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4749class StrToDate(Func):
4750    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4753class StrToTime(Func):
4754    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4759class StrToUnix(Func):
4760    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
4765class StrToMap(Func):
4766    arg_types = {
4767        "this": True,
4768        "pair_delim": False,
4769        "key_value_delim": False,
4770        "duplicate_resolution_callback": False,
4771    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
4774class NumberToStr(Func):
4775    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
4778class FromBase(Func):
4779    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4782class Struct(Func):
4783    arg_types = {"expressions": True}
4784    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4787class StructExtract(Func):
4788    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Stuff(Func):
4793class Stuff(Func):
4794    _sql_names = ["STUFF", "INSERT"]
4795    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):
4798class Sum(AggFunc):
4799    pass
key = 'sum'
class Sqrt(Func):
4802class Sqrt(Func):
4803    pass
key = 'sqrt'
class Stddev(AggFunc):
4806class Stddev(AggFunc):
4807    pass
key = 'stddev'
class StddevPop(AggFunc):
4810class StddevPop(AggFunc):
4811    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4814class StddevSamp(AggFunc):
4815    pass
key = 'stddevsamp'
class TimeToStr(Func):
4818class TimeToStr(Func):
4819    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
4822class TimeToTimeStr(Func):
4823    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4826class TimeToUnix(Func):
4827    pass
key = 'timetounix'
class TimeStrToDate(Func):
4830class TimeStrToDate(Func):
4831    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4834class TimeStrToTime(Func):
4835    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4838class TimeStrToUnix(Func):
4839    pass
key = 'timestrtounix'
class Trim(Func):
4842class Trim(Func):
4843    arg_types = {
4844        "this": True,
4845        "expression": False,
4846        "position": False,
4847        "collation": False,
4848    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4851class TsOrDsAdd(Func, TimeUnit):
4852    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4855class TsOrDsToDateStr(Func):
4856    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4859class TsOrDsToDate(Func):
4860    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4863class TsOrDiToDi(Func):
4864    pass
key = 'tsorditodi'
class Unhex(Func):
4867class Unhex(Func):
4868    pass
key = 'unhex'
class UnixToStr(Func):
4871class UnixToStr(Func):
4872    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4877class UnixToTime(Func):
4878    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4879
4880    SECONDS = Literal.string("seconds")
4881    MILLIS = Literal.string("millis")
4882    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):
4885class UnixToTimeStr(Func):
4886    pass
key = 'unixtotimestr'
class Upper(Func):
4889class Upper(Func):
4890    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4893class Variance(AggFunc):
4894    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4897class VariancePop(AggFunc):
4898    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4901class Week(Func):
4902    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4905class XMLTable(Func):
4906    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):
4909class Year(Func):
4910    pass
key = 'year'
class Use(Expression):
4913class Use(Expression):
4914    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4917class Merge(Expression):
4918    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):
4921class When(Func):
4922    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):
4927class NextValueFor(Func):
4928    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:
4965def maybe_parse(
4966    sql_or_expression: ExpOrStr,
4967    *,
4968    into: t.Optional[IntoType] = None,
4969    dialect: DialectType = None,
4970    prefix: t.Optional[str] = None,
4971    copy: bool = False,
4972    **opts,
4973) -> Expression:
4974    """Gracefully handle a possible string or expression.
4975
4976    Example:
4977        >>> maybe_parse("1")
4978        (LITERAL this: 1, is_string: False)
4979        >>> maybe_parse(to_identifier("x"))
4980        (IDENTIFIER this: x, quoted: False)
4981
4982    Args:
4983        sql_or_expression: the SQL code string or an expression
4984        into: the SQLGlot Expression to parse into
4985        dialect: the dialect used to parse the input expressions (in the case that an
4986            input expression is a SQL string).
4987        prefix: a string to prefix the sql with before it gets parsed
4988            (automatically includes a space)
4989        copy: whether or not to copy the expression.
4990        **opts: other options to use to parse the input expressions (again, in the case
4991            that an input expression is a SQL string).
4992
4993    Returns:
4994        Expression: the parsed or given expression.
4995    """
4996    if isinstance(sql_or_expression, Expression):
4997        if copy:
4998            return sql_or_expression.copy()
4999        return sql_or_expression
5000
5001    if sql_or_expression is None:
5002        raise ParseError(f"SQL cannot be None")
5003
5004    import sqlglot
5005
5006    sql = str(sql_or_expression)
5007    if prefix:
5008        sql = f"{prefix} {sql}"
5009
5010    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):
5023def maybe_copy(instance, copy=True):
5024    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:
5204def union(
5205    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5206) -> Union:
5207    """
5208    Initializes a syntax tree from one UNION expression.
5209
5210    Example:
5211        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5212        'SELECT * FROM foo UNION SELECT * FROM bla'
5213
5214    Args:
5215        left: the SQL code string corresponding to the left-hand side.
5216            If an `Expression` instance is passed, it will be used as-is.
5217        right: the SQL code string corresponding to the right-hand side.
5218            If an `Expression` instance is passed, it will be used as-is.
5219        distinct: set the DISTINCT flag if and only if this is true.
5220        dialect: the dialect used to parse the input expression.
5221        opts: other options to use to parse the input expressions.
5222
5223    Returns:
5224        The new Union instance.
5225    """
5226    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5227    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5228
5229    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:
5232def intersect(
5233    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5234) -> Intersect:
5235    """
5236    Initializes a syntax tree from one INTERSECT expression.
5237
5238    Example:
5239        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5240        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5241
5242    Args:
5243        left: the SQL code string corresponding to the left-hand side.
5244            If an `Expression` instance is passed, it will be used as-is.
5245        right: the SQL code string corresponding to the right-hand side.
5246            If an `Expression` instance is passed, it will be used as-is.
5247        distinct: set the DISTINCT flag if and only if this is true.
5248        dialect: the dialect used to parse the input expression.
5249        opts: other options to use to parse the input expressions.
5250
5251    Returns:
5252        The new Intersect instance.
5253    """
5254    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5255    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5256
5257    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:
5260def except_(
5261    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5262) -> Except:
5263    """
5264    Initializes a syntax tree from one EXCEPT expression.
5265
5266    Example:
5267        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5268        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5269
5270    Args:
5271        left: the SQL code string corresponding to the left-hand side.
5272            If an `Expression` instance is passed, it will be used as-is.
5273        right: the SQL code string corresponding to the right-hand side.
5274            If an `Expression` instance is passed, it will be used as-is.
5275        distinct: set the DISTINCT flag if and only if this is true.
5276        dialect: the dialect used to parse the input expression.
5277        opts: other options to use to parse the input expressions.
5278
5279    Returns:
5280        The new Except instance.
5281    """
5282    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5283    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5284
5285    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:
5288def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5289    """
5290    Initializes a syntax tree from one or multiple SELECT expressions.
5291
5292    Example:
5293        >>> select("col1", "col2").from_("tbl").sql()
5294        'SELECT col1, col2 FROM tbl'
5295
5296    Args:
5297        *expressions: the SQL code string to parse as the expressions of a
5298            SELECT statement. If an Expression instance is passed, this is used as-is.
5299        dialect: the dialect used to parse the input expressions (in the case that an
5300            input expression is a SQL string).
5301        **opts: other options to use to parse the input expressions (again, in the case
5302            that an input expression is a SQL string).
5303
5304    Returns:
5305        Select: the syntax tree for the SELECT statement.
5306    """
5307    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:
5310def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5311    """
5312    Initializes a syntax tree from a FROM expression.
5313
5314    Example:
5315        >>> from_("tbl").select("col1", "col2").sql()
5316        'SELECT col1, col2 FROM tbl'
5317
5318    Args:
5319        *expression: the SQL code string to parse as the FROM expressions of a
5320            SELECT statement. If an Expression instance is passed, this is used as-is.
5321        dialect: the dialect used to parse the input expression (in the case that the
5322            input expression is a SQL string).
5323        **opts: other options to use to parse the input expressions (again, in the case
5324            that the input expression is a SQL string).
5325
5326    Returns:
5327        Select: the syntax tree for the SELECT statement.
5328    """
5329    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:
5332def update(
5333    table: str | Table,
5334    properties: dict,
5335    where: t.Optional[ExpOrStr] = None,
5336    from_: t.Optional[ExpOrStr] = None,
5337    dialect: DialectType = None,
5338    **opts,
5339) -> Update:
5340    """
5341    Creates an update statement.
5342
5343    Example:
5344        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5345        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5346
5347    Args:
5348        *properties: dictionary of properties to set which are
5349            auto converted to sql objects eg None -> NULL
5350        where: sql conditional parsed into a WHERE statement
5351        from_: sql statement parsed into a FROM statement
5352        dialect: the dialect used to parse the input expressions.
5353        **opts: other options to use to parse the input expressions.
5354
5355    Returns:
5356        Update: the syntax tree for the UPDATE statement.
5357    """
5358    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5359    update_expr.set(
5360        "expressions",
5361        [
5362            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5363            for k, v in properties.items()
5364        ],
5365    )
5366    if from_:
5367        update_expr.set(
5368            "from",
5369            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5370        )
5371    if isinstance(where, Condition):
5372        where = Where(this=where)
5373    if where:
5374        update_expr.set(
5375            "where",
5376            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5377        )
5378    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:
5381def delete(
5382    table: ExpOrStr,
5383    where: t.Optional[ExpOrStr] = None,
5384    returning: t.Optional[ExpOrStr] = None,
5385    dialect: DialectType = None,
5386    **opts,
5387) -> Delete:
5388    """
5389    Builds a delete statement.
5390
5391    Example:
5392        >>> delete("my_table", where="id > 1").sql()
5393        'DELETE FROM my_table WHERE id > 1'
5394
5395    Args:
5396        where: sql conditional parsed into a WHERE statement
5397        returning: sql conditional parsed into a RETURNING statement
5398        dialect: the dialect used to parse the input expressions.
5399        **opts: other options to use to parse the input expressions.
5400
5401    Returns:
5402        Delete: the syntax tree for the DELETE statement.
5403    """
5404    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5405    if where:
5406        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5407    if returning:
5408        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5409    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:
5412def insert(
5413    expression: ExpOrStr,
5414    into: ExpOrStr,
5415    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5416    overwrite: t.Optional[bool] = None,
5417    dialect: DialectType = None,
5418    copy: bool = True,
5419    **opts,
5420) -> Insert:
5421    """
5422    Builds an INSERT statement.
5423
5424    Example:
5425        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5426        'INSERT INTO tbl VALUES (1, 2, 3)'
5427
5428    Args:
5429        expression: the sql string or expression of the INSERT statement
5430        into: the tbl to insert data to.
5431        columns: optionally the table's column names.
5432        overwrite: whether to INSERT OVERWRITE or not.
5433        dialect: the dialect used to parse the input expressions.
5434        copy: whether or not to copy the expression.
5435        **opts: other options to use to parse the input expressions.
5436
5437    Returns:
5438        Insert: the syntax tree for the INSERT statement.
5439    """
5440    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5441    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5442
5443    if columns:
5444        this = _apply_list_builder(
5445            *columns,
5446            instance=Schema(this=this),
5447            arg="expressions",
5448            into=Identifier,
5449            copy=False,
5450            dialect=dialect,
5451            **opts,
5452        )
5453
5454    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:
5457def condition(
5458    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5459) -> Condition:
5460    """
5461    Initialize a logical condition expression.
5462
5463    Example:
5464        >>> condition("x=1").sql()
5465        'x = 1'
5466
5467        This is helpful for composing larger logical syntax trees:
5468        >>> where = condition("x=1")
5469        >>> where = where.and_("y=1")
5470        >>> Select().from_("tbl").select("*").where(where).sql()
5471        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5472
5473    Args:
5474        *expression: the SQL code string to parse.
5475            If an Expression instance is passed, this is used as-is.
5476        dialect: the dialect used to parse the input expression (in the case that the
5477            input expression is a SQL string).
5478        copy: Whether or not to copy `expression` (only applies to expressions).
5479        **opts: other options to use to parse the input expressions (again, in the case
5480            that the input expression is a SQL string).
5481
5482    Returns:
5483        The new Condition instance
5484    """
5485    return maybe_parse(
5486        expression,
5487        into=Condition,
5488        dialect=dialect,
5489        copy=copy,
5490        **opts,
5491    )

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:
5494def and_(
5495    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5496) -> Condition:
5497    """
5498    Combine multiple conditions with an AND logical operator.
5499
5500    Example:
5501        >>> and_("x=1", and_("y=1", "z=1")).sql()
5502        'x = 1 AND (y = 1 AND z = 1)'
5503
5504    Args:
5505        *expressions: the SQL code strings to parse.
5506            If an Expression instance is passed, this is used as-is.
5507        dialect: the dialect used to parse the input expression.
5508        copy: whether or not to copy `expressions` (only applies to Expressions).
5509        **opts: other options to use to parse the input expressions.
5510
5511    Returns:
5512        And: the new condition
5513    """
5514    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:
5517def or_(
5518    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5519) -> Condition:
5520    """
5521    Combine multiple conditions with an OR logical operator.
5522
5523    Example:
5524        >>> or_("x=1", or_("y=1", "z=1")).sql()
5525        'x = 1 OR (y = 1 OR z = 1)'
5526
5527    Args:
5528        *expressions: the SQL code strings to parse.
5529            If an Expression instance is passed, this is used as-is.
5530        dialect: the dialect used to parse the input expression.
5531        copy: whether or not to copy `expressions` (only applies to Expressions).
5532        **opts: other options to use to parse the input expressions.
5533
5534    Returns:
5535        Or: the new condition
5536    """
5537    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:
5540def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5541    """
5542    Wrap a condition with a NOT operator.
5543
5544    Example:
5545        >>> not_("this_suit='black'").sql()
5546        "NOT this_suit = 'black'"
5547
5548    Args:
5549        expression: the SQL code string 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 to copy the expression or not.
5553        **opts: other options to use to parse the input expressions.
5554
5555    Returns:
5556        The new condition.
5557    """
5558    this = condition(
5559        expression,
5560        dialect=dialect,
5561        copy=copy,
5562        **opts,
5563    )
5564    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:
5567def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5568    """
5569    Wrap an expression in parentheses.
5570
5571    Example:
5572        >>> paren("5 + 3").sql()
5573        '(5 + 3)'
5574
5575    Args:
5576        expression: the SQL code string to parse.
5577            If an Expression instance is passed, this is used as-is.
5578        copy: whether to copy the expression or not.
5579
5580    Returns:
5581        The wrapped expression.
5582    """
5583    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):
5601def to_identifier(name, quoted=None, copy=True):
5602    """Builds an identifier.
5603
5604    Args:
5605        name: The name to turn into an identifier.
5606        quoted: Whether or not force quote the identifier.
5607        copy: Whether or not to copy a passed in Identefier node.
5608
5609    Returns:
5610        The identifier ast node.
5611    """
5612
5613    if name is None:
5614        return None
5615
5616    if isinstance(name, Identifier):
5617        identifier = maybe_copy(name, copy)
5618    elif isinstance(name, str):
5619        identifier = Identifier(
5620            this=name,
5621            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5622        )
5623    else:
5624        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5625    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:
5631def to_interval(interval: str | Literal) -> Interval:
5632    """Builds an interval expression from a string like '1 day' or '5 months'."""
5633    if isinstance(interval, Literal):
5634        if not interval.is_string:
5635            raise ValueError("Invalid interval string.")
5636
5637        interval = interval.this
5638
5639    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5640
5641    if not interval_parts:
5642        raise ValueError("Invalid interval string.")
5643
5644    return Interval(
5645        this=Literal.string(interval_parts.group(1)),
5646        unit=Var(this=interval_parts.group(2)),
5647    )

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

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:
5819def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5820    """Cast an expression to a data type.
5821
5822    Example:
5823        >>> cast('x + 1', 'int').sql()
5824        'CAST(x + 1 AS INT)'
5825
5826    Args:
5827        expression: The expression to cast.
5828        to: The datatype to cast to.
5829
5830    Returns:
5831        The new Cast instance.
5832    """
5833    expression = maybe_parse(expression, **opts)
5834    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:
5837def table_(
5838    table: Identifier | str,
5839    db: t.Optional[Identifier | str] = None,
5840    catalog: t.Optional[Identifier | str] = None,
5841    quoted: t.Optional[bool] = None,
5842    alias: t.Optional[Identifier | str] = None,
5843) -> Table:
5844    """Build a Table.
5845
5846    Args:
5847        table: Table name.
5848        db: Database name.
5849        catalog: Catalog name.
5850        quote: Whether to force quotes on the table's identifiers.
5851        alias: Table's alias.
5852
5853    Returns:
5854        The new Table instance.
5855    """
5856    return Table(
5857        this=to_identifier(table, quoted=quoted),
5858        db=to_identifier(db, quoted=quoted),
5859        catalog=to_identifier(catalog, quoted=quoted),
5860        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5861    )

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:
5864def values(
5865    values: t.Iterable[t.Tuple[t.Any, ...]],
5866    alias: t.Optional[str] = None,
5867    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5868) -> Values:
5869    """Build VALUES statement.
5870
5871    Example:
5872        >>> values([(1, '2')]).sql()
5873        "VALUES (1, '2')"
5874
5875    Args:
5876        values: values statements that will be converted to SQL
5877        alias: optional alias
5878        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5879         If either are provided then an alias is also required.
5880
5881    Returns:
5882        Values: the Values expression object
5883    """
5884    if columns and not alias:
5885        raise ValueError("Alias is required when providing columns")
5886
5887    return Values(
5888        expressions=[convert(tup) for tup in values],
5889        alias=(
5890            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5891            if columns
5892            else (TableAlias(this=to_identifier(alias)) if alias else None)
5893        ),
5894    )

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:
5897def var(name: t.Optional[ExpOrStr]) -> Var:
5898    """Build a SQL variable.
5899
5900    Example:
5901        >>> repr(var('x'))
5902        '(VAR this: x)'
5903
5904        >>> repr(var(column('x', table='y')))
5905        '(VAR this: x)'
5906
5907    Args:
5908        name: The name of the var or an expression who's name will become the var.
5909
5910    Returns:
5911        The new variable node.
5912    """
5913    if not name:
5914        raise ValueError("Cannot convert empty name into var.")
5915
5916    if isinstance(name, Expression):
5917        name = name.name
5918    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:
5921def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5922    """Build ALTER TABLE... RENAME... expression
5923
5924    Args:
5925        old_name: The old name of the table
5926        new_name: The new name of the table
5927
5928    Returns:
5929        Alter table expression
5930    """
5931    old_table = to_table(old_name)
5932    new_table = to_table(new_name)
5933    return AlterTable(
5934        this=old_table,
5935        actions=[
5936            RenameTable(this=new_table),
5937        ],
5938    )

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

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:
6028def table_name(table: Table | str, dialect: DialectType = None) -> str:
6029    """Get the full name of a table as a string.
6030
6031    Args:
6032        table: Table expression node or string.
6033        dialect: The dialect to generate the table name for.
6034
6035    Examples:
6036        >>> from sqlglot import exp, parse_one
6037        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
6038        'a.b.c'
6039
6040    Returns:
6041        The table name.
6042    """
6043
6044    table = maybe_parse(table, into=Table)
6045
6046    if not table:
6047        raise ValueError(f"Cannot parse {table}")
6048
6049    return ".".join(
6050        part.sql(dialect=dialect, identify=True)
6051        if not SAFE_IDENTIFIER_RE.match(part.name)
6052        else part.name
6053        for part in table.parts
6054    )

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

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
6212def false() -> Boolean:
6213    """
6214    Returns a false Boolean expression.
6215    """
6216    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6219def null() -> Null:
6220    """
6221    Returns a Null expression.
6222    """
6223    return Null()

Returns a Null expression.

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