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

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):
250    def copy(self):
251        """
252        Returns a deep copy of the expression.
253        """
254        new = deepcopy(self)
255        new.parent = self.parent
256        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
258    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
259        if self.comments is None:
260            self.comments = []
261        if comments:
262            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
264    def append(self, arg_key: str, value: t.Any) -> None:
265        """
266        Appends value to arg_key if it's a list or sets it as a new list.
267
268        Args:
269            arg_key (str): name of the list expression arg
270            value (Any): value to append to the list
271        """
272        if not isinstance(self.args.get(arg_key), list):
273            self.args[arg_key] = []
274        self.args[arg_key].append(value)
275        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:
277    def set(self, arg_key: str, value: t.Any) -> None:
278        """
279        Sets arg_key to value.
280
281        Args:
282            arg_key: name of the expression arg.
283            value: value to set the arg to.
284        """
285        if value is None:
286            self.args.pop(arg_key, None)
287            return
288
289        self.args[arg_key] = value
290        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]]:
311    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
312        """Yields the key and expression for all arguments, exploding list args."""
313        for k, vs in self.args.items():
314            if type(vs) is list:
315                for v in vs:
316                    if hasattr(v, "parent"):
317                        yield k, v
318            else:
319                if hasattr(vs, "parent"):
320                    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]:
322    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
323        """
324        Returns the first node in this tree which matches at least one of
325        the specified types.
326
327        Args:
328            expression_types: the expression type(s) to match.
329            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
330
331        Returns:
332            The node which matches the criteria or None if no such node was found.
333        """
334        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]:
336    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
337        """
338        Returns a generator object which visits all nodes in this tree and only
339        yields those that match at least one of the specified expression types.
340
341        Args:
342            expression_types: the expression type(s) to match.
343            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
344
345        Returns:
346            The generator object.
347        """
348        for expression, *_ in self.walk(bfs=bfs):
349            if isinstance(expression, expression_types):
350                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]:
352    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
353        """
354        Returns a nearest parent matching expression_types.
355
356        Args:
357            expression_types: the expression type(s) to match.
358
359        Returns:
360            The parent node.
361        """
362        ancestor = self.parent
363        while ancestor and not isinstance(ancestor, expression_types):
364            ancestor = ancestor.parent
365        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:
379    def root(self) -> Expression:
380        """
381        Returns the root expression of this tree.
382        """
383        expression = self
384        while expression.parent:
385            expression = expression.parent
386        return expression

Returns the root expression of this tree.

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

Returns the first non parenthesis child or self.

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

Returns the inner expression if this is an Alias.

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

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
465    def flatten(self, unnest=True):
466        """
467        Returns a generator which yields child nodes who's parents are the same class.
468
469        A AND B AND C -> [A, B, C]
470        """
471        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
472            if not type(node) is self.__class__:
473                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:
481    def sql(self, dialect: DialectType = None, **opts) -> str:
482        """
483        Returns SQL string representation of this tree.
484
485        Args:
486            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
487            opts: other `sqlglot.generator.Generator` options.
488
489        Returns:
490            The SQL string.
491        """
492        from sqlglot.dialects import Dialect
493
494        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):
520    def transform(self, fun, *args, copy=True, **kwargs):
521        """
522        Recursively visits all tree nodes (excluding already transformed ones)
523        and applies the given transformation function to each node.
524
525        Args:
526            fun (function): a function which takes a node as an argument and returns a
527                new transformed node or the same node without modifications. If the function
528                returns None, then the corresponding node will be removed from the syntax tree.
529            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
530                modified in place.
531
532        Returns:
533            The transformed tree.
534        """
535        node = self.copy() if copy else self
536        new_node = fun(node, *args, **kwargs)
537
538        if new_node is None or not isinstance(new_node, Expression):
539            return new_node
540        if new_node is not node:
541            new_node.parent = node.parent
542            return new_node
543
544        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
545        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):
555    def replace(self, expression):
556        """
557        Swap out this expression with a new expression.
558
559        For example::
560
561            >>> tree = Select().select("x").from_("tbl")
562            >>> tree.find(Column).replace(Column(this="y"))
563            (COLUMN this: y)
564            >>> tree.sql()
565            'SELECT y FROM tbl'
566
567        Args:
568            expression: new node
569
570        Returns:
571            The new expression or expressions.
572        """
573        if not self.parent:
574            return expression
575
576        parent = self.parent
577        self.parent = None
578
579        replace_children(parent, lambda child: expression if child is self else child)
580        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:
582    def pop(self: E) -> E:
583        """
584        Remove this expression from its AST.
585
586        Returns:
587            The popped expression.
588        """
589        self.replace(None)
590        return self

Remove this expression from its AST.

Returns:

The popped expression.

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

Dump this Expression to a JSON-serializable dict.

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

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

key = 'predicate'
class DerivedTable(Expression):
886class DerivedTable(Expression):
887    @property
888    def alias_column_names(self) -> t.List[str]:
889        table_alias = self.args.get("alias")
890        if not table_alias:
891            return []
892        return [c.name for c in table_alias.args.get("columns") or []]
893
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]
alias_column_names: List[str]
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 CollateColumnConstraint(ColumnConstraintKind):
1273class CollateColumnConstraint(ColumnConstraintKind):
1274    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1277class CommentColumnConstraint(ColumnConstraintKind):
1278    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1281class CompressColumnConstraint(ColumnConstraintKind):
1282    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1285class DateFormatColumnConstraint(ColumnConstraintKind):
1286    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1289class DefaultColumnConstraint(ColumnConstraintKind):
1290    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1293class EncodeColumnConstraint(ColumnConstraintKind):
1294    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1297class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1298    # this: True -> ALWAYS, this: False -> BY DEFAULT
1299    arg_types = {
1300        "this": False,
1301        "expression": False,
1302        "on_null": False,
1303        "start": False,
1304        "increment": False,
1305        "minvalue": False,
1306        "maxvalue": False,
1307        "cycle": False,
1308    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class IndexColumnConstraint(ColumnConstraintKind):
1312class IndexColumnConstraint(ColumnConstraintKind):
1313    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):
1316class InlineLengthColumnConstraint(ColumnConstraintKind):
1317    pass
key = 'inlinelengthcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1320class NotNullColumnConstraint(ColumnConstraintKind):
1321    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1325class OnUpdateColumnConstraint(ColumnConstraintKind):
1326    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1329class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1330    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1333class TitleColumnConstraint(ColumnConstraintKind):
1334    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1337class UniqueColumnConstraint(ColumnConstraintKind):
1338    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1341class UppercaseColumnConstraint(ColumnConstraintKind):
1342    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1345class PathColumnConstraint(ColumnConstraintKind):
1346    pass
key = 'pathcolumnconstraint'
class Constraint(Expression):
1349class Constraint(Expression):
1350    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1353class Delete(Expression):
1354    arg_types = {
1355        "with": False,
1356        "this": False,
1357        "using": False,
1358        "where": False,
1359        "returning": False,
1360        "limit": False,
1361        "tables": False,  # Multiple-Table Syntax (MySQL)
1362    }
1363
1364    def delete(
1365        self,
1366        table: ExpOrStr,
1367        dialect: DialectType = None,
1368        copy: bool = True,
1369        **opts,
1370    ) -> Delete:
1371        """
1372        Create a DELETE expression or replace the table on an existing DELETE expression.
1373
1374        Example:
1375            >>> delete("tbl").sql()
1376            'DELETE FROM tbl'
1377
1378        Args:
1379            table: the table from which to delete.
1380            dialect: the dialect used to parse the input expression.
1381            copy: if `False`, modify this expression instance in-place.
1382            opts: other options to use to parse the input expressions.
1383
1384        Returns:
1385            Delete: the modified expression.
1386        """
1387        return _apply_builder(
1388            expression=table,
1389            instance=self,
1390            arg="this",
1391            dialect=dialect,
1392            into=Table,
1393            copy=copy,
1394            **opts,
1395        )
1396
1397    def where(
1398        self,
1399        *expressions: t.Optional[ExpOrStr],
1400        append: bool = True,
1401        dialect: DialectType = None,
1402        copy: bool = True,
1403        **opts,
1404    ) -> Delete:
1405        """
1406        Append to or set the WHERE expressions.
1407
1408        Example:
1409            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1410            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1411
1412        Args:
1413            *expressions: the SQL code strings to parse.
1414                If an `Expression` instance is passed, it will be used as-is.
1415                Multiple expressions are combined with an AND operator.
1416            append: if `True`, AND the new expressions to any existing expression.
1417                Otherwise, this resets the expression.
1418            dialect: the dialect used to parse the input expressions.
1419            copy: if `False`, modify this expression instance in-place.
1420            opts: other options to use to parse the input expressions.
1421
1422        Returns:
1423            Delete: the modified expression.
1424        """
1425        return _apply_conjunction_builder(
1426            *expressions,
1427            instance=self,
1428            arg="where",
1429            append=append,
1430            into=Where,
1431            dialect=dialect,
1432            copy=copy,
1433            **opts,
1434        )
1435
1436    def returning(
1437        self,
1438        expression: ExpOrStr,
1439        dialect: DialectType = None,
1440        copy: bool = True,
1441        **opts,
1442    ) -> Delete:
1443        """
1444        Set the RETURNING expression. Not supported by all dialects.
1445
1446        Example:
1447            >>> delete("tbl").returning("*", dialect="postgres").sql()
1448            'DELETE FROM tbl RETURNING *'
1449
1450        Args:
1451            expression: the SQL code strings to parse.
1452                If an `Expression` instance is passed, it will be used as-is.
1453            dialect: the dialect used to parse the input expressions.
1454            copy: if `False`, modify this expression instance in-place.
1455            opts: other options to use to parse the input expressions.
1456
1457        Returns:
1458            Delete: the modified expression.
1459        """
1460        return _apply_builder(
1461            expression=expression,
1462            instance=self,
1463            arg="returning",
1464            prefix="RETURNING",
1465            dialect=dialect,
1466            copy=copy,
1467            into=Returning,
1468            **opts,
1469        )
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:
1364    def delete(
1365        self,
1366        table: ExpOrStr,
1367        dialect: DialectType = None,
1368        copy: bool = True,
1369        **opts,
1370    ) -> Delete:
1371        """
1372        Create a DELETE expression or replace the table on an existing DELETE expression.
1373
1374        Example:
1375            >>> delete("tbl").sql()
1376            'DELETE FROM tbl'
1377
1378        Args:
1379            table: the table from which to delete.
1380            dialect: the dialect used to parse the input expression.
1381            copy: if `False`, modify this expression instance in-place.
1382            opts: other options to use to parse the input expressions.
1383
1384        Returns:
1385            Delete: the modified expression.
1386        """
1387        return _apply_builder(
1388            expression=table,
1389            instance=self,
1390            arg="this",
1391            dialect=dialect,
1392            into=Table,
1393            copy=copy,
1394            **opts,
1395        )

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

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:
1436    def returning(
1437        self,
1438        expression: ExpOrStr,
1439        dialect: DialectType = None,
1440        copy: bool = True,
1441        **opts,
1442    ) -> Delete:
1443        """
1444        Set the RETURNING expression. Not supported by all dialects.
1445
1446        Example:
1447            >>> delete("tbl").returning("*", dialect="postgres").sql()
1448            'DELETE FROM tbl RETURNING *'
1449
1450        Args:
1451            expression: the SQL code strings to parse.
1452                If an `Expression` instance is passed, it will be used as-is.
1453            dialect: the dialect used to parse the input expressions.
1454            copy: if `False`, modify this expression instance in-place.
1455            opts: other options to use to parse the input expressions.
1456
1457        Returns:
1458            Delete: the modified expression.
1459        """
1460        return _apply_builder(
1461            expression=expression,
1462            instance=self,
1463            arg="returning",
1464            prefix="RETURNING",
1465            dialect=dialect,
1466            copy=copy,
1467            into=Returning,
1468            **opts,
1469        )

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

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):
1621class OnConflict(Expression):
1622    arg_types = {
1623        "duplicate": False,
1624        "expressions": False,
1625        "nothing": False,
1626        "key": False,
1627        "constraint": False,
1628    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1631class Returning(Expression):
1632    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1636class Introducer(Expression):
1637    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1641class National(Expression):
1642    pass
key = 'national'
class LoadData(Expression):
1645class LoadData(Expression):
1646    arg_types = {
1647        "this": True,
1648        "local": False,
1649        "overwrite": False,
1650        "inpath": True,
1651        "partition": False,
1652        "input_format": False,
1653        "serde": False,
1654    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1657class Partition(Expression):
1658    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1661class Fetch(Expression):
1662    arg_types = {
1663        "direction": False,
1664        "count": False,
1665        "percent": False,
1666        "with_ties": False,
1667    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1670class Group(Expression):
1671    arg_types = {
1672        "expressions": False,
1673        "grouping_sets": False,
1674        "cube": False,
1675        "rollup": False,
1676        "totals": False,
1677        "all": False,
1678    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1681class Lambda(Expression):
1682    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1685class Limit(Expression):
1686    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1689class Literal(Condition):
1690    arg_types = {"this": True, "is_string": True}
1691
1692    @property
1693    def hashable_args(self) -> t.Any:
1694        return (self.this, self.args.get("is_string"))
1695
1696    @classmethod
1697    def number(cls, number) -> Literal:
1698        return cls(this=str(number), is_string=False)
1699
1700    @classmethod
1701    def string(cls, string) -> Literal:
1702        return cls(this=str(string), is_string=True)
1703
1704    @property
1705    def output_name(self) -> str:
1706        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1696    @classmethod
1697    def number(cls, number) -> Literal:
1698        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1700    @classmethod
1701    def string(cls, string) -> Literal:
1702        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):
1709class Join(Expression):
1710    arg_types = {
1711        "this": True,
1712        "on": False,
1713        "side": False,
1714        "kind": False,
1715        "using": False,
1716        "method": False,
1717        "global": False,
1718        "hint": False,
1719    }
1720
1721    @property
1722    def method(self) -> str:
1723        return self.text("method").upper()
1724
1725    @property
1726    def kind(self) -> str:
1727        return self.text("kind").upper()
1728
1729    @property
1730    def side(self) -> str:
1731        return self.text("side").upper()
1732
1733    @property
1734    def hint(self) -> str:
1735        return self.text("hint").upper()
1736
1737    @property
1738    def alias_or_name(self) -> str:
1739        return self.this.alias_or_name
1740
1741    def on(
1742        self,
1743        *expressions: t.Optional[ExpOrStr],
1744        append: bool = True,
1745        dialect: DialectType = None,
1746        copy: bool = True,
1747        **opts,
1748    ) -> Join:
1749        """
1750        Append to or set the ON expressions.
1751
1752        Example:
1753            >>> import sqlglot
1754            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1755            'JOIN x ON y = 1'
1756
1757        Args:
1758            *expressions: the SQL code strings to parse.
1759                If an `Expression` instance is passed, it will be used as-is.
1760                Multiple expressions are combined with an AND operator.
1761            append: if `True`, AND the new expressions to any existing expression.
1762                Otherwise, this resets the expression.
1763            dialect: the dialect used to parse the input expressions.
1764            copy: if `False`, modify this expression instance in-place.
1765            opts: other options to use to parse the input expressions.
1766
1767        Returns:
1768            The modified Join expression.
1769        """
1770        join = _apply_conjunction_builder(
1771            *expressions,
1772            instance=self,
1773            arg="on",
1774            append=append,
1775            dialect=dialect,
1776            copy=copy,
1777            **opts,
1778        )
1779
1780        if join.kind == "CROSS":
1781            join.set("kind", None)
1782
1783        return join
1784
1785    def using(
1786        self,
1787        *expressions: t.Optional[ExpOrStr],
1788        append: bool = True,
1789        dialect: DialectType = None,
1790        copy: bool = True,
1791        **opts,
1792    ) -> Join:
1793        """
1794        Append to or set the USING expressions.
1795
1796        Example:
1797            >>> import sqlglot
1798            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1799            'JOIN x USING (foo, bla)'
1800
1801        Args:
1802            *expressions: the SQL code strings to parse.
1803                If an `Expression` instance is passed, it will be used as-is.
1804            append: if `True`, concatenate the new expressions to the existing "using" list.
1805                Otherwise, this resets the expression.
1806            dialect: the dialect used to parse the input expressions.
1807            copy: if `False`, modify this expression instance in-place.
1808            opts: other options to use to parse the input expressions.
1809
1810        Returns:
1811            The modified Join expression.
1812        """
1813        join = _apply_list_builder(
1814            *expressions,
1815            instance=self,
1816            arg="using",
1817            append=append,
1818            dialect=dialect,
1819            copy=copy,
1820            **opts,
1821        )
1822
1823        if join.kind == "CROSS":
1824            join.set("kind", None)
1825
1826        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:
1741    def on(
1742        self,
1743        *expressions: t.Optional[ExpOrStr],
1744        append: bool = True,
1745        dialect: DialectType = None,
1746        copy: bool = True,
1747        **opts,
1748    ) -> Join:
1749        """
1750        Append to or set the ON expressions.
1751
1752        Example:
1753            >>> import sqlglot
1754            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1755            'JOIN x ON y = 1'
1756
1757        Args:
1758            *expressions: the SQL code strings to parse.
1759                If an `Expression` instance is passed, it will be used as-is.
1760                Multiple expressions are combined with an AND operator.
1761            append: if `True`, AND the new expressions to any existing expression.
1762                Otherwise, this resets the expression.
1763            dialect: the dialect used to parse the input expressions.
1764            copy: if `False`, modify this expression instance in-place.
1765            opts: other options to use to parse the input expressions.
1766
1767        Returns:
1768            The modified Join expression.
1769        """
1770        join = _apply_conjunction_builder(
1771            *expressions,
1772            instance=self,
1773            arg="on",
1774            append=append,
1775            dialect=dialect,
1776            copy=copy,
1777            **opts,
1778        )
1779
1780        if join.kind == "CROSS":
1781            join.set("kind", None)
1782
1783        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:
1785    def using(
1786        self,
1787        *expressions: t.Optional[ExpOrStr],
1788        append: bool = True,
1789        dialect: DialectType = None,
1790        copy: bool = True,
1791        **opts,
1792    ) -> Join:
1793        """
1794        Append to or set the USING expressions.
1795
1796        Example:
1797            >>> import sqlglot
1798            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1799            'JOIN x USING (foo, bla)'
1800
1801        Args:
1802            *expressions: the SQL code strings to parse.
1803                If an `Expression` instance is passed, it will be used as-is.
1804            append: if `True`, concatenate the new expressions to the existing "using" list.
1805                Otherwise, this resets the expression.
1806            dialect: the dialect used to parse the input expressions.
1807            copy: if `False`, modify this expression instance in-place.
1808            opts: other options to use to parse the input expressions.
1809
1810        Returns:
1811            The modified Join expression.
1812        """
1813        join = _apply_list_builder(
1814            *expressions,
1815            instance=self,
1816            arg="using",
1817            append=append,
1818            dialect=dialect,
1819            copy=copy,
1820            **opts,
1821        )
1822
1823        if join.kind == "CROSS":
1824            join.set("kind", None)
1825
1826        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):
1829class Lateral(UDTF):
1830    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):
1833class MatchRecognize(Expression):
1834    arg_types = {
1835        "partition_by": False,
1836        "order": False,
1837        "measures": False,
1838        "rows": False,
1839        "after": False,
1840        "pattern": False,
1841        "define": False,
1842        "alias": False,
1843    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1848class Final(Expression):
1849    pass
key = 'final'
class Offset(Expression):
1852class Offset(Expression):
1853    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1856class Order(Expression):
1857    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1862class Cluster(Order):
1863    pass
key = 'cluster'
class Distribute(Order):
1866class Distribute(Order):
1867    pass
key = 'distribute'
class Sort(Order):
1870class Sort(Order):
1871    pass
key = 'sort'
class Ordered(Expression):
1874class Ordered(Expression):
1875    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1878class Property(Expression):
1879    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1882class AlgorithmProperty(Property):
1883    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1886class AutoIncrementProperty(Property):
1887    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1890class BlockCompressionProperty(Property):
1891    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):
1894class CharacterSetProperty(Property):
1895    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1898class ChecksumProperty(Property):
1899    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1902class CollateProperty(Property):
1903    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1906class CopyGrantsProperty(Property):
1907    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1910class DataBlocksizeProperty(Property):
1911    arg_types = {
1912        "size": False,
1913        "units": False,
1914        "minimum": False,
1915        "maximum": False,
1916        "default": False,
1917    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1920class DefinerProperty(Property):
1921    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1924class DistKeyProperty(Property):
1925    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1928class DistStyleProperty(Property):
1929    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1932class EngineProperty(Property):
1933    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
1936class HeapProperty(Property):
1937    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
1940class ToTableProperty(Property):
1941    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1944class ExecuteAsProperty(Property):
1945    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1948class ExternalProperty(Property):
1949    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1952class FallbackProperty(Property):
1953    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1956class FileFormatProperty(Property):
1957    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1960class FreespaceProperty(Property):
1961    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1964class InputOutputFormat(Expression):
1965    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1968class IsolatedLoadingProperty(Property):
1969    arg_types = {
1970        "no": True,
1971        "concurrent": True,
1972        "for_all": True,
1973        "for_insert": True,
1974        "for_none": True,
1975    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1978class JournalProperty(Property):
1979    arg_types = {
1980        "no": False,
1981        "dual": False,
1982        "before": False,
1983        "local": False,
1984        "after": False,
1985    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1988class LanguageProperty(Property):
1989    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1993class ClusteredByProperty(Property):
1994    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1997class DictProperty(Property):
1998    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2001class DictSubProperty(Property):
2002    pass
key = 'dictsubproperty'
class DictRange(Property):
2005class DictRange(Property):
2006    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2011class OnCluster(Property):
2012    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2015class LikeProperty(Property):
2016    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2019class LocationProperty(Property):
2020    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2023class LockingProperty(Property):
2024    arg_types = {
2025        "this": False,
2026        "kind": True,
2027        "for_or_in": True,
2028        "lock_type": True,
2029        "override": False,
2030    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2033class LogProperty(Property):
2034    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2037class MaterializedProperty(Property):
2038    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2041class MergeBlockRatioProperty(Property):
2042    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):
2045class NoPrimaryIndexProperty(Property):
2046    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
2049class OnCommitProperty(Property):
2050    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2053class PartitionedByProperty(Property):
2054    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2057class ReturnsProperty(Property):
2058    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2061class RowFormatProperty(Property):
2062    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2065class RowFormatDelimitedProperty(Property):
2066    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2067    arg_types = {
2068        "fields": False,
2069        "escaped": False,
2070        "collection_items": False,
2071        "map_keys": False,
2072        "lines": False,
2073        "null": False,
2074        "serde": False,
2075    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2078class RowFormatSerdeProperty(Property):
2079    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2083class QueryTransform(Expression):
2084    arg_types = {
2085        "expressions": True,
2086        "command_script": True,
2087        "schema": False,
2088        "row_format_before": False,
2089        "record_writer": False,
2090        "row_format_after": False,
2091        "record_reader": False,
2092    }
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):
2095class SchemaCommentProperty(Property):
2096    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2099class SerdeProperties(Property):
2100    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2103class SetProperty(Property):
2104    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2107class SettingsProperty(Property):
2108    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2111class SortKeyProperty(Property):
2112    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2115class SqlSecurityProperty(Property):
2116    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2119class StabilityProperty(Property):
2120    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2123class TemporaryProperty(Property):
2124    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2127class TransientProperty(Property):
2128    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2131class VolatileProperty(Property):
2132    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2135class WithDataProperty(Property):
2136    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2139class WithJournalTableProperty(Property):
2140    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2143class Properties(Expression):
2144    arg_types = {"expressions": True}
2145
2146    NAME_TO_PROPERTY = {
2147        "ALGORITHM": AlgorithmProperty,
2148        "AUTO_INCREMENT": AutoIncrementProperty,
2149        "CHARACTER SET": CharacterSetProperty,
2150        "CLUSTERED_BY": ClusteredByProperty,
2151        "COLLATE": CollateProperty,
2152        "COMMENT": SchemaCommentProperty,
2153        "DEFINER": DefinerProperty,
2154        "DISTKEY": DistKeyProperty,
2155        "DISTSTYLE": DistStyleProperty,
2156        "ENGINE": EngineProperty,
2157        "EXECUTE AS": ExecuteAsProperty,
2158        "FORMAT": FileFormatProperty,
2159        "LANGUAGE": LanguageProperty,
2160        "LOCATION": LocationProperty,
2161        "PARTITIONED_BY": PartitionedByProperty,
2162        "RETURNS": ReturnsProperty,
2163        "ROW_FORMAT": RowFormatProperty,
2164        "SORTKEY": SortKeyProperty,
2165    }
2166
2167    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2168
2169    # CREATE property locations
2170    # Form: schema specified
2171    #   create [POST_CREATE]
2172    #     table a [POST_NAME]
2173    #     (b int) [POST_SCHEMA]
2174    #     with ([POST_WITH])
2175    #     index (b) [POST_INDEX]
2176    #
2177    # Form: alias selection
2178    #   create [POST_CREATE]
2179    #     table a [POST_NAME]
2180    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2181    #     index (c) [POST_INDEX]
2182    class Location(AutoName):
2183        POST_CREATE = auto()
2184        POST_NAME = auto()
2185        POST_SCHEMA = auto()
2186        POST_WITH = auto()
2187        POST_ALIAS = auto()
2188        POST_EXPRESSION = auto()
2189        POST_INDEX = auto()
2190        UNSUPPORTED = auto()
2191
2192    @classmethod
2193    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2194        expressions = []
2195        for key, value in properties_dict.items():
2196            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2197            if property_cls:
2198                expressions.append(property_cls(this=convert(value)))
2199            else:
2200                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2201
2202        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:
2192    @classmethod
2193    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2194        expressions = []
2195        for key, value in properties_dict.items():
2196            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2197            if property_cls:
2198                expressions.append(property_cls(this=convert(value)))
2199            else:
2200                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2201
2202        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2182    class Location(AutoName):
2183        POST_CREATE = auto()
2184        POST_NAME = auto()
2185        POST_SCHEMA = auto()
2186        POST_WITH = auto()
2187        POST_ALIAS = auto()
2188        POST_EXPRESSION = auto()
2189        POST_INDEX = auto()
2190        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):
2205class Qualify(Expression):
2206    pass
key = 'qualify'
class Return(Expression):
2210class Return(Expression):
2211    pass
key = 'return'
class Reference(Expression):
2214class Reference(Expression):
2215    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2218class Tuple(Expression):
2219    arg_types = {"expressions": False}
2220
2221    def isin(
2222        self,
2223        *expressions: t.Any,
2224        query: t.Optional[ExpOrStr] = None,
2225        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2226        copy: bool = True,
2227        **opts,
2228    ) -> In:
2229        return In(
2230            this=maybe_copy(self, copy),
2231            expressions=[convert(e, copy=copy) for e in expressions],
2232            query=maybe_parse(query, copy=copy, **opts) if query else None,
2233            unnest=Unnest(
2234                expressions=[
2235                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2236                ]
2237            )
2238            if unnest
2239            else None,
2240        )
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:
2221    def isin(
2222        self,
2223        *expressions: t.Any,
2224        query: t.Optional[ExpOrStr] = None,
2225        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2226        copy: bool = True,
2227        **opts,
2228    ) -> In:
2229        return In(
2230            this=maybe_copy(self, copy),
2231            expressions=[convert(e, copy=copy) for e in expressions],
2232            query=maybe_parse(query, copy=copy, **opts) if query else None,
2233            unnest=Unnest(
2234                expressions=[
2235                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2236                ]
2237            )
2238            if unnest
2239            else None,
2240        )
key = 'tuple'
class Subqueryable(Unionable):
2243class Subqueryable(Unionable):
2244    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2245        """
2246        Convert this expression to an aliased expression that can be used as a Subquery.
2247
2248        Example:
2249            >>> subquery = Select().select("x").from_("tbl").subquery()
2250            >>> Select().select("x").from_(subquery).sql()
2251            'SELECT x FROM (SELECT x FROM tbl)'
2252
2253        Args:
2254            alias (str | Identifier): an optional alias for the subquery
2255            copy (bool): if `False`, modify this expression instance in-place.
2256
2257        Returns:
2258            Alias: the subquery
2259        """
2260        instance = maybe_copy(self, copy)
2261        if not isinstance(alias, Expression):
2262            alias = TableAlias(this=to_identifier(alias)) if alias else None
2263
2264        return Subquery(this=instance, alias=alias)
2265
2266    def limit(
2267        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2268    ) -> Select:
2269        raise NotImplementedError
2270
2271    @property
2272    def ctes(self):
2273        with_ = self.args.get("with")
2274        if not with_:
2275            return []
2276        return with_.expressions
2277
2278    @property
2279    def selects(self) -> t.List[Expression]:
2280        raise NotImplementedError("Subqueryable objects must implement `selects`")
2281
2282    @property
2283    def named_selects(self) -> t.List[str]:
2284        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2285
2286    def with_(
2287        self,
2288        alias: ExpOrStr,
2289        as_: ExpOrStr,
2290        recursive: t.Optional[bool] = None,
2291        append: bool = True,
2292        dialect: DialectType = None,
2293        copy: bool = True,
2294        **opts,
2295    ) -> Subqueryable:
2296        """
2297        Append to or set the common table expressions.
2298
2299        Example:
2300            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2301            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2302
2303        Args:
2304            alias: the SQL code string to parse as the table name.
2305                If an `Expression` instance is passed, this is used as-is.
2306            as_: the SQL code string to parse as the table expression.
2307                If an `Expression` instance is passed, it will be used as-is.
2308            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2309            append: if `True`, add to any existing expressions.
2310                Otherwise, this resets the expressions.
2311            dialect: the dialect used to parse the input expression.
2312            copy: if `False`, modify this expression instance in-place.
2313            opts: other options to use to parse the input expressions.
2314
2315        Returns:
2316            The modified expression.
2317        """
2318        return _apply_cte_builder(
2319            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2320        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2244    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2245        """
2246        Convert this expression to an aliased expression that can be used as a Subquery.
2247
2248        Example:
2249            >>> subquery = Select().select("x").from_("tbl").subquery()
2250            >>> Select().select("x").from_(subquery).sql()
2251            'SELECT x FROM (SELECT x FROM tbl)'
2252
2253        Args:
2254            alias (str | Identifier): an optional alias for the subquery
2255            copy (bool): if `False`, modify this expression instance in-place.
2256
2257        Returns:
2258            Alias: the subquery
2259        """
2260        instance = maybe_copy(self, copy)
2261        if not isinstance(alias, Expression):
2262            alias = TableAlias(this=to_identifier(alias)) if alias else None
2263
2264        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:
2266    def limit(
2267        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2268    ) -> Select:
2269        raise NotImplementedError
ctes
named_selects: List[str]
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Subqueryable:
2286    def with_(
2287        self,
2288        alias: ExpOrStr,
2289        as_: ExpOrStr,
2290        recursive: t.Optional[bool] = None,
2291        append: bool = True,
2292        dialect: DialectType = None,
2293        copy: bool = True,
2294        **opts,
2295    ) -> Subqueryable:
2296        """
2297        Append to or set the common table expressions.
2298
2299        Example:
2300            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2301            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2302
2303        Args:
2304            alias: the SQL code string to parse as the table name.
2305                If an `Expression` instance is passed, this is used as-is.
2306            as_: the SQL code string to parse as the table expression.
2307                If an `Expression` instance is passed, it will be used as-is.
2308            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2309            append: if `True`, add to any existing expressions.
2310                Otherwise, this resets the expressions.
2311            dialect: the dialect used to parse the input expression.
2312            copy: if `False`, modify this expression instance in-place.
2313            opts: other options to use to parse the input expressions.
2314
2315        Returns:
2316            The modified expression.
2317        """
2318        return _apply_cte_builder(
2319            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2320        )

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):
2347class WithTableHint(Expression):
2348    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2352class IndexTableHint(Expression):
2353    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2356class Table(Expression):
2357    arg_types = {
2358        "this": True,
2359        "alias": False,
2360        "db": False,
2361        "catalog": False,
2362        "laterals": False,
2363        "joins": False,
2364        "pivots": False,
2365        "hints": False,
2366        "system_time": False,
2367    }
2368
2369    @property
2370    def name(self) -> str:
2371        if isinstance(self.this, Func):
2372            return ""
2373        return self.this.name
2374
2375    @property
2376    def db(self) -> str:
2377        return self.text("db")
2378
2379    @property
2380    def catalog(self) -> str:
2381        return self.text("catalog")
2382
2383    @property
2384    def selects(self) -> t.List[Expression]:
2385        return []
2386
2387    @property
2388    def named_selects(self) -> t.List[str]:
2389        return []
2390
2391    @property
2392    def parts(self) -> t.List[Identifier]:
2393        """Return the parts of a table in order catalog, db, table."""
2394        parts: t.List[Identifier] = []
2395
2396        for arg in ("catalog", "db", "this"):
2397            part = self.args.get(arg)
2398
2399            if isinstance(part, Identifier):
2400                parts.append(part)
2401            elif isinstance(part, Dot):
2402                parts.extend(part.flatten())
2403
2404        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):
2408class SystemTime(Expression):
2409    arg_types = {
2410        "this": False,
2411        "expression": False,
2412        "kind": True,
2413    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2416class Union(Subqueryable):
2417    arg_types = {
2418        "with": False,
2419        "this": True,
2420        "expression": True,
2421        "distinct": False,
2422        **QUERY_MODIFIERS,
2423    }
2424
2425    def limit(
2426        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2427    ) -> Select:
2428        """
2429        Set the LIMIT expression.
2430
2431        Example:
2432            >>> select("1").union(select("1")).limit(1).sql()
2433            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2434
2435        Args:
2436            expression: the SQL code string to parse.
2437                This can also be an integer.
2438                If a `Limit` instance is passed, this is used as-is.
2439                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2440            dialect: the dialect used to parse the input expression.
2441            copy: if `False`, modify this expression instance in-place.
2442            opts: other options to use to parse the input expressions.
2443
2444        Returns:
2445            The limited subqueryable.
2446        """
2447        return (
2448            select("*")
2449            .from_(self.subquery(alias="_l_0", copy=copy))
2450            .limit(expression, dialect=dialect, copy=False, **opts)
2451        )
2452
2453    def select(
2454        self,
2455        *expressions: t.Optional[ExpOrStr],
2456        append: bool = True,
2457        dialect: DialectType = None,
2458        copy: bool = True,
2459        **opts,
2460    ) -> Union:
2461        """Append to or set the SELECT of the union recursively.
2462
2463        Example:
2464            >>> from sqlglot import parse_one
2465            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2466            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2467
2468        Args:
2469            *expressions: the SQL code strings to parse.
2470                If an `Expression` instance is passed, it will be used as-is.
2471            append: if `True`, add to any existing expressions.
2472                Otherwise, this resets the expressions.
2473            dialect: the dialect used to parse the input expressions.
2474            copy: if `False`, modify this expression instance in-place.
2475            opts: other options to use to parse the input expressions.
2476
2477        Returns:
2478            Union: the modified expression.
2479        """
2480        this = self.copy() if copy else self
2481        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2482        this.expression.unnest().select(
2483            *expressions, append=append, dialect=dialect, copy=False, **opts
2484        )
2485        return this
2486
2487    @property
2488    def named_selects(self) -> t.List[str]:
2489        return self.this.unnest().named_selects
2490
2491    @property
2492    def is_star(self) -> bool:
2493        return self.this.is_star or self.expression.is_star
2494
2495    @property
2496    def selects(self) -> t.List[Expression]:
2497        return self.this.unnest().selects
2498
2499    @property
2500    def left(self):
2501        return self.this
2502
2503    @property
2504    def right(self):
2505        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:
2425    def limit(
2426        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2427    ) -> Select:
2428        """
2429        Set the LIMIT expression.
2430
2431        Example:
2432            >>> select("1").union(select("1")).limit(1).sql()
2433            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2434
2435        Args:
2436            expression: the SQL code string to parse.
2437                This can also be an integer.
2438                If a `Limit` instance is passed, this is used as-is.
2439                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2440            dialect: the dialect used to parse the input expression.
2441            copy: if `False`, modify this expression instance in-place.
2442            opts: other options to use to parse the input expressions.
2443
2444        Returns:
2445            The limited subqueryable.
2446        """
2447        return (
2448            select("*")
2449            .from_(self.subquery(alias="_l_0", copy=copy))
2450            .limit(expression, dialect=dialect, copy=False, **opts)
2451        )

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

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

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

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

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

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:
2767    def limit(
2768        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2769    ) -> Select:
2770        """
2771        Set the LIMIT expression.
2772
2773        Example:
2774            >>> Select().from_("tbl").select("x").limit(10).sql()
2775            'SELECT x FROM tbl LIMIT 10'
2776
2777        Args:
2778            expression: the SQL code string to parse.
2779                This can also be an integer.
2780                If a `Limit` instance is passed, this is used as-is.
2781                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2782            dialect: the dialect used to parse the input expression.
2783            copy: if `False`, modify this expression instance in-place.
2784            opts: other options to use to parse the input expressions.
2785
2786        Returns:
2787            Select: the modified expression.
2788        """
2789        return _apply_builder(
2790            expression=expression,
2791            instance=self,
2792            arg="limit",
2793            into=Limit,
2794            prefix="LIMIT",
2795            dialect=dialect,
2796            copy=copy,
2797            **opts,
2798        )

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

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:
2833    def select(
2834        self,
2835        *expressions: t.Optional[ExpOrStr],
2836        append: bool = True,
2837        dialect: DialectType = None,
2838        copy: bool = True,
2839        **opts,
2840    ) -> Select:
2841        """
2842        Append to or set the SELECT expressions.
2843
2844        Example:
2845            >>> Select().select("x", "y").sql()
2846            'SELECT x, y'
2847
2848        Args:
2849            *expressions: the SQL code strings to parse.
2850                If an `Expression` instance is passed, it will be used as-is.
2851            append: if `True`, add to any existing expressions.
2852                Otherwise, this resets the expressions.
2853            dialect: the dialect used to parse the input expressions.
2854            copy: if `False`, modify this expression instance in-place.
2855            opts: other options to use to parse the input expressions.
2856
2857        Returns:
2858            The modified Select expression.
2859        """
2860        return _apply_list_builder(
2861            *expressions,
2862            instance=self,
2863            arg="expressions",
2864            append=append,
2865            dialect=dialect,
2866            copy=copy,
2867            **opts,
2868        )

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:
2870    def lateral(
2871        self,
2872        *expressions: t.Optional[ExpOrStr],
2873        append: bool = True,
2874        dialect: DialectType = None,
2875        copy: bool = True,
2876        **opts,
2877    ) -> Select:
2878        """
2879        Append to or set the LATERAL expressions.
2880
2881        Example:
2882            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2883            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2884
2885        Args:
2886            *expressions: the SQL code strings to parse.
2887                If an `Expression` instance is passed, it will be used as-is.
2888            append: if `True`, add to any existing expressions.
2889                Otherwise, this resets the expressions.
2890            dialect: the dialect used to parse the input expressions.
2891            copy: if `False`, modify this expression instance in-place.
2892            opts: other options to use to parse the input expressions.
2893
2894        Returns:
2895            The modified Select expression.
2896        """
2897        return _apply_list_builder(
2898            *expressions,
2899            instance=self,
2900            arg="laterals",
2901            append=append,
2902            into=Lateral,
2903            prefix="LATERAL VIEW",
2904            dialect=dialect,
2905            copy=copy,
2906            **opts,
2907        )

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:
2909    def join(
2910        self,
2911        expression: ExpOrStr,
2912        on: t.Optional[ExpOrStr] = None,
2913        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
2914        append: bool = True,
2915        join_type: t.Optional[str] = None,
2916        join_alias: t.Optional[Identifier | str] = None,
2917        dialect: DialectType = None,
2918        copy: bool = True,
2919        **opts,
2920    ) -> Select:
2921        """
2922        Append to or set the JOIN expressions.
2923
2924        Example:
2925            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2926            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2927
2928            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2929            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2930
2931            Use `join_type` to change the type of join:
2932
2933            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2934            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2935
2936        Args:
2937            expression: the SQL code string to parse.
2938                If an `Expression` instance is passed, it will be used as-is.
2939            on: optionally specify the join "on" criteria as a SQL string.
2940                If an `Expression` instance is passed, it will be used as-is.
2941            using: optionally specify the join "using" criteria as a SQL string.
2942                If an `Expression` instance is passed, it will be used as-is.
2943            append: if `True`, add to any existing expressions.
2944                Otherwise, this resets the expressions.
2945            join_type: if set, alter the parsed join type.
2946            join_alias: an optional alias for the joined source.
2947            dialect: the dialect used to parse the input expressions.
2948            copy: if `False`, modify this expression instance in-place.
2949            opts: other options to use to parse the input expressions.
2950
2951        Returns:
2952            Select: the modified expression.
2953        """
2954        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2955
2956        try:
2957            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2958        except ParseError:
2959            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2960
2961        join = expression if isinstance(expression, Join) else Join(this=expression)
2962
2963        if isinstance(join.this, Select):
2964            join.this.replace(join.this.subquery())
2965
2966        if join_type:
2967            method: t.Optional[Token]
2968            side: t.Optional[Token]
2969            kind: t.Optional[Token]
2970
2971            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2972
2973            if method:
2974                join.set("method", method.text)
2975            if side:
2976                join.set("side", side.text)
2977            if kind:
2978                join.set("kind", kind.text)
2979
2980        if on:
2981            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2982            join.set("on", on)
2983
2984        if using:
2985            join = _apply_list_builder(
2986                *ensure_list(using),
2987                instance=join,
2988                arg="using",
2989                append=append,
2990                copy=copy,
2991                into=Identifier,
2992                **opts,
2993            )
2994
2995        if join_alias:
2996            join.set("this", alias_(join.this, join_alias, table=True))
2997
2998        return _apply_list_builder(
2999            join,
3000            instance=self,
3001            arg="joins",
3002            append=append,
3003            copy=copy,
3004            **opts,
3005        )

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:
3007    def where(
3008        self,
3009        *expressions: t.Optional[ExpOrStr],
3010        append: bool = True,
3011        dialect: DialectType = None,
3012        copy: bool = True,
3013        **opts,
3014    ) -> Select:
3015        """
3016        Append to or set the WHERE expressions.
3017
3018        Example:
3019            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3020            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3021
3022        Args:
3023            *expressions: the SQL code strings to parse.
3024                If an `Expression` instance is passed, it will be used as-is.
3025                Multiple expressions are combined with an AND operator.
3026            append: if `True`, AND the new expressions to any existing expression.
3027                Otherwise, this resets the expression.
3028            dialect: the dialect used to parse the input expressions.
3029            copy: if `False`, modify this expression instance in-place.
3030            opts: other options to use to parse the input expressions.
3031
3032        Returns:
3033            Select: the modified expression.
3034        """
3035        return _apply_conjunction_builder(
3036            *expressions,
3037            instance=self,
3038            arg="where",
3039            append=append,
3040            into=Where,
3041            dialect=dialect,
3042            copy=copy,
3043            **opts,
3044        )

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:
3046    def having(
3047        self,
3048        *expressions: t.Optional[ExpOrStr],
3049        append: bool = True,
3050        dialect: DialectType = None,
3051        copy: bool = True,
3052        **opts,
3053    ) -> Select:
3054        """
3055        Append to or set the HAVING expressions.
3056
3057        Example:
3058            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3059            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3060
3061        Args:
3062            *expressions: the SQL code strings to parse.
3063                If an `Expression` instance is passed, it will be used as-is.
3064                Multiple expressions are combined with an AND operator.
3065            append: if `True`, AND the new expressions to any existing expression.
3066                Otherwise, this resets the expression.
3067            dialect: the dialect used to parse the input expressions.
3068            copy: if `False`, modify this expression instance in-place.
3069            opts: other options to use to parse the input expressions.
3070
3071        Returns:
3072            The modified Select expression.
3073        """
3074        return _apply_conjunction_builder(
3075            *expressions,
3076            instance=self,
3077            arg="having",
3078            append=append,
3079            into=Having,
3080            dialect=dialect,
3081            copy=copy,
3082            **opts,
3083        )

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:
3085    def window(
3086        self,
3087        *expressions: t.Optional[ExpOrStr],
3088        append: bool = True,
3089        dialect: DialectType = None,
3090        copy: bool = True,
3091        **opts,
3092    ) -> Select:
3093        return _apply_list_builder(
3094            *expressions,
3095            instance=self,
3096            arg="windows",
3097            append=append,
3098            into=Window,
3099            dialect=dialect,
3100            copy=copy,
3101            **opts,
3102        )
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:
3104    def qualify(
3105        self,
3106        *expressions: t.Optional[ExpOrStr],
3107        append: bool = True,
3108        dialect: DialectType = None,
3109        copy: bool = True,
3110        **opts,
3111    ) -> Select:
3112        return _apply_conjunction_builder(
3113            *expressions,
3114            instance=self,
3115            arg="qualify",
3116            append=append,
3117            into=Qualify,
3118            dialect=dialect,
3119            copy=copy,
3120            **opts,
3121        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3123    def distinct(
3124        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3125    ) -> Select:
3126        """
3127        Set the OFFSET expression.
3128
3129        Example:
3130            >>> Select().from_("tbl").select("x").distinct().sql()
3131            'SELECT DISTINCT x FROM tbl'
3132
3133        Args:
3134            ons: the expressions to distinct on
3135            distinct: whether the Select should be distinct
3136            copy: if `False`, modify this expression instance in-place.
3137
3138        Returns:
3139            Select: the modified expression.
3140        """
3141        instance = maybe_copy(self, copy)
3142        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3143        instance.set("distinct", Distinct(on=on) if distinct else None)
3144        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:
3146    def ctas(
3147        self,
3148        table: ExpOrStr,
3149        properties: t.Optional[t.Dict] = None,
3150        dialect: DialectType = None,
3151        copy: bool = True,
3152        **opts,
3153    ) -> Create:
3154        """
3155        Convert this expression to a CREATE TABLE AS statement.
3156
3157        Example:
3158            >>> Select().select("*").from_("tbl").ctas("x").sql()
3159            'CREATE TABLE x AS SELECT * FROM tbl'
3160
3161        Args:
3162            table: the SQL code string to parse as the table name.
3163                If another `Expression` instance is passed, it will be used as-is.
3164            properties: an optional mapping of table properties
3165            dialect: the dialect used to parse the input table.
3166            copy: if `False`, modify this expression instance in-place.
3167            opts: other options to use to parse the input table.
3168
3169        Returns:
3170            The new Create expression.
3171        """
3172        instance = maybe_copy(self, copy)
3173        table_expression = maybe_parse(
3174            table,
3175            into=Table,
3176            dialect=dialect,
3177            **opts,
3178        )
3179        properties_expression = None
3180        if properties:
3181            properties_expression = Properties.from_dict(properties)
3182
3183        return Create(
3184            this=table_expression,
3185            kind="table",
3186            expression=instance,
3187            properties=properties_expression,
3188        )

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:
3190    def lock(self, update: bool = True, copy: bool = True) -> Select:
3191        """
3192        Set the locking read mode for this expression.
3193
3194        Examples:
3195            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3196            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3197
3198            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3199            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3200
3201        Args:
3202            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3203            copy: if `False`, modify this expression instance in-place.
3204
3205        Returns:
3206            The modified expression.
3207        """
3208        inst = maybe_copy(self, copy)
3209        inst.set("locks", [Lock(update=update)])
3210
3211        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:
3213    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3214        """
3215        Set hints for this expression.
3216
3217        Examples:
3218            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3219            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3220
3221        Args:
3222            hints: The SQL code strings to parse as the hints.
3223                If an `Expression` instance is passed, it will be used as-is.
3224            dialect: The dialect used to parse the hints.
3225            copy: If `False`, modify this expression instance in-place.
3226
3227        Returns:
3228            The modified expression.
3229        """
3230        inst = maybe_copy(self, copy)
3231        inst.set(
3232            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3233        )
3234
3235        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):
3250class Subquery(DerivedTable, Unionable):
3251    arg_types = {
3252        "this": True,
3253        "alias": False,
3254        "with": False,
3255        **QUERY_MODIFIERS,
3256    }
3257
3258    def unnest(self):
3259        """
3260        Returns the first non subquery.
3261        """
3262        expression = self
3263        while isinstance(expression, Subquery):
3264            expression = expression.this
3265        return expression
3266
3267    @property
3268    def is_star(self) -> bool:
3269        return self.this.is_star
3270
3271    @property
3272    def output_name(self) -> str:
3273        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):
3258    def unnest(self):
3259        """
3260        Returns the first non subquery.
3261        """
3262        expression = self
3263        while isinstance(expression, Subquery):
3264            expression = expression.this
3265        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'subquery'
class TableSample(Expression):
3276class TableSample(Expression):
3277    arg_types = {
3278        "this": False,
3279        "method": False,
3280        "bucket_numerator": False,
3281        "bucket_denominator": False,
3282        "bucket_field": False,
3283        "percent": False,
3284        "rows": False,
3285        "size": False,
3286        "seed": False,
3287        "kind": False,
3288    }
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):
3291class Tag(Expression):
3292    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3293
3294    arg_types = {
3295        "this": False,
3296        "prefix": False,
3297        "postfix": False,
3298    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3303class Pivot(Expression):
3304    arg_types = {
3305        "this": False,
3306        "alias": False,
3307        "expressions": True,
3308        "field": False,
3309        "unpivot": False,
3310        "using": False,
3311        "group": False,
3312        "columns": False,
3313    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3316class Window(Expression):
3317    arg_types = {
3318        "this": True,
3319        "partition_by": False,
3320        "order": False,
3321        "spec": False,
3322        "alias": False,
3323        "over": False,
3324        "first": False,
3325    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3328class WindowSpec(Expression):
3329    arg_types = {
3330        "kind": False,
3331        "start": False,
3332        "start_side": False,
3333        "end": False,
3334        "end_side": False,
3335    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3338class Where(Expression):
3339    pass
key = 'where'
class Star(Expression):
3342class Star(Expression):
3343    arg_types = {"except": False, "replace": False}
3344
3345    @property
3346    def name(self) -> str:
3347        return "*"
3348
3349    @property
3350    def output_name(self) -> str:
3351        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):
3354class Parameter(Condition):
3355    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3358class SessionParameter(Condition):
3359    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3362class Placeholder(Condition):
3363    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3366class Null(Condition):
3367    arg_types: t.Dict[str, t.Any] = {}
3368
3369    @property
3370    def name(self) -> str:
3371        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3374class Boolean(Condition):
3375    pass
key = 'boolean'
class DataTypeSize(Expression):
3378class DataTypeSize(Expression):
3379    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3382class DataType(Expression):
3383    arg_types = {
3384        "this": True,
3385        "expressions": False,
3386        "nested": False,
3387        "values": False,
3388        "prefix": False,
3389    }
3390
3391    class Type(AutoName):
3392        ARRAY = auto()
3393        BIGDECIMAL = auto()
3394        BIGINT = auto()
3395        BIGSERIAL = auto()
3396        BINARY = auto()
3397        BIT = auto()
3398        BOOLEAN = auto()
3399        CHAR = auto()
3400        DATE = auto()
3401        DATETIME = auto()
3402        DATETIME64 = auto()
3403        ENUM = auto()
3404        INT4RANGE = auto()
3405        INT4MULTIRANGE = auto()
3406        INT8RANGE = auto()
3407        INT8MULTIRANGE = auto()
3408        NUMRANGE = auto()
3409        NUMMULTIRANGE = auto()
3410        TSRANGE = auto()
3411        TSMULTIRANGE = auto()
3412        TSTZRANGE = auto()
3413        TSTZMULTIRANGE = auto()
3414        DATERANGE = auto()
3415        DATEMULTIRANGE = auto()
3416        DECIMAL = auto()
3417        DOUBLE = auto()
3418        FLOAT = auto()
3419        GEOGRAPHY = auto()
3420        GEOMETRY = auto()
3421        HLLSKETCH = auto()
3422        HSTORE = auto()
3423        IMAGE = auto()
3424        INET = auto()
3425        IPADDRESS = auto()
3426        IPPREFIX = auto()
3427        INT = auto()
3428        INT128 = auto()
3429        INT256 = auto()
3430        INTERVAL = auto()
3431        JSON = auto()
3432        JSONB = auto()
3433        LONGBLOB = auto()
3434        LONGTEXT = auto()
3435        MAP = auto()
3436        MEDIUMBLOB = auto()
3437        MEDIUMTEXT = auto()
3438        MONEY = auto()
3439        NCHAR = auto()
3440        NULL = auto()
3441        NULLABLE = auto()
3442        NVARCHAR = auto()
3443        OBJECT = auto()
3444        ROWVERSION = auto()
3445        SERIAL = auto()
3446        SET = auto()
3447        SMALLINT = auto()
3448        SMALLMONEY = auto()
3449        SMALLSERIAL = auto()
3450        STRUCT = auto()
3451        SUPER = auto()
3452        TEXT = auto()
3453        TIME = auto()
3454        TIMESTAMP = auto()
3455        TIMESTAMPTZ = auto()
3456        TIMESTAMPLTZ = auto()
3457        TINYINT = auto()
3458        UBIGINT = auto()
3459        UINT = auto()
3460        USMALLINT = auto()
3461        UTINYINT = auto()
3462        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3463        UINT128 = auto()
3464        UINT256 = auto()
3465        UNIQUEIDENTIFIER = auto()
3466        USERDEFINED = "USER-DEFINED"
3467        UUID = auto()
3468        VARBINARY = auto()
3469        VARCHAR = auto()
3470        VARIANT = auto()
3471        XML = auto()
3472
3473    TEXT_TYPES = {
3474        Type.CHAR,
3475        Type.NCHAR,
3476        Type.VARCHAR,
3477        Type.NVARCHAR,
3478        Type.TEXT,
3479    }
3480
3481    INTEGER_TYPES = {
3482        Type.INT,
3483        Type.TINYINT,
3484        Type.SMALLINT,
3485        Type.BIGINT,
3486        Type.INT128,
3487        Type.INT256,
3488    }
3489
3490    FLOAT_TYPES = {
3491        Type.FLOAT,
3492        Type.DOUBLE,
3493    }
3494
3495    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3496
3497    TEMPORAL_TYPES = {
3498        Type.TIME,
3499        Type.TIMESTAMP,
3500        Type.TIMESTAMPTZ,
3501        Type.TIMESTAMPLTZ,
3502        Type.DATE,
3503        Type.DATETIME,
3504        Type.DATETIME64,
3505    }
3506
3507    META_TYPES = {"UNKNOWN", "NULL"}
3508
3509    @classmethod
3510    def build(
3511        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3512    ) -> DataType:
3513        from sqlglot import parse_one
3514
3515        if isinstance(dtype, str):
3516            upper = dtype.upper()
3517            if upper in DataType.META_TYPES:
3518                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3519            else:
3520                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3521
3522            if data_type_exp is None:
3523                raise ValueError(f"Unparsable data type value: {dtype}")
3524        elif isinstance(dtype, DataType.Type):
3525            data_type_exp = DataType(this=dtype)
3526        elif isinstance(dtype, DataType):
3527            return dtype
3528        else:
3529            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3530
3531        return DataType(**{**data_type_exp.args, **kwargs})
3532
3533    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3534        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False}
TEXT_TYPES = {<Type.VARCHAR: 'VARCHAR'>, <Type.TEXT: 'TEXT'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>}
INTEGER_TYPES = {<Type.BIGINT: 'BIGINT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.INT: 'INT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT256: 'INT256'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.INT256: 'INT256'>, <Type.BIGINT: 'BIGINT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.FLOAT: 'FLOAT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>, <Type.DOUBLE: 'DOUBLE'>}
TEMPORAL_TYPES = {<Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.TIME: 'TIME'>, <Type.DATE: 'DATE'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.DATETIME64: 'DATETIME64'>, <Type.DATETIME: 'DATETIME'>}
META_TYPES = {'NULL', 'UNKNOWN'}
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
3509    @classmethod
3510    def build(
3511        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3512    ) -> DataType:
3513        from sqlglot import parse_one
3514
3515        if isinstance(dtype, str):
3516            upper = dtype.upper()
3517            if upper in DataType.META_TYPES:
3518                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3519            else:
3520                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3521
3522            if data_type_exp is None:
3523                raise ValueError(f"Unparsable data type value: {dtype}")
3524        elif isinstance(dtype, DataType.Type):
3525            data_type_exp = DataType(this=dtype)
3526        elif isinstance(dtype, DataType):
3527            return dtype
3528        else:
3529            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3530
3531        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3533    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3534        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3391    class Type(AutoName):
3392        ARRAY = auto()
3393        BIGDECIMAL = auto()
3394        BIGINT = auto()
3395        BIGSERIAL = auto()
3396        BINARY = auto()
3397        BIT = auto()
3398        BOOLEAN = auto()
3399        CHAR = auto()
3400        DATE = auto()
3401        DATETIME = auto()
3402        DATETIME64 = auto()
3403        ENUM = auto()
3404        INT4RANGE = auto()
3405        INT4MULTIRANGE = auto()
3406        INT8RANGE = auto()
3407        INT8MULTIRANGE = auto()
3408        NUMRANGE = auto()
3409        NUMMULTIRANGE = auto()
3410        TSRANGE = auto()
3411        TSMULTIRANGE = auto()
3412        TSTZRANGE = auto()
3413        TSTZMULTIRANGE = auto()
3414        DATERANGE = auto()
3415        DATEMULTIRANGE = auto()
3416        DECIMAL = auto()
3417        DOUBLE = auto()
3418        FLOAT = auto()
3419        GEOGRAPHY = auto()
3420        GEOMETRY = auto()
3421        HLLSKETCH = auto()
3422        HSTORE = auto()
3423        IMAGE = auto()
3424        INET = auto()
3425        IPADDRESS = auto()
3426        IPPREFIX = auto()
3427        INT = auto()
3428        INT128 = auto()
3429        INT256 = auto()
3430        INTERVAL = auto()
3431        JSON = auto()
3432        JSONB = auto()
3433        LONGBLOB = auto()
3434        LONGTEXT = auto()
3435        MAP = auto()
3436        MEDIUMBLOB = auto()
3437        MEDIUMTEXT = auto()
3438        MONEY = auto()
3439        NCHAR = auto()
3440        NULL = auto()
3441        NULLABLE = auto()
3442        NVARCHAR = auto()
3443        OBJECT = auto()
3444        ROWVERSION = auto()
3445        SERIAL = auto()
3446        SET = auto()
3447        SMALLINT = auto()
3448        SMALLMONEY = auto()
3449        SMALLSERIAL = auto()
3450        STRUCT = auto()
3451        SUPER = auto()
3452        TEXT = auto()
3453        TIME = auto()
3454        TIMESTAMP = auto()
3455        TIMESTAMPTZ = auto()
3456        TIMESTAMPLTZ = auto()
3457        TINYINT = auto()
3458        UBIGINT = auto()
3459        UINT = auto()
3460        USMALLINT = auto()
3461        UTINYINT = auto()
3462        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3463        UINT128 = auto()
3464        UINT256 = auto()
3465        UNIQUEIDENTIFIER = auto()
3466        USERDEFINED = "USER-DEFINED"
3467        UUID = auto()
3468        VARBINARY = auto()
3469        VARCHAR = auto()
3470        VARIANT = auto()
3471        XML = auto()

An enumeration.

ARRAY = <Type.ARRAY: 'ARRAY'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <Type.BIGINT: 'BIGINT'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
BINARY = <Type.BINARY: 'BINARY'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
CHAR = <Type.CHAR: 'CHAR'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
ENUM = <Type.ENUM: 'ENUM'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
IPADDRESS = <Type.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <Type.IPPREFIX: 'IPPREFIX'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3538class PseudoType(Expression):
3539    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3543class SubqueryPredicate(Predicate):
3544    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3547class All(SubqueryPredicate):
3548    pass
key = 'all'
class Any(SubqueryPredicate):
3551class Any(SubqueryPredicate):
3552    pass
key = 'any'
class Exists(SubqueryPredicate):
3555class Exists(SubqueryPredicate):
3556    pass
key = 'exists'
class Command(Expression):
3561class Command(Expression):
3562    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3565class Transaction(Expression):
3566    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3569class Commit(Expression):
3570    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3573class Rollback(Expression):
3574    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3577class AlterTable(Expression):
3578    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3581class AddConstraint(Expression):
3582    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3585class DropPartition(Expression):
3586    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3590class Binary(Condition):
3591    arg_types = {"this": True, "expression": True}
3592
3593    @property
3594    def left(self):
3595        return self.this
3596
3597    @property
3598    def right(self):
3599        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3602class Add(Binary):
3603    pass
key = 'add'
class Connector(Binary):
3606class Connector(Binary):
3607    pass
key = 'connector'
class And(Connector):
3610class And(Connector):
3611    pass
key = 'and'
class Or(Connector):
3614class Or(Connector):
3615    pass
key = 'or'
class BitwiseAnd(Binary):
3618class BitwiseAnd(Binary):
3619    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3622class BitwiseLeftShift(Binary):
3623    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3626class BitwiseOr(Binary):
3627    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3630class BitwiseRightShift(Binary):
3631    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3634class BitwiseXor(Binary):
3635    pass
key = 'bitwisexor'
class Div(Binary):
3638class Div(Binary):
3639    pass
key = 'div'
class Overlaps(Binary):
3642class Overlaps(Binary):
3643    pass
key = 'overlaps'
class Dot(Binary):
3646class Dot(Binary):
3647    @property
3648    def name(self) -> str:
3649        return self.expression.name
3650
3651    @property
3652    def output_name(self) -> str:
3653        return self.name
3654
3655    @classmethod
3656    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3657        """Build a Dot object with a sequence of expressions."""
3658        if len(expressions) < 2:
3659            raise ValueError(f"Dot requires >= 2 expressions.")
3660
3661        a, b, *expressions = expressions
3662        dot = Dot(this=a, expression=b)
3663
3664        for expression in expressions:
3665            dot = Dot(this=dot, expression=expression)
3666
3667        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:
3655    @classmethod
3656    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3657        """Build a Dot object with a sequence of expressions."""
3658        if len(expressions) < 2:
3659            raise ValueError(f"Dot requires >= 2 expressions.")
3660
3661        a, b, *expressions = expressions
3662        dot = Dot(this=a, expression=b)
3663
3664        for expression in expressions:
3665            dot = Dot(this=dot, expression=expression)
3666
3667        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3670class DPipe(Binary):
3671    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3674class SafeDPipe(DPipe):
3675    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3678class EQ(Binary, Predicate):
3679    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3682class NullSafeEQ(Binary, Predicate):
3683    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3686class NullSafeNEQ(Binary, Predicate):
3687    pass
key = 'nullsafeneq'
class Distance(Binary):
3690class Distance(Binary):
3691    pass
key = 'distance'
class Escape(Binary):
3694class Escape(Binary):
3695    pass
key = 'escape'
class Glob(Binary, Predicate):
3698class Glob(Binary, Predicate):
3699    pass
key = 'glob'
class GT(Binary, Predicate):
3702class GT(Binary, Predicate):
3703    pass
key = 'gt'
class GTE(Binary, Predicate):
3706class GTE(Binary, Predicate):
3707    pass
key = 'gte'
class ILike(Binary, Predicate):
3710class ILike(Binary, Predicate):
3711    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3714class ILikeAny(Binary, Predicate):
3715    pass
key = 'ilikeany'
class IntDiv(Binary):
3718class IntDiv(Binary):
3719    pass
key = 'intdiv'
class Is(Binary, Predicate):
3722class Is(Binary, Predicate):
3723    pass
key = 'is'
class Kwarg(Binary):
3726class Kwarg(Binary):
3727    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3730class Like(Binary, Predicate):
3731    pass
key = 'like'
class LikeAny(Binary, Predicate):
3734class LikeAny(Binary, Predicate):
3735    pass
key = 'likeany'
class LT(Binary, Predicate):
3738class LT(Binary, Predicate):
3739    pass
key = 'lt'
class LTE(Binary, Predicate):
3742class LTE(Binary, Predicate):
3743    pass
key = 'lte'
class Mod(Binary):
3746class Mod(Binary):
3747    pass
key = 'mod'
class Mul(Binary):
3750class Mul(Binary):
3751    pass
key = 'mul'
class NEQ(Binary, Predicate):
3754class NEQ(Binary, Predicate):
3755    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3758class SimilarTo(Binary, Predicate):
3759    pass
key = 'similarto'
class Slice(Binary):
3762class Slice(Binary):
3763    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3766class Sub(Binary):
3767    pass
key = 'sub'
class ArrayOverlaps(Binary):
3770class ArrayOverlaps(Binary):
3771    pass
key = 'arrayoverlaps'
class Unary(Condition):
3776class Unary(Condition):
3777    pass
key = 'unary'
class BitwiseNot(Unary):
3780class BitwiseNot(Unary):
3781    pass
key = 'bitwisenot'
class Not(Unary):
3784class Not(Unary):
3785    pass
key = 'not'
class Paren(Unary):
3788class Paren(Unary):
3789    arg_types = {"this": True, "with": False}
3790
3791    @property
3792    def output_name(self) -> str:
3793        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):
3796class Neg(Unary):
3797    pass
key = 'neg'
class Alias(Expression):
3800class Alias(Expression):
3801    arg_types = {"this": True, "alias": False}
3802
3803    @property
3804    def output_name(self) -> str:
3805        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):
3808class Aliases(Expression):
3809    arg_types = {"this": True, "expressions": True}
3810
3811    @property
3812    def aliases(self):
3813        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3816class AtTimeZone(Expression):
3817    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3820class Between(Predicate):
3821    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3824class Bracket(Condition):
3825    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3828class SafeBracket(Bracket):
3829    """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):
3832class Distinct(Expression):
3833    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3836class In(Predicate):
3837    arg_types = {
3838        "this": True,
3839        "expressions": False,
3840        "query": False,
3841        "unnest": False,
3842        "field": False,
3843        "is_global": False,
3844    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3847class TimeUnit(Expression):
3848    """Automatically converts unit arg into a var."""
3849
3850    arg_types = {"unit": False}
3851
3852    def __init__(self, **args):
3853        unit = args.get("unit")
3854        if isinstance(unit, (Column, Literal)):
3855            args["unit"] = Var(this=unit.name)
3856        elif isinstance(unit, Week):
3857            unit.set("this", Var(this=unit.this.name))
3858
3859        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3852    def __init__(self, **args):
3853        unit = args.get("unit")
3854        if isinstance(unit, (Column, Literal)):
3855            args["unit"] = Var(this=unit.name)
3856        elif isinstance(unit, Week):
3857            unit.set("this", Var(this=unit.this.name))
3858
3859        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3862class Interval(TimeUnit):
3863    arg_types = {"this": False, "unit": False}
3864
3865    @property
3866    def unit(self) -> t.Optional[Var]:
3867        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3870class IgnoreNulls(Expression):
3871    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3874class RespectNulls(Expression):
3875    pass
key = 'respectnulls'
class Func(Condition):
3879class Func(Condition):
3880    """
3881    The base class for all function expressions.
3882
3883    Attributes:
3884        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3885            treated as a variable length argument and the argument's value will be stored as a list.
3886        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3887            for this function expression. These values are used to map this node to a name during parsing
3888            as well as to provide the function's name during SQL string generation. By default the SQL
3889            name is set to the expression's class name transformed to snake case.
3890    """
3891
3892    is_var_len_args = False
3893
3894    @classmethod
3895    def from_arg_list(cls, args):
3896        if cls.is_var_len_args:
3897            all_arg_keys = list(cls.arg_types)
3898            # If this function supports variable length argument treat the last argument as such.
3899            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3900            num_non_var = len(non_var_len_arg_keys)
3901
3902            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3903            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3904        else:
3905            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3906
3907        return cls(**args_dict)
3908
3909    @classmethod
3910    def sql_names(cls):
3911        if cls is Func:
3912            raise NotImplementedError(
3913                "SQL name is only supported by concrete function implementations"
3914            )
3915        if "_sql_names" not in cls.__dict__:
3916            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3917        return cls._sql_names
3918
3919    @classmethod
3920    def sql_name(cls):
3921        return cls.sql_names()[0]
3922
3923    @classmethod
3924    def default_parser_mappings(cls):
3925        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):
3894    @classmethod
3895    def from_arg_list(cls, args):
3896        if cls.is_var_len_args:
3897            all_arg_keys = list(cls.arg_types)
3898            # If this function supports variable length argument treat the last argument as such.
3899            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3900            num_non_var = len(non_var_len_arg_keys)
3901
3902            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3903            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3904        else:
3905            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3906
3907        return cls(**args_dict)
@classmethod
def sql_names(cls):
3909    @classmethod
3910    def sql_names(cls):
3911        if cls is Func:
3912            raise NotImplementedError(
3913                "SQL name is only supported by concrete function implementations"
3914            )
3915        if "_sql_names" not in cls.__dict__:
3916            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3917        return cls._sql_names
@classmethod
def sql_name(cls):
3919    @classmethod
3920    def sql_name(cls):
3921        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3923    @classmethod
3924    def default_parser_mappings(cls):
3925        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3928class AggFunc(Func):
3929    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3932class ParameterizedAgg(AggFunc):
3933    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3936class Abs(Func):
3937    pass
key = 'abs'
class Transform(Func):
3941class Transform(Func):
3942    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
3945class Anonymous(Func):
3946    arg_types = {"this": True, "expressions": False}
3947    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3952class Hll(AggFunc):
3953    arg_types = {"this": True, "expressions": False}
3954    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3957class ApproxDistinct(AggFunc):
3958    arg_types = {"this": True, "accuracy": False}
3959    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3962class Array(Func):
3963    arg_types = {"expressions": False}
3964    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3968class ToChar(Func):
3969    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3972class GenerateSeries(Func):
3973    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3976class ArrayAgg(AggFunc):
3977    pass
key = 'arrayagg'
class ArrayAll(Func):
3980class ArrayAll(Func):
3981    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3984class ArrayAny(Func):
3985    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3988class ArrayConcat(Func):
3989    arg_types = {"this": True, "expressions": False}
3990    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3993class ArrayContains(Binary, Func):
3994    pass
key = 'arraycontains'
class ArrayContained(Binary):
3997class ArrayContained(Binary):
3998    pass
key = 'arraycontained'
class ArrayFilter(Func):
4001class ArrayFilter(Func):
4002    arg_types = {"this": True, "expression": True}
4003    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4006class ArrayJoin(Func):
4007    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4010class ArraySize(Func):
4011    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4014class ArraySort(Func):
4015    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4018class ArraySum(Func):
4019    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4022class ArrayUnionAgg(AggFunc):
4023    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4026class Avg(AggFunc):
4027    pass
key = 'avg'
class AnyValue(AggFunc):
4030class AnyValue(AggFunc):
4031    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
4034class Case(Func):
4035    arg_types = {"this": False, "ifs": True, "default": False}
4036
4037    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4038        instance = maybe_copy(self, copy)
4039        instance.append(
4040            "ifs",
4041            If(
4042                this=maybe_parse(condition, copy=copy, **opts),
4043                true=maybe_parse(then, copy=copy, **opts),
4044            ),
4045        )
4046        return instance
4047
4048    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4049        instance = maybe_copy(self, copy)
4050        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4051        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:
4037    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4038        instance = maybe_copy(self, copy)
4039        instance.append(
4040            "ifs",
4041            If(
4042                this=maybe_parse(condition, copy=copy, **opts),
4043                true=maybe_parse(then, copy=copy, **opts),
4044            ),
4045        )
4046        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4048    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4049        instance = maybe_copy(self, copy)
4050        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4051        return instance
key = 'case'
class Cast(Func):
4054class Cast(Func):
4055    arg_types = {"this": True, "to": True, "format": False}
4056
4057    @property
4058    def name(self) -> str:
4059        return self.this.name
4060
4061    @property
4062    def to(self) -> DataType:
4063        return self.args["to"]
4064
4065    @property
4066    def output_name(self) -> str:
4067        return self.name
4068
4069    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4070        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:
4069    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4070        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
4073class CastToStrType(Func):
4074    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
4077class Collate(Binary):
4078    pass
key = 'collate'
class TryCast(Cast):
4081class TryCast(Cast):
4082    pass
key = 'trycast'
class Ceil(Func):
4085class Ceil(Func):
4086    arg_types = {"this": True, "decimals": False}
4087    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4090class Coalesce(Func):
4091    arg_types = {"this": True, "expressions": False}
4092    is_var_len_args = True
4093    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4096class Concat(Func):
4097    arg_types = {"expressions": True}
4098    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4101class SafeConcat(Concat):
4102    pass
key = 'safeconcat'
class ConcatWs(Concat):
4105class ConcatWs(Concat):
4106    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4109class Count(AggFunc):
4110    arg_types = {"this": False, "expressions": False}
4111    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4114class CountIf(AggFunc):
4115    pass
key = 'countif'
class CurrentDate(Func):
4118class CurrentDate(Func):
4119    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4122class CurrentDatetime(Func):
4123    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4126class CurrentTime(Func):
4127    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4130class CurrentTimestamp(Func):
4131    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4134class CurrentUser(Func):
4135    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4138class DateAdd(Func, TimeUnit):
4139    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4142class DateSub(Func, TimeUnit):
4143    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4146class DateDiff(Func, TimeUnit):
4147    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4148    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4151class DateTrunc(Func):
4152    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4155class DatetimeAdd(Func, TimeUnit):
4156    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4159class DatetimeSub(Func, TimeUnit):
4160    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4163class DatetimeDiff(Func, TimeUnit):
4164    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4167class DatetimeTrunc(Func, TimeUnit):
4168    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4171class DayOfWeek(Func):
4172    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4175class DayOfMonth(Func):
4176    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4179class DayOfYear(Func):
4180    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4183class WeekOfYear(Func):
4184    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4187class MonthsBetween(Func):
4188    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4191class LastDateOfMonth(Func):
4192    pass
key = 'lastdateofmonth'
class Extract(Func):
4195class Extract(Func):
4196    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4199class TimestampAdd(Func, TimeUnit):
4200    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4203class TimestampSub(Func, TimeUnit):
4204    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4207class TimestampDiff(Func, TimeUnit):
4208    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4211class TimestampTrunc(Func, TimeUnit):
4212    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4215class TimeAdd(Func, TimeUnit):
4216    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4219class TimeSub(Func, TimeUnit):
4220    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4223class TimeDiff(Func, TimeUnit):
4224    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4227class TimeTrunc(Func, TimeUnit):
4228    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4231class DateFromParts(Func):
4232    _sql_names = ["DATEFROMPARTS"]
4233    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4236class DateStrToDate(Func):
4237    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4240class DateToDateStr(Func):
4241    pass
key = 'datetodatestr'
class DateToDi(Func):
4244class DateToDi(Func):
4245    pass
key = 'datetodi'
class Date(Func):
4249class Date(Func):
4250    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4253class Day(Func):
4254    pass
key = 'day'
class Decode(Func):
4257class Decode(Func):
4258    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4261class DiToDate(Func):
4262    pass
key = 'ditodate'
class Encode(Func):
4265class Encode(Func):
4266    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4269class Exp(Func):
4270    pass
key = 'exp'
class Explode(Func):
4273class Explode(Func):
4274    pass
key = 'explode'
class Floor(Func):
4277class Floor(Func):
4278    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4281class FromBase64(Func):
4282    pass
key = 'frombase64'
class ToBase64(Func):
4285class ToBase64(Func):
4286    pass
key = 'tobase64'
class Greatest(Func):
4289class Greatest(Func):
4290    arg_types = {"this": True, "expressions": False}
4291    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4294class GroupConcat(Func):
4295    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4298class Hex(Func):
4299    pass
key = 'hex'
class Xor(Connector, Func):
4302class Xor(Connector, Func):
4303    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4306class If(Func):
4307    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4310class Initcap(Func):
4311    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4314class IsNan(Func):
4315    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class JSONKeyValue(Expression):
4318class JSONKeyValue(Expression):
4319    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4322class JSONObject(Func):
4323    arg_types = {
4324        "expressions": False,
4325        "null_handling": False,
4326        "unique_keys": False,
4327        "return_type": False,
4328        "format_json": False,
4329        "encoding": False,
4330    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4333class OpenJSONColumnDef(Expression):
4334    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):
4337class OpenJSON(Func):
4338    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4341class JSONBContains(Binary):
4342    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4345class JSONExtract(Binary, Func):
4346    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4349class JSONExtractScalar(JSONExtract):
4350    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4353class JSONBExtract(JSONExtract):
4354    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4357class JSONBExtractScalar(JSONExtract):
4358    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4361class JSONFormat(Func):
4362    arg_types = {"this": False, "options": False}
4363    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4367class JSONArrayContains(Binary, Predicate, Func):
4368    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4371class Least(Func):
4372    arg_types = {"this": True, "expressions": False}
4373    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4376class Left(Func):
4377    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4384class Length(Func):
4385    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4388class Levenshtein(Func):
4389    arg_types = {
4390        "this": True,
4391        "expression": False,
4392        "ins_cost": False,
4393        "del_cost": False,
4394        "sub_cost": False,
4395    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4398class Ln(Func):
4399    pass
key = 'ln'
class Log(Func):
4402class Log(Func):
4403    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4406class Log2(Func):
4407    pass
key = 'log2'
class Log10(Func):
4410class Log10(Func):
4411    pass
key = 'log10'
class LogicalOr(AggFunc):
4414class LogicalOr(AggFunc):
4415    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4418class LogicalAnd(AggFunc):
4419    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4422class Lower(Func):
4423    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4426class Map(Func):
4427    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4430class MapFromEntries(Func):
4431    pass
key = 'mapfromentries'
class StarMap(Func):
4434class StarMap(Func):
4435    pass
key = 'starmap'
class VarMap(Func):
4438class VarMap(Func):
4439    arg_types = {"keys": True, "values": True}
4440    is_var_len_args = True
4441
4442    @property
4443    def keys(self) -> t.List[Expression]:
4444        return self.args["keys"].expressions
4445
4446    @property
4447    def values(self) -> t.List[Expression]:
4448        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4452class MatchAgainst(Func):
4453    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4456class Max(AggFunc):
4457    arg_types = {"this": True, "expressions": False}
4458    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4461class MD5(Func):
4462    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4466class MD5Digest(Func):
4467    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4470class Min(AggFunc):
4471    arg_types = {"this": True, "expressions": False}
4472    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4475class Month(Func):
4476    pass
key = 'month'
class Nvl2(Func):
4479class Nvl2(Func):
4480    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4483class Posexplode(Func):
4484    pass
key = 'posexplode'
class Pow(Binary, Func):
4487class Pow(Binary, Func):
4488    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4491class PercentileCont(AggFunc):
4492    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4495class PercentileDisc(AggFunc):
4496    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4499class Quantile(AggFunc):
4500    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4503class ApproxQuantile(Quantile):
4504    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):
4507class RangeN(Func):
4508    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4511class ReadCSV(Func):
4512    _sql_names = ["READ_CSV"]
4513    is_var_len_args = True
4514    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4517class Reduce(Func):
4518    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):
4521class RegexpExtract(Func):
4522    arg_types = {
4523        "this": True,
4524        "expression": True,
4525        "position": False,
4526        "occurrence": False,
4527        "parameters": False,
4528        "group": False,
4529    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4532class RegexpReplace(Func):
4533    arg_types = {
4534        "this": True,
4535        "expression": True,
4536        "replacement": True,
4537        "position": False,
4538        "occurrence": False,
4539        "parameters": False,
4540    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4543class RegexpLike(Binary, Func):
4544    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4547class RegexpILike(Func):
4548    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4553class RegexpSplit(Func):
4554    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4557class Repeat(Func):
4558    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4561class Round(Func):
4562    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4565class RowNumber(Func):
4566    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4569class SafeDivide(Func):
4570    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4573class SetAgg(AggFunc):
4574    pass
key = 'setagg'
class SHA(Func):
4577class SHA(Func):
4578    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4581class SHA2(Func):
4582    _sql_names = ["SHA2"]
4583    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4586class SortArray(Func):
4587    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4590class Split(Func):
4591    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4596class Substring(Func):
4597    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4600class StandardHash(Func):
4601    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4604class StartsWith(Func):
4605    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4606    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4609class StrPosition(Func):
4610    arg_types = {
4611        "this": True,
4612        "substr": True,
4613        "position": False,
4614        "instance": False,
4615    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4618class StrToDate(Func):
4619    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4622class StrToTime(Func):
4623    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4628class StrToUnix(Func):
4629    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4632class NumberToStr(Func):
4633    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4636class FromBase(Func):
4637    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4640class Struct(Func):
4641    arg_types = {"expressions": True}
4642    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4645class StructExtract(Func):
4646    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4649class Sum(AggFunc):
4650    pass
key = 'sum'
class Sqrt(Func):
4653class Sqrt(Func):
4654    pass
key = 'sqrt'
class Stddev(AggFunc):
4657class Stddev(AggFunc):
4658    pass
key = 'stddev'
class StddevPop(AggFunc):
4661class StddevPop(AggFunc):
4662    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4665class StddevSamp(AggFunc):
4666    pass
key = 'stddevsamp'
class TimeToStr(Func):
4669class TimeToStr(Func):
4670    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4673class TimeToTimeStr(Func):
4674    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4677class TimeToUnix(Func):
4678    pass
key = 'timetounix'
class TimeStrToDate(Func):
4681class TimeStrToDate(Func):
4682    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4685class TimeStrToTime(Func):
4686    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4689class TimeStrToUnix(Func):
4690    pass
key = 'timestrtounix'
class Trim(Func):
4693class Trim(Func):
4694    arg_types = {
4695        "this": True,
4696        "expression": False,
4697        "position": False,
4698        "collation": False,
4699    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4702class TsOrDsAdd(Func, TimeUnit):
4703    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4706class TsOrDsToDateStr(Func):
4707    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4710class TsOrDsToDate(Func):
4711    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4714class TsOrDiToDi(Func):
4715    pass
key = 'tsorditodi'
class Unhex(Func):
4718class Unhex(Func):
4719    pass
key = 'unhex'
class UnixToStr(Func):
4722class UnixToStr(Func):
4723    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4728class UnixToTime(Func):
4729    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4730
4731    SECONDS = Literal.string("seconds")
4732    MILLIS = Literal.string("millis")
4733    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):
4736class UnixToTimeStr(Func):
4737    pass
key = 'unixtotimestr'
class Upper(Func):
4740class Upper(Func):
4741    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4744class Variance(AggFunc):
4745    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4748class VariancePop(AggFunc):
4749    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4752class Week(Func):
4753    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4756class XMLTable(Func):
4757    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):
4760class Year(Func):
4761    pass
key = 'year'
class Use(Expression):
4764class Use(Expression):
4765    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4768class Merge(Expression):
4769    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):
4772class When(Func):
4773    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):
4778class NextValueFor(Func):
4779    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.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.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.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.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:
4816def maybe_parse(
4817    sql_or_expression: ExpOrStr,
4818    *,
4819    into: t.Optional[IntoType] = None,
4820    dialect: DialectType = None,
4821    prefix: t.Optional[str] = None,
4822    copy: bool = False,
4823    **opts,
4824) -> Expression:
4825    """Gracefully handle a possible string or expression.
4826
4827    Example:
4828        >>> maybe_parse("1")
4829        (LITERAL this: 1, is_string: False)
4830        >>> maybe_parse(to_identifier("x"))
4831        (IDENTIFIER this: x, quoted: False)
4832
4833    Args:
4834        sql_or_expression: the SQL code string or an expression
4835        into: the SQLGlot Expression to parse into
4836        dialect: the dialect used to parse the input expressions (in the case that an
4837            input expression is a SQL string).
4838        prefix: a string to prefix the sql with before it gets parsed
4839            (automatically includes a space)
4840        copy: whether or not to copy the expression.
4841        **opts: other options to use to parse the input expressions (again, in the case
4842            that an input expression is a SQL string).
4843
4844    Returns:
4845        Expression: the parsed or given expression.
4846    """
4847    if isinstance(sql_or_expression, Expression):
4848        if copy:
4849            return sql_or_expression.copy()
4850        return sql_or_expression
4851
4852    if sql_or_expression is None:
4853        raise ParseError(f"SQL cannot be None")
4854
4855    import sqlglot
4856
4857    sql = str(sql_or_expression)
4858    if prefix:
4859        sql = f"{prefix} {sql}"
4860
4861    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: ~E, copy: bool = True) -> ~E:
4864def maybe_copy(instance: E, copy: bool = True) -> E:
4865    return instance.copy() if copy 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:
5045def union(
5046    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5047) -> Union:
5048    """
5049    Initializes a syntax tree from one UNION expression.
5050
5051    Example:
5052        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5053        'SELECT * FROM foo UNION SELECT * FROM bla'
5054
5055    Args:
5056        left: the SQL code string corresponding to the left-hand side.
5057            If an `Expression` instance is passed, it will be used as-is.
5058        right: the SQL code string corresponding to the right-hand side.
5059            If an `Expression` instance is passed, it will be used as-is.
5060        distinct: set the DISTINCT flag if and only if this is true.
5061        dialect: the dialect used to parse the input expression.
5062        opts: other options to use to parse the input expressions.
5063
5064    Returns:
5065        The new Union instance.
5066    """
5067    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5068    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5069
5070    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:
5073def intersect(
5074    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5075) -> Intersect:
5076    """
5077    Initializes a syntax tree from one INTERSECT expression.
5078
5079    Example:
5080        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5081        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5082
5083    Args:
5084        left: the SQL code string corresponding to the left-hand side.
5085            If an `Expression` instance is passed, it will be used as-is.
5086        right: the SQL code string corresponding to the right-hand side.
5087            If an `Expression` instance is passed, it will be used as-is.
5088        distinct: set the DISTINCT flag if and only if this is true.
5089        dialect: the dialect used to parse the input expression.
5090        opts: other options to use to parse the input expressions.
5091
5092    Returns:
5093        The new Intersect instance.
5094    """
5095    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5096    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5097
5098    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:
5101def except_(
5102    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5103) -> Except:
5104    """
5105    Initializes a syntax tree from one EXCEPT expression.
5106
5107    Example:
5108        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5109        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5110
5111    Args:
5112        left: the SQL code string corresponding to the left-hand side.
5113            If an `Expression` instance is passed, it will be used as-is.
5114        right: the SQL code string corresponding to the right-hand side.
5115            If an `Expression` instance is passed, it will be used as-is.
5116        distinct: set the DISTINCT flag if and only if this is true.
5117        dialect: the dialect used to parse the input expression.
5118        opts: other options to use to parse the input expressions.
5119
5120    Returns:
5121        The new Except instance.
5122    """
5123    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5124    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5125
5126    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:
5129def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5130    """
5131    Initializes a syntax tree from one or multiple SELECT expressions.
5132
5133    Example:
5134        >>> select("col1", "col2").from_("tbl").sql()
5135        'SELECT col1, col2 FROM tbl'
5136
5137    Args:
5138        *expressions: the SQL code string to parse as the expressions of a
5139            SELECT statement. If an Expression instance is passed, this is used as-is.
5140        dialect: the dialect used to parse the input expressions (in the case that an
5141            input expression is a SQL string).
5142        **opts: other options to use to parse the input expressions (again, in the case
5143            that an input expression is a SQL string).
5144
5145    Returns:
5146        Select: the syntax tree for the SELECT statement.
5147    """
5148    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:
5151def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5152    """
5153    Initializes a syntax tree from a FROM expression.
5154
5155    Example:
5156        >>> from_("tbl").select("col1", "col2").sql()
5157        'SELECT col1, col2 FROM tbl'
5158
5159    Args:
5160        *expression: the SQL code string to parse as the FROM expressions of a
5161            SELECT statement. If an Expression instance is passed, this is used as-is.
5162        dialect: the dialect used to parse the input expression (in the case that the
5163            input expression is a SQL string).
5164        **opts: other options to use to parse the input expressions (again, in the case
5165            that the input expression is a SQL string).
5166
5167    Returns:
5168        Select: the syntax tree for the SELECT statement.
5169    """
5170    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:
5173def update(
5174    table: str | Table,
5175    properties: dict,
5176    where: t.Optional[ExpOrStr] = None,
5177    from_: t.Optional[ExpOrStr] = None,
5178    dialect: DialectType = None,
5179    **opts,
5180) -> Update:
5181    """
5182    Creates an update statement.
5183
5184    Example:
5185        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5186        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5187
5188    Args:
5189        *properties: dictionary of properties to set which are
5190            auto converted to sql objects eg None -> NULL
5191        where: sql conditional parsed into a WHERE statement
5192        from_: sql statement parsed into a FROM statement
5193        dialect: the dialect used to parse the input expressions.
5194        **opts: other options to use to parse the input expressions.
5195
5196    Returns:
5197        Update: the syntax tree for the UPDATE statement.
5198    """
5199    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5200    update_expr.set(
5201        "expressions",
5202        [
5203            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5204            for k, v in properties.items()
5205        ],
5206    )
5207    if from_:
5208        update_expr.set(
5209            "from",
5210            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5211        )
5212    if isinstance(where, Condition):
5213        where = Where(this=where)
5214    if where:
5215        update_expr.set(
5216            "where",
5217            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5218        )
5219    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:
5222def delete(
5223    table: ExpOrStr,
5224    where: t.Optional[ExpOrStr] = None,
5225    returning: t.Optional[ExpOrStr] = None,
5226    dialect: DialectType = None,
5227    **opts,
5228) -> Delete:
5229    """
5230    Builds a delete statement.
5231
5232    Example:
5233        >>> delete("my_table", where="id > 1").sql()
5234        'DELETE FROM my_table WHERE id > 1'
5235
5236    Args:
5237        where: sql conditional parsed into a WHERE statement
5238        returning: sql conditional parsed into a RETURNING statement
5239        dialect: the dialect used to parse the input expressions.
5240        **opts: other options to use to parse the input expressions.
5241
5242    Returns:
5243        Delete: the syntax tree for the DELETE statement.
5244    """
5245    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5246    if where:
5247        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5248    if returning:
5249        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5250    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:
5253def insert(
5254    expression: ExpOrStr,
5255    into: ExpOrStr,
5256    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5257    overwrite: t.Optional[bool] = None,
5258    dialect: DialectType = None,
5259    copy: bool = True,
5260    **opts,
5261) -> Insert:
5262    """
5263    Builds an INSERT statement.
5264
5265    Example:
5266        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5267        'INSERT INTO tbl VALUES (1, 2, 3)'
5268
5269    Args:
5270        expression: the sql string or expression of the INSERT statement
5271        into: the tbl to insert data to.
5272        columns: optionally the table's column names.
5273        overwrite: whether to INSERT OVERWRITE or not.
5274        dialect: the dialect used to parse the input expressions.
5275        copy: whether or not to copy the expression.
5276        **opts: other options to use to parse the input expressions.
5277
5278    Returns:
5279        Insert: the syntax tree for the INSERT statement.
5280    """
5281    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5282    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5283
5284    if columns:
5285        this = _apply_list_builder(
5286            *columns,
5287            instance=Schema(this=this),
5288            arg="expressions",
5289            into=Identifier,
5290            copy=False,
5291            dialect=dialect,
5292            **opts,
5293        )
5294
5295    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:
5298def condition(
5299    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5300) -> Condition:
5301    """
5302    Initialize a logical condition expression.
5303
5304    Example:
5305        >>> condition("x=1").sql()
5306        'x = 1'
5307
5308        This is helpful for composing larger logical syntax trees:
5309        >>> where = condition("x=1")
5310        >>> where = where.and_("y=1")
5311        >>> Select().from_("tbl").select("*").where(where).sql()
5312        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5313
5314    Args:
5315        *expression: the SQL code string to parse.
5316            If an Expression instance is passed, this is used as-is.
5317        dialect: the dialect used to parse the input expression (in the case that the
5318            input expression is a SQL string).
5319        copy: Whether or not to copy `expression` (only applies to expressions).
5320        **opts: other options to use to parse the input expressions (again, in the case
5321            that the input expression is a SQL string).
5322
5323    Returns:
5324        The new Condition instance
5325    """
5326    return maybe_parse(
5327        expression,
5328        into=Condition,
5329        dialect=dialect,
5330        copy=copy,
5331        **opts,
5332    )

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:
5335def and_(
5336    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5337) -> Condition:
5338    """
5339    Combine multiple conditions with an AND logical operator.
5340
5341    Example:
5342        >>> and_("x=1", and_("y=1", "z=1")).sql()
5343        'x = 1 AND (y = 1 AND z = 1)'
5344
5345    Args:
5346        *expressions: the SQL code strings to parse.
5347            If an Expression instance is passed, this is used as-is.
5348        dialect: the dialect used to parse the input expression.
5349        copy: whether or not to copy `expressions` (only applies to Expressions).
5350        **opts: other options to use to parse the input expressions.
5351
5352    Returns:
5353        And: the new condition
5354    """
5355    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:
5358def or_(
5359    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5360) -> Condition:
5361    """
5362    Combine multiple conditions with an OR logical operator.
5363
5364    Example:
5365        >>> or_("x=1", or_("y=1", "z=1")).sql()
5366        'x = 1 OR (y = 1 OR z = 1)'
5367
5368    Args:
5369        *expressions: the SQL code strings to parse.
5370            If an Expression instance is passed, this is used as-is.
5371        dialect: the dialect used to parse the input expression.
5372        copy: whether or not to copy `expressions` (only applies to Expressions).
5373        **opts: other options to use to parse the input expressions.
5374
5375    Returns:
5376        Or: the new condition
5377    """
5378    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:
5381def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5382    """
5383    Wrap a condition with a NOT operator.
5384
5385    Example:
5386        >>> not_("this_suit='black'").sql()
5387        "NOT this_suit = 'black'"
5388
5389    Args:
5390        expression: the SQL code string to parse.
5391            If an Expression instance is passed, this is used as-is.
5392        dialect: the dialect used to parse the input expression.
5393        copy: whether to copy the expression or not.
5394        **opts: other options to use to parse the input expressions.
5395
5396    Returns:
5397        The new condition.
5398    """
5399    this = condition(
5400        expression,
5401        dialect=dialect,
5402        copy=copy,
5403        **opts,
5404    )
5405    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:
5408def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5409    """
5410    Wrap an expression in parentheses.
5411
5412    Example:
5413        >>> paren("5 + 3").sql()
5414        '(5 + 3)'
5415
5416    Args:
5417        expression: the SQL code string to parse.
5418            If an Expression instance is passed, this is used as-is.
5419        copy: whether to copy the expression or not.
5420
5421    Returns:
5422        The wrapped expression.
5423    """
5424    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):
5442def to_identifier(name, quoted=None, copy=True):
5443    """Builds an identifier.
5444
5445    Args:
5446        name: The name to turn into an identifier.
5447        quoted: Whether or not force quote the identifier.
5448        copy: Whether or not to copy a passed in Identefier node.
5449
5450    Returns:
5451        The identifier ast node.
5452    """
5453
5454    if name is None:
5455        return None
5456
5457    if isinstance(name, Identifier):
5458        identifier = maybe_copy(name, copy)
5459    elif isinstance(name, str):
5460        identifier = Identifier(
5461            this=name,
5462            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5463        )
5464    else:
5465        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5466    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:
5472def to_interval(interval: str | Literal) -> Interval:
5473    """Builds an interval expression from a string like '1 day' or '5 months'."""
5474    if isinstance(interval, Literal):
5475        if not interval.is_string:
5476            raise ValueError("Invalid interval string.")
5477
5478        interval = interval.this
5479
5480    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5481
5482    if not interval_parts:
5483        raise ValueError("Invalid interval string.")
5484
5485    return Interval(
5486        this=Literal.string(interval_parts.group(1)),
5487        unit=Var(this=interval_parts.group(2)),
5488    )

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]:
5501def to_table(
5502    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5503) -> t.Optional[Table]:
5504    """
5505    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5506    If a table is passed in then that table is returned.
5507
5508    Args:
5509        sql_path: a `[catalog].[schema].[table]` string.
5510        dialect: the source dialect according to which the table name will be parsed.
5511        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5512
5513    Returns:
5514        A table expression.
5515    """
5516    if sql_path is None or isinstance(sql_path, Table):
5517        return sql_path
5518    if not isinstance(sql_path, str):
5519        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5520
5521    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5522    if table:
5523        for k, v in kwargs.items():
5524            table.set(k, v)
5525
5526    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:
5529def to_column(sql_path: str | Column, **kwargs) -> Column:
5530    """
5531    Create a column from a `[table].[column]` sql path. Schema is optional.
5532
5533    If a column is passed in then that column is returned.
5534
5535    Args:
5536        sql_path: `[table].[column]` string
5537    Returns:
5538        Table: A column expression
5539    """
5540    if sql_path is None or isinstance(sql_path, Column):
5541        return sql_path
5542    if not isinstance(sql_path, str):
5543        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5544    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):
5547def alias_(
5548    expression: ExpOrStr,
5549    alias: str | Identifier,
5550    table: bool | t.Sequence[str | Identifier] = False,
5551    quoted: t.Optional[bool] = None,
5552    dialect: DialectType = None,
5553    copy: bool = True,
5554    **opts,
5555):
5556    """Create an Alias expression.
5557
5558    Example:
5559        >>> alias_('foo', 'bar').sql()
5560        'foo AS bar'
5561
5562        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5563        '(SELECT 1, 2) AS bar(a, b)'
5564
5565    Args:
5566        expression: the SQL code strings to parse.
5567            If an Expression instance is passed, this is used as-is.
5568        alias: the alias name to use. If the name has
5569            special characters it is quoted.
5570        table: Whether or not to create a table alias, can also be a list of columns.
5571        quoted: whether or not to quote the alias
5572        dialect: the dialect used to parse the input expression.
5573        copy: Whether or not to copy the expression.
5574        **opts: other options to use to parse the input expressions.
5575
5576    Returns:
5577        Alias: the aliased expression
5578    """
5579    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5580    alias = to_identifier(alias, quoted=quoted)
5581
5582    if table:
5583        table_alias = TableAlias(this=alias)
5584        exp.set("alias", table_alias)
5585
5586        if not isinstance(table, bool):
5587            for column in table:
5588                table_alias.append("columns", to_identifier(column, quoted=quoted))
5589
5590        return exp
5591
5592    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5593    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5594    # for the complete Window expression.
5595    #
5596    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5597
5598    if "alias" in exp.arg_types and not isinstance(exp, Window):
5599        exp.set("alias", alias)
5600        return exp
5601    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:
5604def subquery(
5605    expression: ExpOrStr,
5606    alias: t.Optional[Identifier | str] = None,
5607    dialect: DialectType = None,
5608    **opts,
5609) -> Select:
5610    """
5611    Build a subquery expression.
5612
5613    Example:
5614        >>> subquery('select x from tbl', 'bar').select('x').sql()
5615        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5616
5617    Args:
5618        expression: the SQL code strings to parse.
5619            If an Expression instance is passed, this is used as-is.
5620        alias: the alias name to use.
5621        dialect: the dialect used to parse the input expression.
5622        **opts: other options to use to parse the input expressions.
5623
5624    Returns:
5625        A new Select instance with the subquery expression included.
5626    """
5627
5628    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5629    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:
5632def column(
5633    col: str | Identifier,
5634    table: t.Optional[str | Identifier] = None,
5635    db: t.Optional[str | Identifier] = None,
5636    catalog: t.Optional[str | Identifier] = None,
5637    quoted: t.Optional[bool] = None,
5638) -> Column:
5639    """
5640    Build a Column.
5641
5642    Args:
5643        col: Column name.
5644        table: Table name.
5645        db: Database name.
5646        catalog: Catalog name.
5647        quoted: Whether to force quotes on the column's identifiers.
5648
5649    Returns:
5650        The new Column instance.
5651    """
5652    return Column(
5653        this=to_identifier(col, quoted=quoted),
5654        table=to_identifier(table, quoted=quoted),
5655        db=to_identifier(db, quoted=quoted),
5656        catalog=to_identifier(catalog, quoted=quoted),
5657    )

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:
5660def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5661    """Cast an expression to a data type.
5662
5663    Example:
5664        >>> cast('x + 1', 'int').sql()
5665        'CAST(x + 1 AS INT)'
5666
5667    Args:
5668        expression: The expression to cast.
5669        to: The datatype to cast to.
5670
5671    Returns:
5672        The new Cast instance.
5673    """
5674    expression = maybe_parse(expression, **opts)
5675    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:
5678def table_(
5679    table: Identifier | str,
5680    db: t.Optional[Identifier | str] = None,
5681    catalog: t.Optional[Identifier | str] = None,
5682    quoted: t.Optional[bool] = None,
5683    alias: t.Optional[Identifier | str] = None,
5684) -> Table:
5685    """Build a Table.
5686
5687    Args:
5688        table: Table name.
5689        db: Database name.
5690        catalog: Catalog name.
5691        quote: Whether to force quotes on the table's identifiers.
5692        alias: Table's alias.
5693
5694    Returns:
5695        The new Table instance.
5696    """
5697    return Table(
5698        this=to_identifier(table, quoted=quoted),
5699        db=to_identifier(db, quoted=quoted),
5700        catalog=to_identifier(catalog, quoted=quoted),
5701        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5702    )

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:
5705def values(
5706    values: t.Iterable[t.Tuple[t.Any, ...]],
5707    alias: t.Optional[str] = None,
5708    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5709) -> Values:
5710    """Build VALUES statement.
5711
5712    Example:
5713        >>> values([(1, '2')]).sql()
5714        "VALUES (1, '2')"
5715
5716    Args:
5717        values: values statements that will be converted to SQL
5718        alias: optional alias
5719        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5720         If either are provided then an alias is also required.
5721
5722    Returns:
5723        Values: the Values expression object
5724    """
5725    if columns and not alias:
5726        raise ValueError("Alias is required when providing columns")
5727
5728    return Values(
5729        expressions=[convert(tup) for tup in values],
5730        alias=(
5731            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5732            if columns
5733            else (TableAlias(this=to_identifier(alias)) if alias else None)
5734        ),
5735    )

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:
5738def var(name: t.Optional[ExpOrStr]) -> Var:
5739    """Build a SQL variable.
5740
5741    Example:
5742        >>> repr(var('x'))
5743        '(VAR this: x)'
5744
5745        >>> repr(var(column('x', table='y')))
5746        '(VAR this: x)'
5747
5748    Args:
5749        name: The name of the var or an expression who's name will become the var.
5750
5751    Returns:
5752        The new variable node.
5753    """
5754    if not name:
5755        raise ValueError("Cannot convert empty name into var.")
5756
5757    if isinstance(name, Expression):
5758        name = name.name
5759    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:
5762def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5763    """Build ALTER TABLE... RENAME... expression
5764
5765    Args:
5766        old_name: The old name of the table
5767        new_name: The new name of the table
5768
5769    Returns:
5770        Alter table expression
5771    """
5772    old_table = to_table(old_name)
5773    new_table = to_table(new_name)
5774    return AlterTable(
5775        this=old_table,
5776        actions=[
5777            RenameTable(this=new_table),
5778        ],
5779    )

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:
5782def convert(value: t.Any, copy: bool = False) -> Expression:
5783    """Convert a python value into an expression object.
5784
5785    Raises an error if a conversion is not possible.
5786
5787    Args:
5788        value: A python object.
5789        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5790
5791    Returns:
5792        Expression: the equivalent expression object.
5793    """
5794    if isinstance(value, Expression):
5795        return maybe_copy(value, copy)
5796    if isinstance(value, str):
5797        return Literal.string(value)
5798    if isinstance(value, bool):
5799        return Boolean(this=value)
5800    if value is None or (isinstance(value, float) and math.isnan(value)):
5801        return NULL
5802    if isinstance(value, numbers.Number):
5803        return Literal.number(value)
5804    if isinstance(value, datetime.datetime):
5805        datetime_literal = Literal.string(
5806            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5807        )
5808        return TimeStrToTime(this=datetime_literal)
5809    if isinstance(value, datetime.date):
5810        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5811        return DateStrToDate(this=date_literal)
5812    if isinstance(value, tuple):
5813        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5814    if isinstance(value, list):
5815        return Array(expressions=[convert(v, copy=copy) for v in value])
5816    if isinstance(value, dict):
5817        return Map(
5818            keys=[convert(k, copy=copy) for k in value],
5819            values=[convert(v, copy=copy) for v in value.values()],
5820        )
5821    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:
5824def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5825    """
5826    Replace children of an expression with the result of a lambda fun(child) -> exp.
5827    """
5828    for k, v in expression.args.items():
5829        is_list_arg = type(v) is list
5830
5831        child_nodes = v if is_list_arg else [v]
5832        new_child_nodes = []
5833
5834        for cn in child_nodes:
5835            if isinstance(cn, Expression):
5836                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5837                    new_child_nodes.append(child_node)
5838                    child_node.parent = expression
5839                    child_node.arg_key = k
5840            else:
5841                new_child_nodes.append(cn)
5842
5843        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]:
5846def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5847    """
5848    Return all table names referenced through columns in an expression.
5849
5850    Example:
5851        >>> import sqlglot
5852        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5853        ['a', 'c']
5854
5855    Args:
5856        expression: expression to find table names.
5857        exclude: a table name to exclude
5858
5859    Returns:
5860        A list of unique names.
5861    """
5862    return {
5863        table
5864        for table in (column.table for column in expression.find_all(Column))
5865        if table and table != exclude
5866    }

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:
5869def table_name(table: Table | str, dialect: DialectType = None) -> str:
5870    """Get the full name of a table as a string.
5871
5872    Args:
5873        table: Table expression node or string.
5874        dialect: The dialect to generate the table name for.
5875
5876    Examples:
5877        >>> from sqlglot import exp, parse_one
5878        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5879        'a.b.c'
5880
5881    Returns:
5882        The table name.
5883    """
5884
5885    table = maybe_parse(table, into=Table)
5886
5887    if not table:
5888        raise ValueError(f"Cannot parse {table}")
5889
5890    return ".".join(
5891        part.sql(dialect=dialect, identify=True)
5892        if not SAFE_IDENTIFIER_RE.match(part.name)
5893        else part.name
5894        for part in table.parts
5895    )

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:
5898def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5899    """Replace all tables in expression according to the mapping.
5900
5901    Args:
5902        expression: expression node to be transformed and replaced.
5903        mapping: mapping of table names.
5904        copy: whether or not to copy the expression.
5905
5906    Examples:
5907        >>> from sqlglot import exp, parse_one
5908        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5909        'SELECT * FROM c'
5910
5911    Returns:
5912        The mapped expression.
5913    """
5914
5915    def _replace_tables(node: Expression) -> Expression:
5916        if isinstance(node, Table):
5917            new_name = mapping.get(table_name(node))
5918            if new_name:
5919                return to_table(
5920                    new_name,
5921                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5922                )
5923        return node
5924
5925    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:
5928def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5929    """Replace placeholders in an expression.
5930
5931    Args:
5932        expression: expression node to be transformed and replaced.
5933        args: positional names that will substitute unnamed placeholders in the given order.
5934        kwargs: keyword arguments that will substitute named placeholders.
5935
5936    Examples:
5937        >>> from sqlglot import exp, parse_one
5938        >>> replace_placeholders(
5939        ...     parse_one("select * from :tbl where ? = ?"),
5940        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5941        ... ).sql()
5942        "SELECT * FROM foo WHERE str_col = 'b'"
5943
5944    Returns:
5945        The mapped expression.
5946    """
5947
5948    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5949        if isinstance(node, Placeholder):
5950            if node.name:
5951                new_name = kwargs.get(node.name)
5952                if new_name:
5953                    return convert(new_name)
5954            else:
5955                try:
5956                    return convert(next(args))
5957                except StopIteration:
5958                    pass
5959        return node
5960
5961    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:
5964def expand(
5965    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5966) -> Expression:
5967    """Transforms an expression by expanding all referenced sources into subqueries.
5968
5969    Examples:
5970        >>> from sqlglot import parse_one
5971        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5972        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5973
5974        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5975        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5976
5977    Args:
5978        expression: The expression to expand.
5979        sources: A dictionary of name to Subqueryables.
5980        copy: Whether or not to copy the expression during transformation. Defaults to True.
5981
5982    Returns:
5983        The transformed expression.
5984    """
5985
5986    def _expand(node: Expression):
5987        if isinstance(node, Table):
5988            name = table_name(node)
5989            source = sources.get(name)
5990            if source:
5991                subquery = source.subquery(node.alias or name)
5992                subquery.comments = [f"source: {name}"]
5993                return subquery.transform(_expand, copy=False)
5994        return node
5995
5996    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:
5999def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6000    """
6001    Returns a Func expression.
6002
6003    Examples:
6004        >>> func("abs", 5).sql()
6005        'ABS(5)'
6006
6007        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6008        'CAST(5 AS DOUBLE)'
6009
6010    Args:
6011        name: the name of the function to build.
6012        args: the args used to instantiate the function of interest.
6013        dialect: the source dialect.
6014        kwargs: the kwargs used to instantiate the function of interest.
6015
6016    Note:
6017        The arguments `args` and `kwargs` are mutually exclusive.
6018
6019    Returns:
6020        An instance of the function of interest, or an anonymous function, if `name` doesn't
6021        correspond to an existing `sqlglot.expressions.Func` class.
6022    """
6023    if args and kwargs:
6024        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6025
6026    from sqlglot.dialects.dialect import Dialect
6027
6028    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6029    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6030
6031    parser = Dialect.get_or_raise(dialect)().parser()
6032    from_args_list = parser.FUNCTIONS.get(name.upper())
6033
6034    if from_args_list:
6035        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6036    else:
6037        kwargs = kwargs or {"expressions": converted}
6038        function = Anonymous(this=name, **kwargs)
6039
6040    for error_message in function.error_messages(converted):
6041        raise ValueError(error_message)
6042
6043    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:
6046def true() -> Boolean:
6047    """
6048    Returns a true Boolean expression.
6049    """
6050    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
6053def false() -> Boolean:
6054    """
6055    Returns a false Boolean expression.
6056    """
6057    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6060def null() -> Null:
6061    """
6062    Returns a Null expression.
6063    """
6064    return Null()

Returns a Null expression.

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