Edit on GitHub

Expressions

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

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


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

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

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

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

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

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

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

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

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

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

name: str
alias_or_name: str
output_name: str

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

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

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

Returns a deep copy of the expression.

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

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

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

Sets arg_key to value.

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

Returns the depth of this tree.

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

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

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

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

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

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

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

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

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

The generator object.

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

Returns a nearest parent matching expression_types.

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

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

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

Returns the root expression of this tree.

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

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

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

the generator object.

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

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

Returns:

The generator object.

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

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

Returns:

The generator object.

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

Returns the first non parenthesis child or self.

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

Returns the inner expression if this is an Alias.

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

Returns unnested operands as a tuple.

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

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

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

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

Returns SQL string representation of this tree.

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

The SQL string.

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

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

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

The transformed tree.

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

Swap out this expression with a new expression.

For example::

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

The new expression or expressions.

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

Remove this expression from its AST.

Returns:

The popped expression.

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

Assert that this Expression is an instance of type_.

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

Examples:

This is useful for type security in chained expressions:

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

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

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

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

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

Dump this Expression to a JSON-serializable dict.

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

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

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

AND this condition with one or multiple expressions.

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

The new And condition.

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

OR this condition with one or multiple expressions.

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

The new Or condition.

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

Wrap this condition with NOT.

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

The new Not instance.

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

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

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

Builds a UNION expression.

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

The new Union expression.

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

Builds an INTERSECT expression.

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

The new Intersect expression.

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

Builds an EXCEPT expression.

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

The new Except expression.

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

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

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

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

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

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

Converts the column into a dot expression.

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

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:
1375    def where(
1376        self,
1377        *expressions: t.Optional[ExpOrStr],
1378        append: bool = True,
1379        dialect: DialectType = None,
1380        copy: bool = True,
1381        **opts,
1382    ) -> Delete:
1383        """
1384        Append to or set the WHERE expressions.
1385
1386        Example:
1387            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1388            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1389
1390        Args:
1391            *expressions: the SQL code strings to parse.
1392                If an `Expression` instance is passed, it will be used as-is.
1393                Multiple expressions are combined with an AND operator.
1394            append: if `True`, AND the new expressions to any existing expression.
1395                Otherwise, this resets the expression.
1396            dialect: the dialect used to parse the input expressions.
1397            copy: if `False`, modify this expression instance in-place.
1398            opts: other options to use to parse the input expressions.
1399
1400        Returns:
1401            Delete: the modified expression.
1402        """
1403        return _apply_conjunction_builder(
1404            *expressions,
1405            instance=self,
1406            arg="where",
1407            append=append,
1408            into=Where,
1409            dialect=dialect,
1410            copy=copy,
1411            **opts,
1412        )

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:
1414    def returning(
1415        self,
1416        expression: ExpOrStr,
1417        dialect: DialectType = None,
1418        copy: bool = True,
1419        **opts,
1420    ) -> Delete:
1421        """
1422        Set the RETURNING expression. Not supported by all dialects.
1423
1424        Example:
1425            >>> delete("tbl").returning("*", dialect="postgres").sql()
1426            'DELETE FROM tbl RETURNING *'
1427
1428        Args:
1429            expression: the SQL code strings to parse.
1430                If an `Expression` instance is passed, it will be used as-is.
1431            dialect: the dialect used to parse the input expressions.
1432            copy: if `False`, modify this expression instance in-place.
1433            opts: other options to use to parse the input expressions.
1434
1435        Returns:
1436            Delete: the modified expression.
1437        """
1438        return _apply_builder(
1439            expression=expression,
1440            instance=self,
1441            arg="returning",
1442            prefix="RETURNING",
1443            dialect=dialect,
1444            copy=copy,
1445            into=Returning,
1446            **opts,
1447        )

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):
1450class Drop(Expression):
1451    arg_types = {
1452        "this": False,
1453        "kind": False,
1454        "exists": False,
1455        "temporary": False,
1456        "materialized": False,
1457        "cascade": False,
1458        "constraints": False,
1459        "purge": False,
1460    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1463class Filter(Expression):
1464    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1467class Check(Expression):
1468    pass
key = 'check'
class Directory(Expression):
1471class Directory(Expression):
1472    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1473    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1476class ForeignKey(Expression):
1477    arg_types = {
1478        "expressions": True,
1479        "reference": False,
1480        "delete": False,
1481        "update": False,
1482    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1485class PrimaryKey(Expression):
1486    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1491class Into(Expression):
1492    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1495class From(Expression):
1496    @property
1497    def name(self) -> str:
1498        return self.this.name
1499
1500    @property
1501    def alias_or_name(self) -> str:
1502        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1505class Having(Expression):
1506    pass
key = 'having'
class Hint(Expression):
1509class Hint(Expression):
1510    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1513class JoinHint(Expression):
1514    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1517class Identifier(Expression):
1518    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1519
1520    @property
1521    def quoted(self) -> bool:
1522        return bool(self.args.get("quoted"))
1523
1524    @property
1525    def hashable_args(self) -> t.Any:
1526        return (self.this, self.quoted)
1527
1528    @property
1529    def output_name(self) -> str:
1530        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):
1533class Index(Expression):
1534    arg_types = {
1535        "this": False,
1536        "table": False,
1537        "using": False,
1538        "where": False,
1539        "columns": False,
1540        "unique": False,
1541        "primary": False,
1542        "amp": False,  # teradata
1543        "partition_by": False,  # teradata
1544    }
arg_types = {'this': False, 'table': False, 'using': False, 'where': False, 'columns': False, 'unique': False, 'primary': False, 'amp': False, 'partition_by': False}
key = 'index'
class Insert(Expression):
1547class Insert(Expression):
1548    arg_types = {
1549        "with": False,
1550        "this": True,
1551        "expression": False,
1552        "conflict": False,
1553        "returning": False,
1554        "overwrite": False,
1555        "exists": False,
1556        "partition": False,
1557        "alternative": False,
1558        "where": False,
1559        "ignore": False,
1560    }
1561
1562    def with_(
1563        self,
1564        alias: ExpOrStr,
1565        as_: ExpOrStr,
1566        recursive: t.Optional[bool] = None,
1567        append: bool = True,
1568        dialect: DialectType = None,
1569        copy: bool = True,
1570        **opts,
1571    ) -> Insert:
1572        """
1573        Append to or set the common table expressions.
1574
1575        Example:
1576            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1577            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1578
1579        Args:
1580            alias: the SQL code string to parse as the table name.
1581                If an `Expression` instance is passed, this is used as-is.
1582            as_: the SQL code string to parse as the table expression.
1583                If an `Expression` instance is passed, it will be used as-is.
1584            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1585            append: if `True`, add to any existing expressions.
1586                Otherwise, this resets the expressions.
1587            dialect: the dialect used to parse the input expression.
1588            copy: if `False`, modify this expression instance in-place.
1589            opts: other options to use to parse the input expressions.
1590
1591        Returns:
1592            The modified expression.
1593        """
1594        return _apply_cte_builder(
1595            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1596        )
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:
1562    def with_(
1563        self,
1564        alias: ExpOrStr,
1565        as_: ExpOrStr,
1566        recursive: t.Optional[bool] = None,
1567        append: bool = True,
1568        dialect: DialectType = None,
1569        copy: bool = True,
1570        **opts,
1571    ) -> Insert:
1572        """
1573        Append to or set the common table expressions.
1574
1575        Example:
1576            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1577            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1578
1579        Args:
1580            alias: the SQL code string to parse as the table name.
1581                If an `Expression` instance is passed, this is used as-is.
1582            as_: the SQL code string to parse as the table expression.
1583                If an `Expression` instance is passed, it will be used as-is.
1584            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1585            append: if `True`, add to any existing expressions.
1586                Otherwise, this resets the expressions.
1587            dialect: the dialect used to parse the input expression.
1588            copy: if `False`, modify this expression instance in-place.
1589            opts: other options to use to parse the input expressions.
1590
1591        Returns:
1592            The modified expression.
1593        """
1594        return _apply_cte_builder(
1595            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1596        )

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):
1599class OnConflict(Expression):
1600    arg_types = {
1601        "duplicate": False,
1602        "expressions": False,
1603        "nothing": False,
1604        "key": False,
1605        "constraint": False,
1606    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1609class Returning(Expression):
1610    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1614class Introducer(Expression):
1615    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1619class National(Expression):
1620    pass
key = 'national'
class LoadData(Expression):
1623class LoadData(Expression):
1624    arg_types = {
1625        "this": True,
1626        "local": False,
1627        "overwrite": False,
1628        "inpath": True,
1629        "partition": False,
1630        "input_format": False,
1631        "serde": False,
1632    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1635class Partition(Expression):
1636    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1639class Fetch(Expression):
1640    arg_types = {
1641        "direction": False,
1642        "count": False,
1643        "percent": False,
1644        "with_ties": False,
1645    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1648class Group(Expression):
1649    arg_types = {
1650        "expressions": False,
1651        "grouping_sets": False,
1652        "cube": False,
1653        "rollup": False,
1654        "totals": False,
1655        "all": False,
1656    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1659class Lambda(Expression):
1660    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1663class Limit(Expression):
1664    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1667class Literal(Condition):
1668    arg_types = {"this": True, "is_string": True}
1669
1670    @property
1671    def hashable_args(self) -> t.Any:
1672        return (self.this, self.args.get("is_string"))
1673
1674    @classmethod
1675    def number(cls, number) -> Literal:
1676        return cls(this=str(number), is_string=False)
1677
1678    @classmethod
1679    def string(cls, string) -> Literal:
1680        return cls(this=str(string), is_string=True)
1681
1682    @property
1683    def output_name(self) -> str:
1684        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1674    @classmethod
1675    def number(cls, number) -> Literal:
1676        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1678    @classmethod
1679    def string(cls, string) -> Literal:
1680        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):
1687class Join(Expression):
1688    arg_types = {
1689        "this": True,
1690        "on": False,
1691        "side": False,
1692        "kind": False,
1693        "using": False,
1694        "method": False,
1695        "global": False,
1696        "hint": False,
1697    }
1698
1699    @property
1700    def method(self) -> str:
1701        return self.text("method").upper()
1702
1703    @property
1704    def kind(self) -> str:
1705        return self.text("kind").upper()
1706
1707    @property
1708    def side(self) -> str:
1709        return self.text("side").upper()
1710
1711    @property
1712    def hint(self) -> str:
1713        return self.text("hint").upper()
1714
1715    @property
1716    def alias_or_name(self) -> str:
1717        return self.this.alias_or_name
1718
1719    def on(
1720        self,
1721        *expressions: t.Optional[ExpOrStr],
1722        append: bool = True,
1723        dialect: DialectType = None,
1724        copy: bool = True,
1725        **opts,
1726    ) -> Join:
1727        """
1728        Append to or set the ON expressions.
1729
1730        Example:
1731            >>> import sqlglot
1732            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1733            'JOIN x ON y = 1'
1734
1735        Args:
1736            *expressions: the SQL code strings to parse.
1737                If an `Expression` instance is passed, it will be used as-is.
1738                Multiple expressions are combined with an AND operator.
1739            append: if `True`, AND the new expressions to any existing expression.
1740                Otherwise, this resets the expression.
1741            dialect: the dialect used to parse the input expressions.
1742            copy: if `False`, modify this expression instance in-place.
1743            opts: other options to use to parse the input expressions.
1744
1745        Returns:
1746            The modified Join expression.
1747        """
1748        join = _apply_conjunction_builder(
1749            *expressions,
1750            instance=self,
1751            arg="on",
1752            append=append,
1753            dialect=dialect,
1754            copy=copy,
1755            **opts,
1756        )
1757
1758        if join.kind == "CROSS":
1759            join.set("kind", None)
1760
1761        return join
1762
1763    def using(
1764        self,
1765        *expressions: t.Optional[ExpOrStr],
1766        append: bool = True,
1767        dialect: DialectType = None,
1768        copy: bool = True,
1769        **opts,
1770    ) -> Join:
1771        """
1772        Append to or set the USING expressions.
1773
1774        Example:
1775            >>> import sqlglot
1776            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1777            'JOIN x USING (foo, bla)'
1778
1779        Args:
1780            *expressions: the SQL code strings to parse.
1781                If an `Expression` instance is passed, it will be used as-is.
1782            append: if `True`, concatenate the new expressions to the existing "using" list.
1783                Otherwise, this resets the expression.
1784            dialect: the dialect used to parse the input expressions.
1785            copy: if `False`, modify this expression instance in-place.
1786            opts: other options to use to parse the input expressions.
1787
1788        Returns:
1789            The modified Join expression.
1790        """
1791        join = _apply_list_builder(
1792            *expressions,
1793            instance=self,
1794            arg="using",
1795            append=append,
1796            dialect=dialect,
1797            copy=copy,
1798            **opts,
1799        )
1800
1801        if join.kind == "CROSS":
1802            join.set("kind", None)
1803
1804        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:
1719    def on(
1720        self,
1721        *expressions: t.Optional[ExpOrStr],
1722        append: bool = True,
1723        dialect: DialectType = None,
1724        copy: bool = True,
1725        **opts,
1726    ) -> Join:
1727        """
1728        Append to or set the ON expressions.
1729
1730        Example:
1731            >>> import sqlglot
1732            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1733            'JOIN x ON y = 1'
1734
1735        Args:
1736            *expressions: the SQL code strings to parse.
1737                If an `Expression` instance is passed, it will be used as-is.
1738                Multiple expressions are combined with an AND operator.
1739            append: if `True`, AND the new expressions to any existing expression.
1740                Otherwise, this resets the expression.
1741            dialect: the dialect used to parse the input expressions.
1742            copy: if `False`, modify this expression instance in-place.
1743            opts: other options to use to parse the input expressions.
1744
1745        Returns:
1746            The modified Join expression.
1747        """
1748        join = _apply_conjunction_builder(
1749            *expressions,
1750            instance=self,
1751            arg="on",
1752            append=append,
1753            dialect=dialect,
1754            copy=copy,
1755            **opts,
1756        )
1757
1758        if join.kind == "CROSS":
1759            join.set("kind", None)
1760
1761        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:
1763    def using(
1764        self,
1765        *expressions: t.Optional[ExpOrStr],
1766        append: bool = True,
1767        dialect: DialectType = None,
1768        copy: bool = True,
1769        **opts,
1770    ) -> Join:
1771        """
1772        Append to or set the USING expressions.
1773
1774        Example:
1775            >>> import sqlglot
1776            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1777            'JOIN x USING (foo, bla)'
1778
1779        Args:
1780            *expressions: the SQL code strings to parse.
1781                If an `Expression` instance is passed, it will be used as-is.
1782            append: if `True`, concatenate the new expressions to the existing "using" list.
1783                Otherwise, this resets the expression.
1784            dialect: the dialect used to parse the input expressions.
1785            copy: if `False`, modify this expression instance in-place.
1786            opts: other options to use to parse the input expressions.
1787
1788        Returns:
1789            The modified Join expression.
1790        """
1791        join = _apply_list_builder(
1792            *expressions,
1793            instance=self,
1794            arg="using",
1795            append=append,
1796            dialect=dialect,
1797            copy=copy,
1798            **opts,
1799        )
1800
1801        if join.kind == "CROSS":
1802            join.set("kind", None)
1803
1804        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):
1807class Lateral(UDTF):
1808    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):
1811class MatchRecognize(Expression):
1812    arg_types = {
1813        "partition_by": False,
1814        "order": False,
1815        "measures": False,
1816        "rows": False,
1817        "after": False,
1818        "pattern": False,
1819        "define": False,
1820        "alias": False,
1821    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1826class Final(Expression):
1827    pass
key = 'final'
class Offset(Expression):
1830class Offset(Expression):
1831    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1834class Order(Expression):
1835    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1840class Cluster(Order):
1841    pass
key = 'cluster'
class Distribute(Order):
1844class Distribute(Order):
1845    pass
key = 'distribute'
class Sort(Order):
1848class Sort(Order):
1849    pass
key = 'sort'
class Ordered(Expression):
1852class Ordered(Expression):
1853    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1856class Property(Expression):
1857    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1860class AlgorithmProperty(Property):
1861    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1864class AutoIncrementProperty(Property):
1865    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1868class BlockCompressionProperty(Property):
1869    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):
1872class CharacterSetProperty(Property):
1873    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1876class ChecksumProperty(Property):
1877    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1880class CollateProperty(Property):
1881    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1884class CopyGrantsProperty(Property):
1885    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1888class DataBlocksizeProperty(Property):
1889    arg_types = {
1890        "size": False,
1891        "units": False,
1892        "minimum": False,
1893        "maximum": False,
1894        "default": False,
1895    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1898class DefinerProperty(Property):
1899    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1902class DistKeyProperty(Property):
1903    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1906class DistStyleProperty(Property):
1907    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1910class EngineProperty(Property):
1911    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1914class ToTableProperty(Property):
1915    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1918class ExecuteAsProperty(Property):
1919    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1922class ExternalProperty(Property):
1923    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1926class FallbackProperty(Property):
1927    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1930class FileFormatProperty(Property):
1931    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1934class FreespaceProperty(Property):
1935    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1938class InputOutputFormat(Expression):
1939    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1942class IsolatedLoadingProperty(Property):
1943    arg_types = {
1944        "no": True,
1945        "concurrent": True,
1946        "for_all": True,
1947        "for_insert": True,
1948        "for_none": True,
1949    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1952class JournalProperty(Property):
1953    arg_types = {
1954        "no": False,
1955        "dual": False,
1956        "before": False,
1957        "local": False,
1958        "after": False,
1959    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1962class LanguageProperty(Property):
1963    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1967class ClusteredByProperty(Property):
1968    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1971class DictProperty(Property):
1972    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1975class DictSubProperty(Property):
1976    pass
key = 'dictsubproperty'
class DictRange(Property):
1979class DictRange(Property):
1980    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1985class OnCluster(Property):
1986    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1989class LikeProperty(Property):
1990    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1993class LocationProperty(Property):
1994    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
1997class LockingProperty(Property):
1998    arg_types = {
1999        "this": False,
2000        "kind": True,
2001        "for_or_in": True,
2002        "lock_type": True,
2003        "override": False,
2004    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2007class LogProperty(Property):
2008    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2011class MaterializedProperty(Property):
2012    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2015class MergeBlockRatioProperty(Property):
2016    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):
2019class NoPrimaryIndexProperty(Property):
2020    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
2023class OnCommitProperty(Property):
2024    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2027class PartitionedByProperty(Property):
2028    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2031class ReturnsProperty(Property):
2032    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2035class RowFormatProperty(Property):
2036    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2039class RowFormatDelimitedProperty(Property):
2040    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2041    arg_types = {
2042        "fields": False,
2043        "escaped": False,
2044        "collection_items": False,
2045        "map_keys": False,
2046        "lines": False,
2047        "null": False,
2048        "serde": False,
2049    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2052class RowFormatSerdeProperty(Property):
2053    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2057class QueryTransform(Expression):
2058    arg_types = {
2059        "expressions": True,
2060        "command_script": True,
2061        "schema": False,
2062        "row_format_before": False,
2063        "record_writer": False,
2064        "row_format_after": False,
2065        "record_reader": False,
2066    }
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):
2069class SchemaCommentProperty(Property):
2070    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2073class SerdeProperties(Property):
2074    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2077class SetProperty(Property):
2078    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2081class SettingsProperty(Property):
2082    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2085class SortKeyProperty(Property):
2086    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2089class SqlSecurityProperty(Property):
2090    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2093class StabilityProperty(Property):
2094    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2097class TemporaryProperty(Property):
2098    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2101class TransientProperty(Property):
2102    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2105class VolatileProperty(Property):
2106    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2109class WithDataProperty(Property):
2110    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2113class WithJournalTableProperty(Property):
2114    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2117class Properties(Expression):
2118    arg_types = {"expressions": True}
2119
2120    NAME_TO_PROPERTY = {
2121        "ALGORITHM": AlgorithmProperty,
2122        "AUTO_INCREMENT": AutoIncrementProperty,
2123        "CHARACTER SET": CharacterSetProperty,
2124        "CLUSTERED_BY": ClusteredByProperty,
2125        "COLLATE": CollateProperty,
2126        "COMMENT": SchemaCommentProperty,
2127        "DEFINER": DefinerProperty,
2128        "DISTKEY": DistKeyProperty,
2129        "DISTSTYLE": DistStyleProperty,
2130        "ENGINE": EngineProperty,
2131        "EXECUTE AS": ExecuteAsProperty,
2132        "FORMAT": FileFormatProperty,
2133        "LANGUAGE": LanguageProperty,
2134        "LOCATION": LocationProperty,
2135        "PARTITIONED_BY": PartitionedByProperty,
2136        "RETURNS": ReturnsProperty,
2137        "ROW_FORMAT": RowFormatProperty,
2138        "SORTKEY": SortKeyProperty,
2139    }
2140
2141    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2142
2143    # CREATE property locations
2144    # Form: schema specified
2145    #   create [POST_CREATE]
2146    #     table a [POST_NAME]
2147    #     (b int) [POST_SCHEMA]
2148    #     with ([POST_WITH])
2149    #     index (b) [POST_INDEX]
2150    #
2151    # Form: alias selection
2152    #   create [POST_CREATE]
2153    #     table a [POST_NAME]
2154    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2155    #     index (c) [POST_INDEX]
2156    class Location(AutoName):
2157        POST_CREATE = auto()
2158        POST_NAME = auto()
2159        POST_SCHEMA = auto()
2160        POST_WITH = auto()
2161        POST_ALIAS = auto()
2162        POST_EXPRESSION = auto()
2163        POST_INDEX = auto()
2164        UNSUPPORTED = auto()
2165
2166    @classmethod
2167    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2168        expressions = []
2169        for key, value in properties_dict.items():
2170            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2171            if property_cls:
2172                expressions.append(property_cls(this=convert(value)))
2173            else:
2174                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2175
2176        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:
2166    @classmethod
2167    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2168        expressions = []
2169        for key, value in properties_dict.items():
2170            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2171            if property_cls:
2172                expressions.append(property_cls(this=convert(value)))
2173            else:
2174                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2175
2176        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2156    class Location(AutoName):
2157        POST_CREATE = auto()
2158        POST_NAME = auto()
2159        POST_SCHEMA = auto()
2160        POST_WITH = auto()
2161        POST_ALIAS = auto()
2162        POST_EXPRESSION = auto()
2163        POST_INDEX = auto()
2164        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):
2179class Qualify(Expression):
2180    pass
key = 'qualify'
class Return(Expression):
2184class Return(Expression):
2185    pass
key = 'return'
class Reference(Expression):
2188class Reference(Expression):
2189    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2192class Tuple(Expression):
2193    arg_types = {"expressions": False}
2194
2195    def isin(
2196        self,
2197        *expressions: t.Any,
2198        query: t.Optional[ExpOrStr] = None,
2199        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2200        copy: bool = True,
2201        **opts,
2202    ) -> In:
2203        return In(
2204            this=_maybe_copy(self, copy),
2205            expressions=[convert(e, copy=copy) for e in expressions],
2206            query=maybe_parse(query, copy=copy, **opts) if query else None,
2207            unnest=Unnest(
2208                expressions=[
2209                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2210                ]
2211            )
2212            if unnest
2213            else None,
2214        )
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:
2195    def isin(
2196        self,
2197        *expressions: t.Any,
2198        query: t.Optional[ExpOrStr] = None,
2199        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2200        copy: bool = True,
2201        **opts,
2202    ) -> In:
2203        return In(
2204            this=_maybe_copy(self, copy),
2205            expressions=[convert(e, copy=copy) for e in expressions],
2206            query=maybe_parse(query, copy=copy, **opts) if query else None,
2207            unnest=Unnest(
2208                expressions=[
2209                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2210                ]
2211            )
2212            if unnest
2213            else None,
2214        )
key = 'tuple'
class Subqueryable(Unionable):
2217class Subqueryable(Unionable):
2218    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2219        """
2220        Convert this expression to an aliased expression that can be used as a Subquery.
2221
2222        Example:
2223            >>> subquery = Select().select("x").from_("tbl").subquery()
2224            >>> Select().select("x").from_(subquery).sql()
2225            'SELECT x FROM (SELECT x FROM tbl)'
2226
2227        Args:
2228            alias (str | Identifier): an optional alias for the subquery
2229            copy (bool): if `False`, modify this expression instance in-place.
2230
2231        Returns:
2232            Alias: the subquery
2233        """
2234        instance = _maybe_copy(self, copy)
2235        if not isinstance(alias, Expression):
2236            alias = TableAlias(this=to_identifier(alias)) if alias else None
2237
2238        return Subquery(this=instance, alias=alias)
2239
2240    def limit(
2241        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2242    ) -> Select:
2243        raise NotImplementedError
2244
2245    @property
2246    def ctes(self):
2247        with_ = self.args.get("with")
2248        if not with_:
2249            return []
2250        return with_.expressions
2251
2252    @property
2253    def selects(self) -> t.List[Expression]:
2254        raise NotImplementedError("Subqueryable objects must implement `selects`")
2255
2256    @property
2257    def named_selects(self) -> t.List[str]:
2258        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2259
2260    def with_(
2261        self,
2262        alias: ExpOrStr,
2263        as_: ExpOrStr,
2264        recursive: t.Optional[bool] = None,
2265        append: bool = True,
2266        dialect: DialectType = None,
2267        copy: bool = True,
2268        **opts,
2269    ) -> Subqueryable:
2270        """
2271        Append to or set the common table expressions.
2272
2273        Example:
2274            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2275            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2276
2277        Args:
2278            alias: the SQL code string to parse as the table name.
2279                If an `Expression` instance is passed, this is used as-is.
2280            as_: the SQL code string to parse as the table expression.
2281                If an `Expression` instance is passed, it will be used as-is.
2282            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2283            append: if `True`, add to any existing expressions.
2284                Otherwise, this resets the expressions.
2285            dialect: the dialect used to parse the input expression.
2286            copy: if `False`, modify this expression instance in-place.
2287            opts: other options to use to parse the input expressions.
2288
2289        Returns:
2290            The modified expression.
2291        """
2292        return _apply_cte_builder(
2293            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2294        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2218    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2219        """
2220        Convert this expression to an aliased expression that can be used as a Subquery.
2221
2222        Example:
2223            >>> subquery = Select().select("x").from_("tbl").subquery()
2224            >>> Select().select("x").from_(subquery).sql()
2225            'SELECT x FROM (SELECT x FROM tbl)'
2226
2227        Args:
2228            alias (str | Identifier): an optional alias for the subquery
2229            copy (bool): if `False`, modify this expression instance in-place.
2230
2231        Returns:
2232            Alias: the subquery
2233        """
2234        instance = _maybe_copy(self, copy)
2235        if not isinstance(alias, Expression):
2236            alias = TableAlias(this=to_identifier(alias)) if alias else None
2237
2238        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:
2240    def limit(
2241        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2242    ) -> Select:
2243        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:
2260    def with_(
2261        self,
2262        alias: ExpOrStr,
2263        as_: ExpOrStr,
2264        recursive: t.Optional[bool] = None,
2265        append: bool = True,
2266        dialect: DialectType = None,
2267        copy: bool = True,
2268        **opts,
2269    ) -> Subqueryable:
2270        """
2271        Append to or set the common table expressions.
2272
2273        Example:
2274            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2275            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2276
2277        Args:
2278            alias: the SQL code string to parse as the table name.
2279                If an `Expression` instance is passed, this is used as-is.
2280            as_: the SQL code string to parse as the table expression.
2281                If an `Expression` instance is passed, it will be used as-is.
2282            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2283            append: if `True`, add to any existing expressions.
2284                Otherwise, this resets the expressions.
2285            dialect: the dialect used to parse the input expression.
2286            copy: if `False`, modify this expression instance in-place.
2287            opts: other options to use to parse the input expressions.
2288
2289        Returns:
2290            The modified expression.
2291        """
2292        return _apply_cte_builder(
2293            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2294        )

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

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

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:
2577    def group_by(
2578        self,
2579        *expressions: t.Optional[ExpOrStr],
2580        append: bool = True,
2581        dialect: DialectType = None,
2582        copy: bool = True,
2583        **opts,
2584    ) -> Select:
2585        """
2586        Set the GROUP BY expression.
2587
2588        Example:
2589            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2590            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2591
2592        Args:
2593            *expressions: the SQL code strings to parse.
2594                If a `Group` instance is passed, this is used as-is.
2595                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2596                If nothing is passed in then a group by is not applied to the expression
2597            append: if `True`, add to any existing expressions.
2598                Otherwise, this flattens all the `Group` expression into a single expression.
2599            dialect: the dialect used to parse the input expression.
2600            copy: if `False`, modify this expression instance in-place.
2601            opts: other options to use to parse the input expressions.
2602
2603        Returns:
2604            The modified Select expression.
2605        """
2606        if not expressions:
2607            return self if not copy else self.copy()
2608
2609        return _apply_child_list_builder(
2610            *expressions,
2611            instance=self,
2612            arg="group",
2613            append=append,
2614            copy=copy,
2615            prefix="GROUP BY",
2616            into=Group,
2617            dialect=dialect,
2618            **opts,
2619        )

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

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

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

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

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

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:
2807    def select(
2808        self,
2809        *expressions: t.Optional[ExpOrStr],
2810        append: bool = True,
2811        dialect: DialectType = None,
2812        copy: bool = True,
2813        **opts,
2814    ) -> Select:
2815        """
2816        Append to or set the SELECT expressions.
2817
2818        Example:
2819            >>> Select().select("x", "y").sql()
2820            'SELECT x, y'
2821
2822        Args:
2823            *expressions: the SQL code strings to parse.
2824                If an `Expression` instance is passed, it will be used as-is.
2825            append: if `True`, add to any existing expressions.
2826                Otherwise, this resets the expressions.
2827            dialect: the dialect used to parse the input expressions.
2828            copy: if `False`, modify this expression instance in-place.
2829            opts: other options to use to parse the input expressions.
2830
2831        Returns:
2832            The modified Select expression.
2833        """
2834        return _apply_list_builder(
2835            *expressions,
2836            instance=self,
2837            arg="expressions",
2838            append=append,
2839            dialect=dialect,
2840            copy=copy,
2841            **opts,
2842        )

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:
2844    def lateral(
2845        self,
2846        *expressions: t.Optional[ExpOrStr],
2847        append: bool = True,
2848        dialect: DialectType = None,
2849        copy: bool = True,
2850        **opts,
2851    ) -> Select:
2852        """
2853        Append to or set the LATERAL expressions.
2854
2855        Example:
2856            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2857            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2858
2859        Args:
2860            *expressions: the SQL code strings to parse.
2861                If an `Expression` instance is passed, it will be used as-is.
2862            append: if `True`, add to any existing expressions.
2863                Otherwise, this resets the expressions.
2864            dialect: the dialect used to parse the input expressions.
2865            copy: if `False`, modify this expression instance in-place.
2866            opts: other options to use to parse the input expressions.
2867
2868        Returns:
2869            The modified Select expression.
2870        """
2871        return _apply_list_builder(
2872            *expressions,
2873            instance=self,
2874            arg="laterals",
2875            append=append,
2876            into=Lateral,
2877            prefix="LATERAL VIEW",
2878            dialect=dialect,
2879            copy=copy,
2880            **opts,
2881        )

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

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

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:
3020    def having(
3021        self,
3022        *expressions: t.Optional[ExpOrStr],
3023        append: bool = True,
3024        dialect: DialectType = None,
3025        copy: bool = True,
3026        **opts,
3027    ) -> Select:
3028        """
3029        Append to or set the HAVING expressions.
3030
3031        Example:
3032            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3033            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3034
3035        Args:
3036            *expressions: the SQL code strings to parse.
3037                If an `Expression` instance is passed, it will be used as-is.
3038                Multiple expressions are combined with an AND operator.
3039            append: if `True`, AND the new expressions to any existing expression.
3040                Otherwise, this resets the expression.
3041            dialect: the dialect used to parse the input expressions.
3042            copy: if `False`, modify this expression instance in-place.
3043            opts: other options to use to parse the input expressions.
3044
3045        Returns:
3046            The modified Select expression.
3047        """
3048        return _apply_conjunction_builder(
3049            *expressions,
3050            instance=self,
3051            arg="having",
3052            append=append,
3053            into=Having,
3054            dialect=dialect,
3055            copy=copy,
3056            **opts,
3057        )

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:
3059    def window(
3060        self,
3061        *expressions: t.Optional[ExpOrStr],
3062        append: bool = True,
3063        dialect: DialectType = None,
3064        copy: bool = True,
3065        **opts,
3066    ) -> Select:
3067        return _apply_list_builder(
3068            *expressions,
3069            instance=self,
3070            arg="windows",
3071            append=append,
3072            into=Window,
3073            dialect=dialect,
3074            copy=copy,
3075            **opts,
3076        )
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:
3078    def qualify(
3079        self,
3080        *expressions: t.Optional[ExpOrStr],
3081        append: bool = True,
3082        dialect: DialectType = None,
3083        copy: bool = True,
3084        **opts,
3085    ) -> Select:
3086        return _apply_conjunction_builder(
3087            *expressions,
3088            instance=self,
3089            arg="qualify",
3090            append=append,
3091            into=Qualify,
3092            dialect=dialect,
3093            copy=copy,
3094            **opts,
3095        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3097    def distinct(
3098        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3099    ) -> Select:
3100        """
3101        Set the OFFSET expression.
3102
3103        Example:
3104            >>> Select().from_("tbl").select("x").distinct().sql()
3105            'SELECT DISTINCT x FROM tbl'
3106
3107        Args:
3108            ons: the expressions to distinct on
3109            distinct: whether the Select should be distinct
3110            copy: if `False`, modify this expression instance in-place.
3111
3112        Returns:
3113            Select: the modified expression.
3114        """
3115        instance = _maybe_copy(self, copy)
3116        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3117        instance.set("distinct", Distinct(on=on) if distinct else None)
3118        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:
3120    def ctas(
3121        self,
3122        table: ExpOrStr,
3123        properties: t.Optional[t.Dict] = None,
3124        dialect: DialectType = None,
3125        copy: bool = True,
3126        **opts,
3127    ) -> Create:
3128        """
3129        Convert this expression to a CREATE TABLE AS statement.
3130
3131        Example:
3132            >>> Select().select("*").from_("tbl").ctas("x").sql()
3133            'CREATE TABLE x AS SELECT * FROM tbl'
3134
3135        Args:
3136            table: the SQL code string to parse as the table name.
3137                If another `Expression` instance is passed, it will be used as-is.
3138            properties: an optional mapping of table properties
3139            dialect: the dialect used to parse the input table.
3140            copy: if `False`, modify this expression instance in-place.
3141            opts: other options to use to parse the input table.
3142
3143        Returns:
3144            The new Create expression.
3145        """
3146        instance = _maybe_copy(self, copy)
3147        table_expression = maybe_parse(
3148            table,
3149            into=Table,
3150            dialect=dialect,
3151            **opts,
3152        )
3153        properties_expression = None
3154        if properties:
3155            properties_expression = Properties.from_dict(properties)
3156
3157        return Create(
3158            this=table_expression,
3159            kind="table",
3160            expression=instance,
3161            properties=properties_expression,
3162        )

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:
3164    def lock(self, update: bool = True, copy: bool = True) -> Select:
3165        """
3166        Set the locking read mode for this expression.
3167
3168        Examples:
3169            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3170            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3171
3172            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3173            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3174
3175        Args:
3176            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3177            copy: if `False`, modify this expression instance in-place.
3178
3179        Returns:
3180            The modified expression.
3181        """
3182        inst = _maybe_copy(self, copy)
3183        inst.set("locks", [Lock(update=update)])
3184
3185        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:
3187    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3188        """
3189        Set hints for this expression.
3190
3191        Examples:
3192            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3193            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3194
3195        Args:
3196            hints: The SQL code strings to parse as the hints.
3197                If an `Expression` instance is passed, it will be used as-is.
3198            dialect: The dialect used to parse the hints.
3199            copy: If `False`, modify this expression instance in-place.
3200
3201        Returns:
3202            The modified expression.
3203        """
3204        inst = _maybe_copy(self, copy)
3205        inst.set(
3206            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3207        )
3208
3209        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):
3224class Subquery(DerivedTable, Unionable):
3225    arg_types = {
3226        "this": True,
3227        "alias": False,
3228        "with": False,
3229        **QUERY_MODIFIERS,
3230    }
3231
3232    def unnest(self):
3233        """
3234        Returns the first non subquery.
3235        """
3236        expression = self
3237        while isinstance(expression, Subquery):
3238            expression = expression.this
3239        return expression
3240
3241    @property
3242    def is_star(self) -> bool:
3243        return self.this.is_star
3244
3245    @property
3246    def output_name(self) -> str:
3247        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):
3232    def unnest(self):
3233        """
3234        Returns the first non subquery.
3235        """
3236        expression = self
3237        while isinstance(expression, Subquery):
3238            expression = expression.this
3239        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):
3250class TableSample(Expression):
3251    arg_types = {
3252        "this": False,
3253        "method": False,
3254        "bucket_numerator": False,
3255        "bucket_denominator": False,
3256        "bucket_field": False,
3257        "percent": False,
3258        "rows": False,
3259        "size": False,
3260        "seed": False,
3261        "kind": False,
3262    }
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):
3265class Tag(Expression):
3266    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3267
3268    arg_types = {
3269        "this": False,
3270        "prefix": False,
3271        "postfix": False,
3272    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3277class Pivot(Expression):
3278    arg_types = {
3279        "this": False,
3280        "alias": False,
3281        "expressions": True,
3282        "field": False,
3283        "unpivot": False,
3284        "using": False,
3285        "group": False,
3286        "columns": False,
3287    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3290class Window(Expression):
3291    arg_types = {
3292        "this": True,
3293        "partition_by": False,
3294        "order": False,
3295        "spec": False,
3296        "alias": False,
3297        "over": False,
3298        "first": False,
3299    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3302class WindowSpec(Expression):
3303    arg_types = {
3304        "kind": False,
3305        "start": False,
3306        "start_side": False,
3307        "end": False,
3308        "end_side": False,
3309    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3312class Where(Expression):
3313    pass
key = 'where'
class Star(Expression):
3316class Star(Expression):
3317    arg_types = {"except": False, "replace": False}
3318
3319    @property
3320    def name(self) -> str:
3321        return "*"
3322
3323    @property
3324    def output_name(self) -> str:
3325        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):
3328class Parameter(Condition):
3329    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3332class SessionParameter(Condition):
3333    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3336class Placeholder(Condition):
3337    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3340class Null(Condition):
3341    arg_types: t.Dict[str, t.Any] = {}
3342
3343    @property
3344    def name(self) -> str:
3345        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3348class Boolean(Condition):
3349    pass
key = 'boolean'
class DataTypeSize(Expression):
3352class DataTypeSize(Expression):
3353    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3356class DataType(Expression):
3357    arg_types = {
3358        "this": True,
3359        "expressions": False,
3360        "nested": False,
3361        "values": False,
3362        "prefix": False,
3363    }
3364
3365    class Type(AutoName):
3366        ARRAY = auto()
3367        BIGDECIMAL = auto()
3368        BIGINT = auto()
3369        BIGSERIAL = auto()
3370        BINARY = auto()
3371        BIT = auto()
3372        BOOLEAN = auto()
3373        CHAR = auto()
3374        DATE = auto()
3375        DATETIME = auto()
3376        DATETIME64 = auto()
3377        ENUM = auto()
3378        INT4RANGE = auto()
3379        INT4MULTIRANGE = auto()
3380        INT8RANGE = auto()
3381        INT8MULTIRANGE = auto()
3382        NUMRANGE = auto()
3383        NUMMULTIRANGE = auto()
3384        TSRANGE = auto()
3385        TSMULTIRANGE = auto()
3386        TSTZRANGE = auto()
3387        TSTZMULTIRANGE = auto()
3388        DATERANGE = auto()
3389        DATEMULTIRANGE = auto()
3390        DECIMAL = auto()
3391        DOUBLE = auto()
3392        FLOAT = auto()
3393        GEOGRAPHY = auto()
3394        GEOMETRY = auto()
3395        HLLSKETCH = auto()
3396        HSTORE = auto()
3397        IMAGE = auto()
3398        INET = auto()
3399        IPADDRESS = auto()
3400        IPPREFIX = auto()
3401        INT = auto()
3402        INT128 = auto()
3403        INT256 = auto()
3404        INTERVAL = auto()
3405        JSON = auto()
3406        JSONB = auto()
3407        LONGBLOB = auto()
3408        LONGTEXT = auto()
3409        MAP = auto()
3410        MEDIUMBLOB = auto()
3411        MEDIUMTEXT = auto()
3412        MONEY = auto()
3413        NCHAR = auto()
3414        NULL = auto()
3415        NULLABLE = auto()
3416        NVARCHAR = auto()
3417        OBJECT = auto()
3418        ROWVERSION = auto()
3419        SERIAL = auto()
3420        SET = auto()
3421        SMALLINT = auto()
3422        SMALLMONEY = auto()
3423        SMALLSERIAL = auto()
3424        STRUCT = auto()
3425        SUPER = auto()
3426        TEXT = auto()
3427        TIME = auto()
3428        TIMESTAMP = auto()
3429        TIMESTAMPTZ = auto()
3430        TIMESTAMPLTZ = auto()
3431        TINYINT = auto()
3432        UBIGINT = auto()
3433        UINT = auto()
3434        USMALLINT = auto()
3435        UTINYINT = auto()
3436        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3437        UINT128 = auto()
3438        UINT256 = auto()
3439        UNIQUEIDENTIFIER = auto()
3440        USERDEFINED = "USER-DEFINED"
3441        UUID = auto()
3442        VARBINARY = auto()
3443        VARCHAR = auto()
3444        VARIANT = auto()
3445        XML = auto()
3446
3447    TEXT_TYPES = {
3448        Type.CHAR,
3449        Type.NCHAR,
3450        Type.VARCHAR,
3451        Type.NVARCHAR,
3452        Type.TEXT,
3453    }
3454
3455    INTEGER_TYPES = {
3456        Type.INT,
3457        Type.TINYINT,
3458        Type.SMALLINT,
3459        Type.BIGINT,
3460        Type.INT128,
3461        Type.INT256,
3462    }
3463
3464    FLOAT_TYPES = {
3465        Type.FLOAT,
3466        Type.DOUBLE,
3467    }
3468
3469    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3470
3471    TEMPORAL_TYPES = {
3472        Type.TIME,
3473        Type.TIMESTAMP,
3474        Type.TIMESTAMPTZ,
3475        Type.TIMESTAMPLTZ,
3476        Type.DATE,
3477        Type.DATETIME,
3478        Type.DATETIME64,
3479    }
3480
3481    META_TYPES = {"UNKNOWN", "NULL"}
3482
3483    @classmethod
3484    def build(
3485        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3486    ) -> DataType:
3487        from sqlglot import parse_one
3488
3489        if isinstance(dtype, str):
3490            upper = dtype.upper()
3491            if upper in DataType.META_TYPES:
3492                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3493            else:
3494                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3495
3496            if data_type_exp is None:
3497                raise ValueError(f"Unparsable data type value: {dtype}")
3498        elif isinstance(dtype, DataType.Type):
3499            data_type_exp = DataType(this=dtype)
3500        elif isinstance(dtype, DataType):
3501            return dtype
3502        else:
3503            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3504
3505        return DataType(**{**data_type_exp.args, **kwargs})
3506
3507    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3508        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.TEXT: 'TEXT'>, <Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>}
INTEGER_TYPES = {<Type.BIGINT: 'BIGINT'>, <Type.INT: 'INT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.INT256: 'INT256'>, <Type.TINYINT: 'TINYINT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT: 'INT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.INT256: 'INT256'>, <Type.TINYINT: 'TINYINT'>}
TEMPORAL_TYPES = {<Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATETIME64: 'DATETIME64'>, <Type.TIME: 'TIME'>, <Type.DATETIME: 'DATETIME'>, <Type.DATE: 'DATE'>}
META_TYPES = {'UNKNOWN', 'NULL'}
@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:
3483    @classmethod
3484    def build(
3485        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3486    ) -> DataType:
3487        from sqlglot import parse_one
3488
3489        if isinstance(dtype, str):
3490            upper = dtype.upper()
3491            if upper in DataType.META_TYPES:
3492                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3493            else:
3494                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3495
3496            if data_type_exp is None:
3497                raise ValueError(f"Unparsable data type value: {dtype}")
3498        elif isinstance(dtype, DataType.Type):
3499            data_type_exp = DataType(this=dtype)
3500        elif isinstance(dtype, DataType):
3501            return dtype
3502        else:
3503            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3504
3505        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3507    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3508        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3365    class Type(AutoName):
3366        ARRAY = auto()
3367        BIGDECIMAL = auto()
3368        BIGINT = auto()
3369        BIGSERIAL = auto()
3370        BINARY = auto()
3371        BIT = auto()
3372        BOOLEAN = auto()
3373        CHAR = auto()
3374        DATE = auto()
3375        DATETIME = auto()
3376        DATETIME64 = auto()
3377        ENUM = auto()
3378        INT4RANGE = auto()
3379        INT4MULTIRANGE = auto()
3380        INT8RANGE = auto()
3381        INT8MULTIRANGE = auto()
3382        NUMRANGE = auto()
3383        NUMMULTIRANGE = auto()
3384        TSRANGE = auto()
3385        TSMULTIRANGE = auto()
3386        TSTZRANGE = auto()
3387        TSTZMULTIRANGE = auto()
3388        DATERANGE = auto()
3389        DATEMULTIRANGE = auto()
3390        DECIMAL = auto()
3391        DOUBLE = auto()
3392        FLOAT = auto()
3393        GEOGRAPHY = auto()
3394        GEOMETRY = auto()
3395        HLLSKETCH = auto()
3396        HSTORE = auto()
3397        IMAGE = auto()
3398        INET = auto()
3399        IPADDRESS = auto()
3400        IPPREFIX = auto()
3401        INT = auto()
3402        INT128 = auto()
3403        INT256 = auto()
3404        INTERVAL = auto()
3405        JSON = auto()
3406        JSONB = auto()
3407        LONGBLOB = auto()
3408        LONGTEXT = auto()
3409        MAP = auto()
3410        MEDIUMBLOB = auto()
3411        MEDIUMTEXT = auto()
3412        MONEY = auto()
3413        NCHAR = auto()
3414        NULL = auto()
3415        NULLABLE = auto()
3416        NVARCHAR = auto()
3417        OBJECT = auto()
3418        ROWVERSION = auto()
3419        SERIAL = auto()
3420        SET = auto()
3421        SMALLINT = auto()
3422        SMALLMONEY = auto()
3423        SMALLSERIAL = auto()
3424        STRUCT = auto()
3425        SUPER = auto()
3426        TEXT = auto()
3427        TIME = auto()
3428        TIMESTAMP = auto()
3429        TIMESTAMPTZ = auto()
3430        TIMESTAMPLTZ = auto()
3431        TINYINT = auto()
3432        UBIGINT = auto()
3433        UINT = auto()
3434        USMALLINT = auto()
3435        UTINYINT = auto()
3436        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3437        UINT128 = auto()
3438        UINT256 = auto()
3439        UNIQUEIDENTIFIER = auto()
3440        USERDEFINED = "USER-DEFINED"
3441        UUID = auto()
3442        VARBINARY = auto()
3443        VARCHAR = auto()
3444        VARIANT = auto()
3445        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):
3512class PseudoType(Expression):
3513    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3517class SubqueryPredicate(Predicate):
3518    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3521class All(SubqueryPredicate):
3522    pass
key = 'all'
class Any(SubqueryPredicate):
3525class Any(SubqueryPredicate):
3526    pass
key = 'any'
class Exists(SubqueryPredicate):
3529class Exists(SubqueryPredicate):
3530    pass
key = 'exists'
class Command(Expression):
3535class Command(Expression):
3536    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3539class Transaction(Expression):
3540    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3543class Commit(Expression):
3544    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3547class Rollback(Expression):
3548    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3551class AlterTable(Expression):
3552    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3555class AddConstraint(Expression):
3556    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3559class DropPartition(Expression):
3560    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3564class Binary(Condition):
3565    arg_types = {"this": True, "expression": True}
3566
3567    @property
3568    def left(self):
3569        return self.this
3570
3571    @property
3572    def right(self):
3573        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3576class Add(Binary):
3577    pass
key = 'add'
class Connector(Binary):
3580class Connector(Binary):
3581    pass
key = 'connector'
class And(Connector):
3584class And(Connector):
3585    pass
key = 'and'
class Or(Connector):
3588class Or(Connector):
3589    pass
key = 'or'
class BitwiseAnd(Binary):
3592class BitwiseAnd(Binary):
3593    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3596class BitwiseLeftShift(Binary):
3597    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3600class BitwiseOr(Binary):
3601    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3604class BitwiseRightShift(Binary):
3605    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3608class BitwiseXor(Binary):
3609    pass
key = 'bitwisexor'
class Div(Binary):
3612class Div(Binary):
3613    pass
key = 'div'
class Overlaps(Binary):
3616class Overlaps(Binary):
3617    pass
key = 'overlaps'
class Dot(Binary):
3620class Dot(Binary):
3621    @property
3622    def name(self) -> str:
3623        return self.expression.name
3624
3625    @property
3626    def output_name(self) -> str:
3627        return self.name
3628
3629    @classmethod
3630    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3631        """Build a Dot object with a sequence of expressions."""
3632        if len(expressions) < 2:
3633            raise ValueError(f"Dot requires >= 2 expressions.")
3634
3635        a, b, *expressions = expressions
3636        dot = Dot(this=a, expression=b)
3637
3638        for expression in expressions:
3639            dot = Dot(this=dot, expression=expression)
3640
3641        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:
3629    @classmethod
3630    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3631        """Build a Dot object with a sequence of expressions."""
3632        if len(expressions) < 2:
3633            raise ValueError(f"Dot requires >= 2 expressions.")
3634
3635        a, b, *expressions = expressions
3636        dot = Dot(this=a, expression=b)
3637
3638        for expression in expressions:
3639            dot = Dot(this=dot, expression=expression)
3640
3641        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3644class DPipe(Binary):
3645    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3648class SafeDPipe(DPipe):
3649    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3652class EQ(Binary, Predicate):
3653    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3656class NullSafeEQ(Binary, Predicate):
3657    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3660class NullSafeNEQ(Binary, Predicate):
3661    pass
key = 'nullsafeneq'
class Distance(Binary):
3664class Distance(Binary):
3665    pass
key = 'distance'
class Escape(Binary):
3668class Escape(Binary):
3669    pass
key = 'escape'
class Glob(Binary, Predicate):
3672class Glob(Binary, Predicate):
3673    pass
key = 'glob'
class GT(Binary, Predicate):
3676class GT(Binary, Predicate):
3677    pass
key = 'gt'
class GTE(Binary, Predicate):
3680class GTE(Binary, Predicate):
3681    pass
key = 'gte'
class ILike(Binary, Predicate):
3684class ILike(Binary, Predicate):
3685    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3688class ILikeAny(Binary, Predicate):
3689    pass
key = 'ilikeany'
class IntDiv(Binary):
3692class IntDiv(Binary):
3693    pass
key = 'intdiv'
class Is(Binary, Predicate):
3696class Is(Binary, Predicate):
3697    pass
key = 'is'
class Kwarg(Binary):
3700class Kwarg(Binary):
3701    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3704class Like(Binary, Predicate):
3705    pass
key = 'like'
class LikeAny(Binary, Predicate):
3708class LikeAny(Binary, Predicate):
3709    pass
key = 'likeany'
class LT(Binary, Predicate):
3712class LT(Binary, Predicate):
3713    pass
key = 'lt'
class LTE(Binary, Predicate):
3716class LTE(Binary, Predicate):
3717    pass
key = 'lte'
class Mod(Binary):
3720class Mod(Binary):
3721    pass
key = 'mod'
class Mul(Binary):
3724class Mul(Binary):
3725    pass
key = 'mul'
class NEQ(Binary, Predicate):
3728class NEQ(Binary, Predicate):
3729    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3732class SimilarTo(Binary, Predicate):
3733    pass
key = 'similarto'
class Slice(Binary):
3736class Slice(Binary):
3737    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3740class Sub(Binary):
3741    pass
key = 'sub'
class ArrayOverlaps(Binary):
3744class ArrayOverlaps(Binary):
3745    pass
key = 'arrayoverlaps'
class Unary(Condition):
3750class Unary(Condition):
3751    pass
key = 'unary'
class BitwiseNot(Unary):
3754class BitwiseNot(Unary):
3755    pass
key = 'bitwisenot'
class Not(Unary):
3758class Not(Unary):
3759    pass
key = 'not'
class Paren(Unary):
3762class Paren(Unary):
3763    arg_types = {"this": True, "with": False}
3764
3765    @property
3766    def output_name(self) -> str:
3767        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):
3770class Neg(Unary):
3771    pass
key = 'neg'
class Alias(Expression):
3774class Alias(Expression):
3775    arg_types = {"this": True, "alias": False}
3776
3777    @property
3778    def output_name(self) -> str:
3779        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):
3782class Aliases(Expression):
3783    arg_types = {"this": True, "expressions": True}
3784
3785    @property
3786    def aliases(self):
3787        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3790class AtTimeZone(Expression):
3791    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3794class Between(Predicate):
3795    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3798class Bracket(Condition):
3799    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3802class SafeBracket(Bracket):
3803    """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):
3806class Distinct(Expression):
3807    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3810class In(Predicate):
3811    arg_types = {
3812        "this": True,
3813        "expressions": False,
3814        "query": False,
3815        "unnest": False,
3816        "field": False,
3817        "is_global": False,
3818    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3821class TimeUnit(Expression):
3822    """Automatically converts unit arg into a var."""
3823
3824    arg_types = {"unit": False}
3825
3826    def __init__(self, **args):
3827        unit = args.get("unit")
3828        if isinstance(unit, (Column, Literal)):
3829            args["unit"] = Var(this=unit.name)
3830        elif isinstance(unit, Week):
3831            unit.set("this", Var(this=unit.this.name))
3832
3833        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3826    def __init__(self, **args):
3827        unit = args.get("unit")
3828        if isinstance(unit, (Column, Literal)):
3829            args["unit"] = Var(this=unit.name)
3830        elif isinstance(unit, Week):
3831            unit.set("this", Var(this=unit.this.name))
3832
3833        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3836class Interval(TimeUnit):
3837    arg_types = {"this": False, "unit": False}
3838
3839    @property
3840    def unit(self) -> t.Optional[Var]:
3841        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3844class IgnoreNulls(Expression):
3845    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3848class RespectNulls(Expression):
3849    pass
key = 'respectnulls'
class Func(Condition):
3853class Func(Condition):
3854    """
3855    The base class for all function expressions.
3856
3857    Attributes:
3858        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3859            treated as a variable length argument and the argument's value will be stored as a list.
3860        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3861            for this function expression. These values are used to map this node to a name during parsing
3862            as well as to provide the function's name during SQL string generation. By default the SQL
3863            name is set to the expression's class name transformed to snake case.
3864    """
3865
3866    is_var_len_args = False
3867
3868    @classmethod
3869    def from_arg_list(cls, args):
3870        if cls.is_var_len_args:
3871            all_arg_keys = list(cls.arg_types)
3872            # If this function supports variable length argument treat the last argument as such.
3873            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3874            num_non_var = len(non_var_len_arg_keys)
3875
3876            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3877            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3878        else:
3879            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3880
3881        return cls(**args_dict)
3882
3883    @classmethod
3884    def sql_names(cls):
3885        if cls is Func:
3886            raise NotImplementedError(
3887                "SQL name is only supported by concrete function implementations"
3888            )
3889        if "_sql_names" not in cls.__dict__:
3890            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3891        return cls._sql_names
3892
3893    @classmethod
3894    def sql_name(cls):
3895        return cls.sql_names()[0]
3896
3897    @classmethod
3898    def default_parser_mappings(cls):
3899        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):
3868    @classmethod
3869    def from_arg_list(cls, args):
3870        if cls.is_var_len_args:
3871            all_arg_keys = list(cls.arg_types)
3872            # If this function supports variable length argument treat the last argument as such.
3873            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3874            num_non_var = len(non_var_len_arg_keys)
3875
3876            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3877            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3878        else:
3879            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3880
3881        return cls(**args_dict)
@classmethod
def sql_names(cls):
3883    @classmethod
3884    def sql_names(cls):
3885        if cls is Func:
3886            raise NotImplementedError(
3887                "SQL name is only supported by concrete function implementations"
3888            )
3889        if "_sql_names" not in cls.__dict__:
3890            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3891        return cls._sql_names
@classmethod
def sql_name(cls):
3893    @classmethod
3894    def sql_name(cls):
3895        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3897    @classmethod
3898    def default_parser_mappings(cls):
3899        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3902class AggFunc(Func):
3903    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3906class ParameterizedAgg(AggFunc):
3907    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3910class Abs(Func):
3911    pass
key = 'abs'
class Transform(Func):
3915class Transform(Func):
3916    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
3919class Anonymous(Func):
3920    arg_types = {"this": True, "expressions": False}
3921    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3926class Hll(AggFunc):
3927    arg_types = {"this": True, "expressions": False}
3928    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3931class ApproxDistinct(AggFunc):
3932    arg_types = {"this": True, "accuracy": False}
3933    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3936class Array(Func):
3937    arg_types = {"expressions": False}
3938    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3942class ToChar(Func):
3943    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3946class GenerateSeries(Func):
3947    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3950class ArrayAgg(AggFunc):
3951    pass
key = 'arrayagg'
class ArrayAll(Func):
3954class ArrayAll(Func):
3955    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3958class ArrayAny(Func):
3959    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3962class ArrayConcat(Func):
3963    arg_types = {"this": True, "expressions": False}
3964    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3967class ArrayContains(Binary, Func):
3968    pass
key = 'arraycontains'
class ArrayContained(Binary):
3971class ArrayContained(Binary):
3972    pass
key = 'arraycontained'
class ArrayFilter(Func):
3975class ArrayFilter(Func):
3976    arg_types = {"this": True, "expression": True}
3977    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3980class ArrayJoin(Func):
3981    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3984class ArraySize(Func):
3985    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3988class ArraySort(Func):
3989    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3992class ArraySum(Func):
3993    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3996class ArrayUnionAgg(AggFunc):
3997    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4000class Avg(AggFunc):
4001    pass
key = 'avg'
class AnyValue(AggFunc):
4004class AnyValue(AggFunc):
4005    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
4008class Case(Func):
4009    arg_types = {"this": False, "ifs": True, "default": False}
4010
4011    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4012        instance = _maybe_copy(self, copy)
4013        instance.append(
4014            "ifs",
4015            If(
4016                this=maybe_parse(condition, copy=copy, **opts),
4017                true=maybe_parse(then, copy=copy, **opts),
4018            ),
4019        )
4020        return instance
4021
4022    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4023        instance = _maybe_copy(self, copy)
4024        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4025        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:
4011    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4012        instance = _maybe_copy(self, copy)
4013        instance.append(
4014            "ifs",
4015            If(
4016                this=maybe_parse(condition, copy=copy, **opts),
4017                true=maybe_parse(then, copy=copy, **opts),
4018            ),
4019        )
4020        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4022    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4023        instance = _maybe_copy(self, copy)
4024        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4025        return instance
key = 'case'
class Cast(Func):
4028class Cast(Func):
4029    arg_types = {"this": True, "to": True, "format": False}
4030
4031    @property
4032    def name(self) -> str:
4033        return self.this.name
4034
4035    @property
4036    def to(self) -> DataType:
4037        return self.args["to"]
4038
4039    @property
4040    def output_name(self) -> str:
4041        return self.name
4042
4043    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4044        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:
4043    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4044        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
4047class CastToStrType(Func):
4048    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
4051class Collate(Binary):
4052    pass
key = 'collate'
class TryCast(Cast):
4055class TryCast(Cast):
4056    pass
key = 'trycast'
class Ceil(Func):
4059class Ceil(Func):
4060    arg_types = {"this": True, "decimals": False}
4061    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4064class Coalesce(Func):
4065    arg_types = {"this": True, "expressions": False}
4066    is_var_len_args = True
4067    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4070class Concat(Func):
4071    arg_types = {"expressions": True}
4072    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4075class SafeConcat(Concat):
4076    pass
key = 'safeconcat'
class ConcatWs(Concat):
4079class ConcatWs(Concat):
4080    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4083class Count(AggFunc):
4084    arg_types = {"this": False, "expressions": False}
4085    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4088class CountIf(AggFunc):
4089    pass
key = 'countif'
class CurrentDate(Func):
4092class CurrentDate(Func):
4093    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4096class CurrentDatetime(Func):
4097    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4100class CurrentTime(Func):
4101    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4104class CurrentTimestamp(Func):
4105    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4108class CurrentUser(Func):
4109    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4112class DateAdd(Func, TimeUnit):
4113    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4116class DateSub(Func, TimeUnit):
4117    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4120class DateDiff(Func, TimeUnit):
4121    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4122    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4125class DateTrunc(Func):
4126    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4129class DatetimeAdd(Func, TimeUnit):
4130    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4133class DatetimeSub(Func, TimeUnit):
4134    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4137class DatetimeDiff(Func, TimeUnit):
4138    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4141class DatetimeTrunc(Func, TimeUnit):
4142    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4145class DayOfWeek(Func):
4146    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4149class DayOfMonth(Func):
4150    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4153class DayOfYear(Func):
4154    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4157class WeekOfYear(Func):
4158    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4161class MonthsBetween(Func):
4162    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4165class LastDateOfMonth(Func):
4166    pass
key = 'lastdateofmonth'
class Extract(Func):
4169class Extract(Func):
4170    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4173class TimestampAdd(Func, TimeUnit):
4174    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4177class TimestampSub(Func, TimeUnit):
4178    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4181class TimestampDiff(Func, TimeUnit):
4182    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4185class TimestampTrunc(Func, TimeUnit):
4186    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4189class TimeAdd(Func, TimeUnit):
4190    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4193class TimeSub(Func, TimeUnit):
4194    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4197class TimeDiff(Func, TimeUnit):
4198    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4201class TimeTrunc(Func, TimeUnit):
4202    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4205class DateFromParts(Func):
4206    _sql_names = ["DATEFROMPARTS"]
4207    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4210class DateStrToDate(Func):
4211    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4214class DateToDateStr(Func):
4215    pass
key = 'datetodatestr'
class DateToDi(Func):
4218class DateToDi(Func):
4219    pass
key = 'datetodi'
class Date(Func):
4223class Date(Func):
4224    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4227class Day(Func):
4228    pass
key = 'day'
class Decode(Func):
4231class Decode(Func):
4232    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4235class DiToDate(Func):
4236    pass
key = 'ditodate'
class Encode(Func):
4239class Encode(Func):
4240    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4243class Exp(Func):
4244    pass
key = 'exp'
class Explode(Func):
4247class Explode(Func):
4248    pass
key = 'explode'
class Floor(Func):
4251class Floor(Func):
4252    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4255class FromBase64(Func):
4256    pass
key = 'frombase64'
class ToBase64(Func):
4259class ToBase64(Func):
4260    pass
key = 'tobase64'
class Greatest(Func):
4263class Greatest(Func):
4264    arg_types = {"this": True, "expressions": False}
4265    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4268class GroupConcat(Func):
4269    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4272class Hex(Func):
4273    pass
key = 'hex'
class Xor(Connector, Func):
4276class Xor(Connector, Func):
4277    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4280class If(Func):
4281    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4284class Initcap(Func):
4285    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4288class IsNan(Func):
4289    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class JSONKeyValue(Expression):
4292class JSONKeyValue(Expression):
4293    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4296class JSONObject(Func):
4297    arg_types = {
4298        "expressions": False,
4299        "null_handling": False,
4300        "unique_keys": False,
4301        "return_type": False,
4302        "format_json": False,
4303        "encoding": False,
4304    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4307class OpenJSONColumnDef(Expression):
4308    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):
4311class OpenJSON(Func):
4312    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4315class JSONBContains(Binary):
4316    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4319class JSONExtract(Binary, Func):
4320    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4323class JSONExtractScalar(JSONExtract):
4324    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4327class JSONBExtract(JSONExtract):
4328    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4331class JSONBExtractScalar(JSONExtract):
4332    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4335class JSONFormat(Func):
4336    arg_types = {"this": False, "options": False}
4337    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4341class JSONArrayContains(Binary, Predicate, Func):
4342    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4345class Least(Func):
4346    arg_types = {"this": True, "expressions": False}
4347    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4350class Left(Func):
4351    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4358class Length(Func):
4359    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4362class Levenshtein(Func):
4363    arg_types = {
4364        "this": True,
4365        "expression": False,
4366        "ins_cost": False,
4367        "del_cost": False,
4368        "sub_cost": False,
4369    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4372class Ln(Func):
4373    pass
key = 'ln'
class Log(Func):
4376class Log(Func):
4377    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4380class Log2(Func):
4381    pass
key = 'log2'
class Log10(Func):
4384class Log10(Func):
4385    pass
key = 'log10'
class LogicalOr(AggFunc):
4388class LogicalOr(AggFunc):
4389    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4392class LogicalAnd(AggFunc):
4393    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4396class Lower(Func):
4397    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4400class Map(Func):
4401    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4404class MapFromEntries(Func):
4405    pass
key = 'mapfromentries'
class StarMap(Func):
4408class StarMap(Func):
4409    pass
key = 'starmap'
class VarMap(Func):
4412class VarMap(Func):
4413    arg_types = {"keys": True, "values": True}
4414    is_var_len_args = True
4415
4416    @property
4417    def keys(self) -> t.List[Expression]:
4418        return self.args["keys"].expressions
4419
4420    @property
4421    def values(self) -> t.List[Expression]:
4422        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4426class MatchAgainst(Func):
4427    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4430class Max(AggFunc):
4431    arg_types = {"this": True, "expressions": False}
4432    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4435class MD5(Func):
4436    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4440class MD5Digest(Func):
4441    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4444class Min(AggFunc):
4445    arg_types = {"this": True, "expressions": False}
4446    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4449class Month(Func):
4450    pass
key = 'month'
class Nvl2(Func):
4453class Nvl2(Func):
4454    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4457class Posexplode(Func):
4458    pass
key = 'posexplode'
class Pow(Binary, Func):
4461class Pow(Binary, Func):
4462    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4465class PercentileCont(AggFunc):
4466    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4469class PercentileDisc(AggFunc):
4470    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4473class Quantile(AggFunc):
4474    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4477class ApproxQuantile(Quantile):
4478    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):
4481class RangeN(Func):
4482    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4485class ReadCSV(Func):
4486    _sql_names = ["READ_CSV"]
4487    is_var_len_args = True
4488    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4491class Reduce(Func):
4492    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):
4495class RegexpExtract(Func):
4496    arg_types = {
4497        "this": True,
4498        "expression": True,
4499        "position": False,
4500        "occurrence": False,
4501        "parameters": False,
4502        "group": False,
4503    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4506class RegexpReplace(Func):
4507    arg_types = {
4508        "this": True,
4509        "expression": True,
4510        "replacement": True,
4511        "position": False,
4512        "occurrence": False,
4513        "parameters": False,
4514    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4517class RegexpLike(Binary, Func):
4518    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4521class RegexpILike(Func):
4522    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4527class RegexpSplit(Func):
4528    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4531class Repeat(Func):
4532    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4535class Round(Func):
4536    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4539class RowNumber(Func):
4540    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4543class SafeDivide(Func):
4544    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4547class SetAgg(AggFunc):
4548    pass
key = 'setagg'
class SHA(Func):
4551class SHA(Func):
4552    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4555class SHA2(Func):
4556    _sql_names = ["SHA2"]
4557    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4560class SortArray(Func):
4561    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4564class Split(Func):
4565    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4570class Substring(Func):
4571    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4574class StandardHash(Func):
4575    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4578class StartsWith(Func):
4579    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4580    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4583class StrPosition(Func):
4584    arg_types = {
4585        "this": True,
4586        "substr": True,
4587        "position": False,
4588        "instance": False,
4589    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4592class StrToDate(Func):
4593    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4596class StrToTime(Func):
4597    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4602class StrToUnix(Func):
4603    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4606class NumberToStr(Func):
4607    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4610class FromBase(Func):
4611    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4614class Struct(Func):
4615    arg_types = {"expressions": True}
4616    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4619class StructExtract(Func):
4620    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4623class Sum(AggFunc):
4624    pass
key = 'sum'
class Sqrt(Func):
4627class Sqrt(Func):
4628    pass
key = 'sqrt'
class Stddev(AggFunc):
4631class Stddev(AggFunc):
4632    pass
key = 'stddev'
class StddevPop(AggFunc):
4635class StddevPop(AggFunc):
4636    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4639class StddevSamp(AggFunc):
4640    pass
key = 'stddevsamp'
class TimeToStr(Func):
4643class TimeToStr(Func):
4644    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4647class TimeToTimeStr(Func):
4648    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4651class TimeToUnix(Func):
4652    pass
key = 'timetounix'
class TimeStrToDate(Func):
4655class TimeStrToDate(Func):
4656    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4659class TimeStrToTime(Func):
4660    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4663class TimeStrToUnix(Func):
4664    pass
key = 'timestrtounix'
class Trim(Func):
4667class Trim(Func):
4668    arg_types = {
4669        "this": True,
4670        "expression": False,
4671        "position": False,
4672        "collation": False,
4673    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4676class TsOrDsAdd(Func, TimeUnit):
4677    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4680class TsOrDsToDateStr(Func):
4681    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4684class TsOrDsToDate(Func):
4685    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4688class TsOrDiToDi(Func):
4689    pass
key = 'tsorditodi'
class Unhex(Func):
4692class Unhex(Func):
4693    pass
key = 'unhex'
class UnixToStr(Func):
4696class UnixToStr(Func):
4697    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4702class UnixToTime(Func):
4703    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4704
4705    SECONDS = Literal.string("seconds")
4706    MILLIS = Literal.string("millis")
4707    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):
4710class UnixToTimeStr(Func):
4711    pass
key = 'unixtotimestr'
class Upper(Func):
4714class Upper(Func):
4715    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4718class Variance(AggFunc):
4719    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4722class VariancePop(AggFunc):
4723    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4726class Week(Func):
4727    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4730class XMLTable(Func):
4731    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):
4734class Year(Func):
4735    pass
key = 'year'
class Use(Expression):
4738class Use(Expression):
4739    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4742class Merge(Expression):
4743    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):
4746class When(Func):
4747    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):
4752class NextValueFor(Func):
4753    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:
4790def maybe_parse(
4791    sql_or_expression: ExpOrStr,
4792    *,
4793    into: t.Optional[IntoType] = None,
4794    dialect: DialectType = None,
4795    prefix: t.Optional[str] = None,
4796    copy: bool = False,
4797    **opts,
4798) -> Expression:
4799    """Gracefully handle a possible string or expression.
4800
4801    Example:
4802        >>> maybe_parse("1")
4803        (LITERAL this: 1, is_string: False)
4804        >>> maybe_parse(to_identifier("x"))
4805        (IDENTIFIER this: x, quoted: False)
4806
4807    Args:
4808        sql_or_expression: the SQL code string or an expression
4809        into: the SQLGlot Expression to parse into
4810        dialect: the dialect used to parse the input expressions (in the case that an
4811            input expression is a SQL string).
4812        prefix: a string to prefix the sql with before it gets parsed
4813            (automatically includes a space)
4814        copy: whether or not to copy the expression.
4815        **opts: other options to use to parse the input expressions (again, in the case
4816            that an input expression is a SQL string).
4817
4818    Returns:
4819        Expression: the parsed or given expression.
4820    """
4821    if isinstance(sql_or_expression, Expression):
4822        if copy:
4823            return sql_or_expression.copy()
4824        return sql_or_expression
4825
4826    if sql_or_expression is None:
4827        raise ParseError(f"SQL cannot be None")
4828
4829    import sqlglot
4830
4831    sql = str(sql_or_expression)
4832    if prefix:
4833        sql = f"{prefix} {sql}"
4834
4835    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Union:
5019def union(
5020    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5021) -> Union:
5022    """
5023    Initializes a syntax tree from one UNION expression.
5024
5025    Example:
5026        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5027        'SELECT * FROM foo UNION SELECT * FROM bla'
5028
5029    Args:
5030        left: the SQL code string corresponding to the left-hand side.
5031            If an `Expression` instance is passed, it will be used as-is.
5032        right: the SQL code string corresponding to the right-hand side.
5033            If an `Expression` instance is passed, it will be used as-is.
5034        distinct: set the DISTINCT flag if and only if this is true.
5035        dialect: the dialect used to parse the input expression.
5036        opts: other options to use to parse the input expressions.
5037
5038    Returns:
5039        The new Union instance.
5040    """
5041    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5042    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5043
5044    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:
5047def intersect(
5048    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5049) -> Intersect:
5050    """
5051    Initializes a syntax tree from one INTERSECT expression.
5052
5053    Example:
5054        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5055        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5056
5057    Args:
5058        left: the SQL code string corresponding to the left-hand side.
5059            If an `Expression` instance is passed, it will be used as-is.
5060        right: the SQL code string corresponding to the right-hand side.
5061            If an `Expression` instance is passed, it will be used as-is.
5062        distinct: set the DISTINCT flag if and only if this is true.
5063        dialect: the dialect used to parse the input expression.
5064        opts: other options to use to parse the input expressions.
5065
5066    Returns:
5067        The new Intersect instance.
5068    """
5069    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5070    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5071
5072    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:
5075def except_(
5076    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5077) -> Except:
5078    """
5079    Initializes a syntax tree from one EXCEPT expression.
5080
5081    Example:
5082        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5083        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5084
5085    Args:
5086        left: the SQL code string corresponding to the left-hand side.
5087            If an `Expression` instance is passed, it will be used as-is.
5088        right: the SQL code string corresponding to the right-hand side.
5089            If an `Expression` instance is passed, it will be used as-is.
5090        distinct: set the DISTINCT flag if and only if this is true.
5091        dialect: the dialect used to parse the input expression.
5092        opts: other options to use to parse the input expressions.
5093
5094    Returns:
5095        The new Except instance.
5096    """
5097    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5098    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5099
5100    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:
5103def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5104    """
5105    Initializes a syntax tree from one or multiple SELECT expressions.
5106
5107    Example:
5108        >>> select("col1", "col2").from_("tbl").sql()
5109        'SELECT col1, col2 FROM tbl'
5110
5111    Args:
5112        *expressions: the SQL code string to parse as the expressions of a
5113            SELECT statement. If an Expression instance is passed, this is used as-is.
5114        dialect: the dialect used to parse the input expressions (in the case that an
5115            input expression is a SQL string).
5116        **opts: other options to use to parse the input expressions (again, in the case
5117            that an input expression is a SQL string).
5118
5119    Returns:
5120        Select: the syntax tree for the SELECT statement.
5121    """
5122    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:
5125def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5126    """
5127    Initializes a syntax tree from a FROM expression.
5128
5129    Example:
5130        >>> from_("tbl").select("col1", "col2").sql()
5131        'SELECT col1, col2 FROM tbl'
5132
5133    Args:
5134        *expression: the SQL code string to parse as the FROM expressions of a
5135            SELECT statement. If an Expression instance is passed, this is used as-is.
5136        dialect: the dialect used to parse the input expression (in the case that the
5137            input expression is a SQL string).
5138        **opts: other options to use to parse the input expressions (again, in the case
5139            that the input expression is a SQL string).
5140
5141    Returns:
5142        Select: the syntax tree for the SELECT statement.
5143    """
5144    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:
5147def update(
5148    table: str | Table,
5149    properties: dict,
5150    where: t.Optional[ExpOrStr] = None,
5151    from_: t.Optional[ExpOrStr] = None,
5152    dialect: DialectType = None,
5153    **opts,
5154) -> Update:
5155    """
5156    Creates an update statement.
5157
5158    Example:
5159        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5160        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5161
5162    Args:
5163        *properties: dictionary of properties to set which are
5164            auto converted to sql objects eg None -> NULL
5165        where: sql conditional parsed into a WHERE statement
5166        from_: sql statement parsed into a FROM statement
5167        dialect: the dialect used to parse the input expressions.
5168        **opts: other options to use to parse the input expressions.
5169
5170    Returns:
5171        Update: the syntax tree for the UPDATE statement.
5172    """
5173    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5174    update_expr.set(
5175        "expressions",
5176        [
5177            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5178            for k, v in properties.items()
5179        ],
5180    )
5181    if from_:
5182        update_expr.set(
5183            "from",
5184            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5185        )
5186    if isinstance(where, Condition):
5187        where = Where(this=where)
5188    if where:
5189        update_expr.set(
5190            "where",
5191            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5192        )
5193    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:
5196def delete(
5197    table: ExpOrStr,
5198    where: t.Optional[ExpOrStr] = None,
5199    returning: t.Optional[ExpOrStr] = None,
5200    dialect: DialectType = None,
5201    **opts,
5202) -> Delete:
5203    """
5204    Builds a delete statement.
5205
5206    Example:
5207        >>> delete("my_table", where="id > 1").sql()
5208        'DELETE FROM my_table WHERE id > 1'
5209
5210    Args:
5211        where: sql conditional parsed into a WHERE statement
5212        returning: sql conditional parsed into a RETURNING statement
5213        dialect: the dialect used to parse the input expressions.
5214        **opts: other options to use to parse the input expressions.
5215
5216    Returns:
5217        Delete: the syntax tree for the DELETE statement.
5218    """
5219    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5220    if where:
5221        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5222    if returning:
5223        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5224    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:
5227def insert(
5228    expression: ExpOrStr,
5229    into: ExpOrStr,
5230    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5231    overwrite: t.Optional[bool] = None,
5232    dialect: DialectType = None,
5233    copy: bool = True,
5234    **opts,
5235) -> Insert:
5236    """
5237    Builds an INSERT statement.
5238
5239    Example:
5240        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5241        'INSERT INTO tbl VALUES (1, 2, 3)'
5242
5243    Args:
5244        expression: the sql string or expression of the INSERT statement
5245        into: the tbl to insert data to.
5246        columns: optionally the table's column names.
5247        overwrite: whether to INSERT OVERWRITE or not.
5248        dialect: the dialect used to parse the input expressions.
5249        copy: whether or not to copy the expression.
5250        **opts: other options to use to parse the input expressions.
5251
5252    Returns:
5253        Insert: the syntax tree for the INSERT statement.
5254    """
5255    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5256    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5257
5258    if columns:
5259        this = _apply_list_builder(
5260            *columns,
5261            instance=Schema(this=this),
5262            arg="expressions",
5263            into=Identifier,
5264            copy=False,
5265            dialect=dialect,
5266            **opts,
5267        )
5268
5269    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:
5272def condition(
5273    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5274) -> Condition:
5275    """
5276    Initialize a logical condition expression.
5277
5278    Example:
5279        >>> condition("x=1").sql()
5280        'x = 1'
5281
5282        This is helpful for composing larger logical syntax trees:
5283        >>> where = condition("x=1")
5284        >>> where = where.and_("y=1")
5285        >>> Select().from_("tbl").select("*").where(where).sql()
5286        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5287
5288    Args:
5289        *expression: the SQL code string to parse.
5290            If an Expression instance is passed, this is used as-is.
5291        dialect: the dialect used to parse the input expression (in the case that the
5292            input expression is a SQL string).
5293        copy: Whether or not to copy `expression` (only applies to expressions).
5294        **opts: other options to use to parse the input expressions (again, in the case
5295            that the input expression is a SQL string).
5296
5297    Returns:
5298        The new Condition instance
5299    """
5300    return maybe_parse(
5301        expression,
5302        into=Condition,
5303        dialect=dialect,
5304        copy=copy,
5305        **opts,
5306    )

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:
5309def and_(
5310    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5311) -> Condition:
5312    """
5313    Combine multiple conditions with an AND logical operator.
5314
5315    Example:
5316        >>> and_("x=1", and_("y=1", "z=1")).sql()
5317        'x = 1 AND (y = 1 AND z = 1)'
5318
5319    Args:
5320        *expressions: the SQL code strings to parse.
5321            If an Expression instance is passed, this is used as-is.
5322        dialect: the dialect used to parse the input expression.
5323        copy: whether or not to copy `expressions` (only applies to Expressions).
5324        **opts: other options to use to parse the input expressions.
5325
5326    Returns:
5327        And: the new condition
5328    """
5329    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:
5332def or_(
5333    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5334) -> Condition:
5335    """
5336    Combine multiple conditions with an OR logical operator.
5337
5338    Example:
5339        >>> or_("x=1", or_("y=1", "z=1")).sql()
5340        'x = 1 OR (y = 1 OR z = 1)'
5341
5342    Args:
5343        *expressions: the SQL code strings to parse.
5344            If an Expression instance is passed, this is used as-is.
5345        dialect: the dialect used to parse the input expression.
5346        copy: whether or not to copy `expressions` (only applies to Expressions).
5347        **opts: other options to use to parse the input expressions.
5348
5349    Returns:
5350        Or: the new condition
5351    """
5352    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:
5355def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5356    """
5357    Wrap a condition with a NOT operator.
5358
5359    Example:
5360        >>> not_("this_suit='black'").sql()
5361        "NOT this_suit = 'black'"
5362
5363    Args:
5364        expression: the SQL code string to parse.
5365            If an Expression instance is passed, this is used as-is.
5366        dialect: the dialect used to parse the input expression.
5367        copy: whether to copy the expression or not.
5368        **opts: other options to use to parse the input expressions.
5369
5370    Returns:
5371        The new condition.
5372    """
5373    this = condition(
5374        expression,
5375        dialect=dialect,
5376        copy=copy,
5377        **opts,
5378    )
5379    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:
5382def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5383    """
5384    Wrap an expression in parentheses.
5385
5386    Example:
5387        >>> paren("5 + 3").sql()
5388        '(5 + 3)'
5389
5390    Args:
5391        expression: the SQL code string to parse.
5392            If an Expression instance is passed, this is used as-is.
5393        copy: whether to copy the expression or not.
5394
5395    Returns:
5396        The wrapped expression.
5397    """
5398    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):
5416def to_identifier(name, quoted=None, copy=True):
5417    """Builds an identifier.
5418
5419    Args:
5420        name: The name to turn into an identifier.
5421        quoted: Whether or not force quote the identifier.
5422        copy: Whether or not to copy a passed in Identefier node.
5423
5424    Returns:
5425        The identifier ast node.
5426    """
5427
5428    if name is None:
5429        return None
5430
5431    if isinstance(name, Identifier):
5432        identifier = _maybe_copy(name, copy)
5433    elif isinstance(name, str):
5434        identifier = Identifier(
5435            this=name,
5436            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5437        )
5438    else:
5439        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5440    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:
5446def to_interval(interval: str | Literal) -> Interval:
5447    """Builds an interval expression from a string like '1 day' or '5 months'."""
5448    if isinstance(interval, Literal):
5449        if not interval.is_string:
5450            raise ValueError("Invalid interval string.")
5451
5452        interval = interval.this
5453
5454    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5455
5456    if not interval_parts:
5457        raise ValueError("Invalid interval string.")
5458
5459    return Interval(
5460        this=Literal.string(interval_parts.group(1)),
5461        unit=Var(this=interval_parts.group(2)),
5462    )

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

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:
5634def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5635    """Cast an expression to a data type.
5636
5637    Example:
5638        >>> cast('x + 1', 'int').sql()
5639        'CAST(x + 1 AS INT)'
5640
5641    Args:
5642        expression: The expression to cast.
5643        to: The datatype to cast to.
5644
5645    Returns:
5646        The new Cast instance.
5647    """
5648    expression = maybe_parse(expression, **opts)
5649    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:
5652def table_(
5653    table: Identifier | str,
5654    db: t.Optional[Identifier | str] = None,
5655    catalog: t.Optional[Identifier | str] = None,
5656    quoted: t.Optional[bool] = None,
5657    alias: t.Optional[Identifier | str] = None,
5658) -> Table:
5659    """Build a Table.
5660
5661    Args:
5662        table: Table name.
5663        db: Database name.
5664        catalog: Catalog name.
5665        quote: Whether to force quotes on the table's identifiers.
5666        alias: Table's alias.
5667
5668    Returns:
5669        The new Table instance.
5670    """
5671    return Table(
5672        this=to_identifier(table, quoted=quoted),
5673        db=to_identifier(db, quoted=quoted),
5674        catalog=to_identifier(catalog, quoted=quoted),
5675        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5676    )

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:
5679def values(
5680    values: t.Iterable[t.Tuple[t.Any, ...]],
5681    alias: t.Optional[str] = None,
5682    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5683) -> Values:
5684    """Build VALUES statement.
5685
5686    Example:
5687        >>> values([(1, '2')]).sql()
5688        "VALUES (1, '2')"
5689
5690    Args:
5691        values: values statements that will be converted to SQL
5692        alias: optional alias
5693        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5694         If either are provided then an alias is also required.
5695
5696    Returns:
5697        Values: the Values expression object
5698    """
5699    if columns and not alias:
5700        raise ValueError("Alias is required when providing columns")
5701
5702    return Values(
5703        expressions=[convert(tup) for tup in values],
5704        alias=(
5705            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5706            if columns
5707            else (TableAlias(this=to_identifier(alias)) if alias else None)
5708        ),
5709    )

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:
5712def var(name: t.Optional[ExpOrStr]) -> Var:
5713    """Build a SQL variable.
5714
5715    Example:
5716        >>> repr(var('x'))
5717        '(VAR this: x)'
5718
5719        >>> repr(var(column('x', table='y')))
5720        '(VAR this: x)'
5721
5722    Args:
5723        name: The name of the var or an expression who's name will become the var.
5724
5725    Returns:
5726        The new variable node.
5727    """
5728    if not name:
5729        raise ValueError("Cannot convert empty name into var.")
5730
5731    if isinstance(name, Expression):
5732        name = name.name
5733    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:
5736def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5737    """Build ALTER TABLE... RENAME... expression
5738
5739    Args:
5740        old_name: The old name of the table
5741        new_name: The new name of the table
5742
5743    Returns:
5744        Alter table expression
5745    """
5746    old_table = to_table(old_name)
5747    new_table = to_table(new_name)
5748    return AlterTable(
5749        this=old_table,
5750        actions=[
5751            RenameTable(this=new_table),
5752        ],
5753    )

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:
5756def convert(value: t.Any, copy: bool = False) -> Expression:
5757    """Convert a python value into an expression object.
5758
5759    Raises an error if a conversion is not possible.
5760
5761    Args:
5762        value: A python object.
5763        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5764
5765    Returns:
5766        Expression: the equivalent expression object.
5767    """
5768    if isinstance(value, Expression):
5769        return _maybe_copy(value, copy)
5770    if isinstance(value, str):
5771        return Literal.string(value)
5772    if isinstance(value, bool):
5773        return Boolean(this=value)
5774    if value is None or (isinstance(value, float) and math.isnan(value)):
5775        return NULL
5776    if isinstance(value, numbers.Number):
5777        return Literal.number(value)
5778    if isinstance(value, datetime.datetime):
5779        datetime_literal = Literal.string(
5780            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5781        )
5782        return TimeStrToTime(this=datetime_literal)
5783    if isinstance(value, datetime.date):
5784        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5785        return DateStrToDate(this=date_literal)
5786    if isinstance(value, tuple):
5787        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5788    if isinstance(value, list):
5789        return Array(expressions=[convert(v, copy=copy) for v in value])
5790    if isinstance(value, dict):
5791        return Map(
5792            keys=[convert(k, copy=copy) for k in value],
5793            values=[convert(v, copy=copy) for v in value.values()],
5794        )
5795    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:
5798def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5799    """
5800    Replace children of an expression with the result of a lambda fun(child) -> exp.
5801    """
5802    for k, v in expression.args.items():
5803        is_list_arg = type(v) is list
5804
5805        child_nodes = v if is_list_arg else [v]
5806        new_child_nodes = []
5807
5808        for cn in child_nodes:
5809            if isinstance(cn, Expression):
5810                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5811                    new_child_nodes.append(child_node)
5812                    child_node.parent = expression
5813                    child_node.arg_key = k
5814            else:
5815                new_child_nodes.append(cn)
5816
5817        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]:
5820def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5821    """
5822    Return all table names referenced through columns in an expression.
5823
5824    Example:
5825        >>> import sqlglot
5826        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5827        ['a', 'c']
5828
5829    Args:
5830        expression: expression to find table names.
5831        exclude: a table name to exclude
5832
5833    Returns:
5834        A list of unique names.
5835    """
5836    return {
5837        table
5838        for table in (column.table for column in expression.find_all(Column))
5839        if table and table != exclude
5840    }

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:
5843def table_name(table: Table | str, dialect: DialectType = None) -> str:
5844    """Get the full name of a table as a string.
5845
5846    Args:
5847        table: Table expression node or string.
5848        dialect: The dialect to generate the table name for.
5849
5850    Examples:
5851        >>> from sqlglot import exp, parse_one
5852        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5853        'a.b.c'
5854
5855    Returns:
5856        The table name.
5857    """
5858
5859    table = maybe_parse(table, into=Table)
5860
5861    if not table:
5862        raise ValueError(f"Cannot parse {table}")
5863
5864    return ".".join(
5865        part.sql(dialect=dialect, identify=True)
5866        if not SAFE_IDENTIFIER_RE.match(part.name)
5867        else part.name
5868        for part in table.parts
5869    )

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

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
6027def false() -> Boolean:
6028    """
6029    Returns a false Boolean expression.
6030    """
6031    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6034def null() -> Null:
6035    """
6036    Returns a Null expression.
6037    """
6038    return Null()

Returns a Null expression.

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