Edit on GitHub

Expressions

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

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


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

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

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

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

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

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

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

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

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

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

alias_column_names: List[str]
name: str
alias_or_name: str
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
meta: Dict[str, Any]
def copy(self):
257    def copy(self):
258        """
259        Returns a deep copy of the expression.
260        """
261        new = deepcopy(self)
262        new.parent = self.parent
263        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
265    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
266        if self.comments is None:
267            self.comments = []
268        if comments:
269            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
271    def append(self, arg_key: str, value: t.Any) -> None:
272        """
273        Appends value to arg_key if it's a list or sets it as a new list.
274
275        Args:
276            arg_key (str): name of the list expression arg
277            value (Any): value to append to the list
278        """
279        if not isinstance(self.args.get(arg_key), list):
280            self.args[arg_key] = []
281        self.args[arg_key].append(value)
282        self._set_parent(arg_key, value)

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

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key: str, value: Any) -> None:
284    def set(self, arg_key: str, value: t.Any) -> None:
285        """
286        Sets arg_key to value.
287
288        Args:
289            arg_key: name of the expression arg.
290            value: value to set the arg to.
291        """
292        if value is None:
293            self.args.pop(arg_key, None)
294            return
295
296        self.args[arg_key] = value
297        self._set_parent(arg_key, value)

Sets arg_key to value.

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

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
318    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
319        """Yields the key and expression for all arguments, exploding list args."""
320        for k, vs in self.args.items():
321            if type(vs) is list:
322                for v in vs:
323                    if hasattr(v, "parent"):
324                        yield k, v
325            else:
326                if hasattr(vs, "parent"):
327                    yield k, vs

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

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

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

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

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

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

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

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

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
359    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
360        """
361        Returns a nearest parent matching expression_types.
362
363        Args:
364            expression_types: the expression type(s) to match.
365
366        Returns:
367            The parent node.
368        """
369        ancestor = self.parent
370        while ancestor and not isinstance(ancestor, expression_types):
371            ancestor = ancestor.parent
372        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

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

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
386    def root(self) -> Expression:
387        """
388        Returns the root expression of this tree.
389        """
390        expression = self
391        while expression.parent:
392            expression = expression.parent
393        return expression

Returns the root expression of this tree.

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

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

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

the generator object.

def dfs(self, parent=None, key=None, prune=None):
413    def dfs(self, parent=None, key=None, prune=None):
414        """
415        Returns a generator object which visits all nodes in this tree in
416        the DFS (Depth-first) order.
417
418        Returns:
419            The generator object.
420        """
421        parent = parent or self.parent
422        yield self, parent, key
423        if prune and prune(self, parent, key):
424            return
425
426        for k, v in self.iter_expressions():
427            yield from v.dfs(self, k, prune)

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

Returns:

The generator object.

def bfs(self, prune=None):
429    def bfs(self, prune=None):
430        """
431        Returns a generator object which visits all nodes in this tree in
432        the BFS (Breadth-first) order.
433
434        Returns:
435            The generator object.
436        """
437        queue = deque([(self, self.parent, None)])
438
439        while queue:
440            item, parent, key = queue.popleft()
441
442            yield item, parent, key
443            if prune and prune(item, parent, key):
444                continue
445
446            for k, v in item.iter_expressions():
447                queue.append((v, item, k))

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

Returns:

The generator object.

def unnest(self):
449    def unnest(self):
450        """
451        Returns the first non parenthesis child or self.
452        """
453        expression = self
454        while type(expression) is Paren:
455            expression = expression.this
456        return expression

Returns the first non parenthesis child or self.

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

Returns the inner expression if this is an Alias.

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

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
472    def flatten(self, unnest=True):
473        """
474        Returns a generator which yields child nodes who's parents are the same class.
475
476        A AND B AND C -> [A, B, C]
477        """
478        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
479            if not type(node) is self.__class__:
480                yield node.unnest() if unnest else node

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

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

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
488    def sql(self, dialect: DialectType = None, **opts) -> str:
489        """
490        Returns SQL string representation of this tree.
491
492        Args:
493            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
494            opts: other `sqlglot.generator.Generator` options.
495
496        Returns:
497            The SQL string.
498        """
499        from sqlglot.dialects import Dialect
500
501        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

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

The SQL string.

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

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

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

The transformed tree.

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

Swap out this expression with a new expression.

For example::

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

The new expression or expressions.

def pop(self: ~E) -> ~E:
589    def pop(self: E) -> E:
590        """
591        Remove this expression from its AST.
592
593        Returns:
594            The popped expression.
595        """
596        self.replace(None)
597        return self

Remove this expression from its AST.

Returns:

The popped expression.

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

Assert that this Expression is an instance of type_.

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

Examples:

This is useful for type security in chained expressions:

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

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

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

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

def dump(self):
650    def dump(self):
651        """
652        Dump this Expression to a JSON-serializable dict.
653        """
654        from sqlglot.serde import dump
655
656        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
658    @classmethod
659    def load(cls, obj):
660        """
661        Load a dict (as returned by `Expression.dump`) into an Expression instance.
662        """
663        from sqlglot.serde import load
664
665        return load(obj)

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

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

AND this condition with one or multiple expressions.

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

The new And condition.

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

OR this condition with one or multiple expressions.

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

The new Or condition.

def not_(self, copy: bool = True):
729    def not_(self, copy: bool = True):
730        """
731        Wrap this condition with NOT.
732
733        Example:
734            >>> condition("x=1").not_().sql()
735            'NOT x = 1'
736
737        Args:
738            copy: whether or not to copy this object.
739
740        Returns:
741            The new Not instance.
742        """
743        return not_(self, copy=copy)

Wrap this condition with NOT.

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

The new Not instance.

def as_( self, alias: str | sqlglot.expressions.Identifier, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Alias:
745    def as_(
746        self,
747        alias: str | Identifier,
748        quoted: t.Optional[bool] = None,
749        dialect: DialectType = None,
750        copy: bool = True,
751        **opts,
752    ) -> Alias:
753        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, unnest: Union[str, sqlglot.expressions.Expression, NoneType, Collection[Union[str, sqlglot.expressions.Expression]]] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
770    def isin(
771        self,
772        *expressions: t.Any,
773        query: t.Optional[ExpOrStr] = None,
774        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
775        copy: bool = True,
776        **opts,
777    ) -> In:
778        return In(
779            this=maybe_copy(self, copy),
780            expressions=[convert(e, copy=copy) for e in expressions],
781            query=maybe_parse(query, copy=copy, **opts) if query else None,
782            unnest=Unnest(
783                expressions=[
784                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
785                ]
786            )
787            if unnest
788            else None,
789        )
def between( self, low: Any, high: Any, copy: bool = True, **opts) -> sqlglot.expressions.Between:
791    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
792        return Between(
793            this=maybe_copy(self, copy),
794            low=convert(low, copy=copy, **opts),
795            high=convert(high, copy=copy, **opts),
796        )
def is_( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Is:
798    def is_(self, other: ExpOrStr) -> Is:
799        return self._binop(Is, other)
def like( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Like:
801    def like(self, other: ExpOrStr) -> Like:
802        return self._binop(Like, other)
def ilike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.ILike:
804    def ilike(self, other: ExpOrStr) -> ILike:
805        return self._binop(ILike, other)
def eq(self, other: Any) -> sqlglot.expressions.EQ:
807    def eq(self, other: t.Any) -> EQ:
808        return self._binop(EQ, other)
def neq(self, other: Any) -> sqlglot.expressions.NEQ:
810    def neq(self, other: t.Any) -> NEQ:
811        return self._binop(NEQ, other)
def rlike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.RegexpLike:
813    def rlike(self, other: ExpOrStr) -> RegexpLike:
814        return self._binop(RegexpLike, other)
key = 'condition'
class Predicate(Condition):
889class Predicate(Condition):
890    """Relationships like x = y, x > 1, x >= y."""

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

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

Builds a UNION expression.

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

The new Union expression.

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

Builds an INTERSECT expression.

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

The new Intersect expression.

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

Builds an EXCEPT expression.

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

The new Except expression.

key = 'unionable'
class UDTF(DerivedTable, Unionable):
974class UDTF(DerivedTable, Unionable):
975    @property
976    def selects(self) -> t.List[Expression]:
977        alias = self.args.get("alias")
978        return alias.columns if alias else []
key = 'udtf'
class Cache(Expression):
981class Cache(Expression):
982    arg_types = {
983        "with": False,
984        "this": True,
985        "lazy": False,
986        "options": False,
987        "expression": False,
988    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
991class Uncache(Expression):
992    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class DDL(Expression):
 995class DDL(Expression):
 996    @property
 997    def ctes(self):
 998        with_ = self.args.get("with")
 999        if not with_:
1000            return []
1001        return with_.expressions
1002
1003    @property
1004    def named_selects(self) -> t.List[str]:
1005        if isinstance(self.expression, Subqueryable):
1006            return self.expression.named_selects
1007        return []
1008
1009    @property
1010    def selects(self) -> t.List[Expression]:
1011        if isinstance(self.expression, Subqueryable):
1012            return self.expression.selects
1013        return []
ctes
named_selects: List[str]
key = 'ddl'
class Create(DDL):
1016class Create(DDL):
1017    arg_types = {
1018        "with": False,
1019        "this": True,
1020        "kind": True,
1021        "expression": False,
1022        "exists": False,
1023        "properties": False,
1024        "replace": False,
1025        "unique": False,
1026        "indexes": False,
1027        "no_schema_binding": False,
1028        "begin": False,
1029        "clone": False,
1030    }
arg_types = {'with': False, 'this': True, 'kind': True, 'expression': False, 'exists': False, 'properties': False, 'replace': False, 'unique': False, 'indexes': False, 'no_schema_binding': False, 'begin': False, 'clone': False}
key = 'create'
class Clone(Expression):
1034class Clone(Expression):
1035    arg_types = {
1036        "this": True,
1037        "when": False,
1038        "kind": False,
1039        "expression": False,
1040    }
arg_types = {'this': True, 'when': False, 'kind': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1043class Describe(Expression):
1044    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'describe'
class Pragma(Expression):
1047class Pragma(Expression):
1048    pass
key = 'pragma'
class Set(Expression):
1051class Set(Expression):
1052    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1055class SetItem(Expression):
1056    arg_types = {
1057        "this": False,
1058        "expressions": False,
1059        "kind": False,
1060        "collate": False,  # MySQL SET NAMES statement
1061        "global": False,
1062    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1065class Show(Expression):
1066    arg_types = {
1067        "this": True,
1068        "target": False,
1069        "offset": False,
1070        "limit": False,
1071        "like": False,
1072        "where": False,
1073        "db": False,
1074        "full": False,
1075        "mutex": False,
1076        "query": False,
1077        "channel": False,
1078        "global": False,
1079        "log": False,
1080        "position": False,
1081        "types": False,
1082    }
arg_types = {'this': True, 'target': False, 'offset': False, 'limit': False, 'like': False, 'where': False, 'db': False, 'full': False, 'mutex': False, 'query': False, 'channel': False, 'global': False, 'log': False, 'position': False, 'types': False}
key = 'show'
class UserDefinedFunction(Expression):
1085class UserDefinedFunction(Expression):
1086    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1089class CharacterSet(Expression):
1090    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1093class With(Expression):
1094    arg_types = {"expressions": True, "recursive": False}
1095
1096    @property
1097    def recursive(self) -> bool:
1098        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1101class WithinGroup(Expression):
1102    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1105class CTE(DerivedTable):
1106    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1109class TableAlias(Expression):
1110    arg_types = {"this": False, "columns": False}
1111
1112    @property
1113    def columns(self):
1114        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1117class BitString(Condition):
1118    pass
key = 'bitstring'
class HexString(Condition):
1121class HexString(Condition):
1122    pass
key = 'hexstring'
class ByteString(Condition):
1125class ByteString(Condition):
1126    pass
key = 'bytestring'
class RawString(Condition):
1129class RawString(Condition):
1130    pass
key = 'rawstring'
class Column(Condition):
1133class Column(Condition):
1134    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1135
1136    @property
1137    def table(self) -> str:
1138        return self.text("table")
1139
1140    @property
1141    def db(self) -> str:
1142        return self.text("db")
1143
1144    @property
1145    def catalog(self) -> str:
1146        return self.text("catalog")
1147
1148    @property
1149    def output_name(self) -> str:
1150        return self.name
1151
1152    @property
1153    def parts(self) -> t.List[Identifier]:
1154        """Return the parts of a column in order catalog, db, table, name."""
1155        return [
1156            t.cast(Identifier, self.args[part])
1157            for part in ("catalog", "db", "table", "this")
1158            if self.args.get(part)
1159        ]
1160
1161    def to_dot(self) -> Dot:
1162        """Converts the column into a dot expression."""
1163        parts = self.parts
1164        parent = self.parent
1165
1166        while parent:
1167            if isinstance(parent, Dot):
1168                parts.append(parent.expression)
1169            parent = parent.parent
1170
1171        return Dot.build(parts)
arg_types = {'this': True, 'table': False, 'db': False, 'catalog': False, 'join_mark': False}
table: str
db: str
catalog: str
output_name: str

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

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

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

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

def to_dot(self) -> sqlglot.expressions.Dot:
1161    def to_dot(self) -> Dot:
1162        """Converts the column into a dot expression."""
1163        parts = self.parts
1164        parent = self.parent
1165
1166        while parent:
1167            if isinstance(parent, Dot):
1168                parts.append(parent.expression)
1169            parent = parent.parent
1170
1171        return Dot.build(parts)

Converts the column into a dot expression.

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

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

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

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

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

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

key = 'delete'
class Drop(Expression):
1472class Drop(Expression):
1473    arg_types = {
1474        "this": False,
1475        "kind": False,
1476        "exists": False,
1477        "temporary": False,
1478        "materialized": False,
1479        "cascade": False,
1480        "constraints": False,
1481        "purge": False,
1482    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1485class Filter(Expression):
1486    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1489class Check(Expression):
1490    pass
key = 'check'
class Directory(Expression):
1493class Directory(Expression):
1494    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1495    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1498class ForeignKey(Expression):
1499    arg_types = {
1500        "expressions": True,
1501        "reference": False,
1502        "delete": False,
1503        "update": False,
1504    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1507class PrimaryKey(Expression):
1508    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1513class Into(Expression):
1514    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1517class From(Expression):
1518    @property
1519    def name(self) -> str:
1520        return self.this.name
1521
1522    @property
1523    def alias_or_name(self) -> str:
1524        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1527class Having(Expression):
1528    pass
key = 'having'
class Hint(Expression):
1531class Hint(Expression):
1532    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1535class JoinHint(Expression):
1536    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1539class Identifier(Expression):
1540    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1541
1542    @property
1543    def quoted(self) -> bool:
1544        return bool(self.args.get("quoted"))
1545
1546    @property
1547    def hashable_args(self) -> t.Any:
1548        return (self.this, self.quoted)
1549
1550    @property
1551    def output_name(self) -> str:
1552        return self.name
arg_types = {'this': True, 'quoted': False, 'global': False, 'temporary': False}
quoted: bool
hashable_args: Any
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'identifier'
class Index(Expression):
1555class Index(Expression):
1556    arg_types = {
1557        "this": False,
1558        "table": False,
1559        "using": False,
1560        "where": False,
1561        "columns": False,
1562        "unique": False,
1563        "primary": False,
1564        "amp": False,  # teradata
1565        "partition_by": False,  # teradata
1566    }
arg_types = {'this': False, 'table': False, 'using': False, 'where': False, 'columns': False, 'unique': False, 'primary': False, 'amp': False, 'partition_by': False}
key = 'index'
class Insert(DDL):
1569class Insert(DDL):
1570    arg_types = {
1571        "with": False,
1572        "this": True,
1573        "expression": False,
1574        "conflict": False,
1575        "returning": False,
1576        "overwrite": False,
1577        "exists": False,
1578        "partition": False,
1579        "alternative": False,
1580        "where": False,
1581        "ignore": False,
1582    }
1583
1584    def with_(
1585        self,
1586        alias: ExpOrStr,
1587        as_: ExpOrStr,
1588        recursive: t.Optional[bool] = None,
1589        append: bool = True,
1590        dialect: DialectType = None,
1591        copy: bool = True,
1592        **opts,
1593    ) -> Insert:
1594        """
1595        Append to or set the common table expressions.
1596
1597        Example:
1598            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1599            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1600
1601        Args:
1602            alias: the SQL code string to parse as the table name.
1603                If an `Expression` instance is passed, this is used as-is.
1604            as_: the SQL code string to parse as the table expression.
1605                If an `Expression` instance is passed, it will be used as-is.
1606            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1607            append: if `True`, add to any existing expressions.
1608                Otherwise, this resets the expressions.
1609            dialect: the dialect used to parse the input expression.
1610            copy: if `False`, modify this expression instance in-place.
1611            opts: other options to use to parse the input expressions.
1612
1613        Returns:
1614            The modified expression.
1615        """
1616        return _apply_cte_builder(
1617            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1618        )
arg_types = {'with': False, 'this': True, 'expression': False, 'conflict': False, 'returning': False, 'overwrite': False, 'exists': False, 'partition': False, 'alternative': False, 'where': False, 'ignore': False}
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Insert:
1584    def with_(
1585        self,
1586        alias: ExpOrStr,
1587        as_: ExpOrStr,
1588        recursive: t.Optional[bool] = None,
1589        append: bool = True,
1590        dialect: DialectType = None,
1591        copy: bool = True,
1592        **opts,
1593    ) -> Insert:
1594        """
1595        Append to or set the common table expressions.
1596
1597        Example:
1598            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1599            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1600
1601        Args:
1602            alias: the SQL code string to parse as the table name.
1603                If an `Expression` instance is passed, this is used as-is.
1604            as_: the SQL code string to parse as the table expression.
1605                If an `Expression` instance is passed, it will be used as-is.
1606            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1607            append: if `True`, add to any existing expressions.
1608                Otherwise, this resets the expressions.
1609            dialect: the dialect used to parse the input expression.
1610            copy: if `False`, modify this expression instance in-place.
1611            opts: other options to use to parse the input expressions.
1612
1613        Returns:
1614            The modified expression.
1615        """
1616        return _apply_cte_builder(
1617            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1618        )

Append to or set the common table expressions.

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

The modified expression.

key = 'insert'
class OnConflict(Expression):
1621class OnConflict(Expression):
1622    arg_types = {
1623        "duplicate": False,
1624        "expressions": False,
1625        "nothing": False,
1626        "key": False,
1627        "constraint": False,
1628    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1631class Returning(Expression):
1632    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1636class Introducer(Expression):
1637    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1641class National(Expression):
1642    pass
key = 'national'
class LoadData(Expression):
1645class LoadData(Expression):
1646    arg_types = {
1647        "this": True,
1648        "local": False,
1649        "overwrite": False,
1650        "inpath": True,
1651        "partition": False,
1652        "input_format": False,
1653        "serde": False,
1654    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1657class Partition(Expression):
1658    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1661class Fetch(Expression):
1662    arg_types = {
1663        "direction": False,
1664        "count": False,
1665        "percent": False,
1666        "with_ties": False,
1667    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1670class Group(Expression):
1671    arg_types = {
1672        "expressions": False,
1673        "grouping_sets": False,
1674        "cube": False,
1675        "rollup": False,
1676        "totals": False,
1677        "all": False,
1678    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1681class Lambda(Expression):
1682    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1685class Limit(Expression):
1686    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1689class Literal(Condition):
1690    arg_types = {"this": True, "is_string": True}
1691
1692    @property
1693    def hashable_args(self) -> t.Any:
1694        return (self.this, self.args.get("is_string"))
1695
1696    @classmethod
1697    def number(cls, number) -> Literal:
1698        return cls(this=str(number), is_string=False)
1699
1700    @classmethod
1701    def string(cls, string) -> Literal:
1702        return cls(this=str(string), is_string=True)
1703
1704    @property
1705    def output_name(self) -> str:
1706        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1696    @classmethod
1697    def number(cls, number) -> Literal:
1698        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1700    @classmethod
1701    def string(cls, string) -> Literal:
1702        return cls(this=str(string), is_string=True)
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'literal'
class Join(Expression):
1709class Join(Expression):
1710    arg_types = {
1711        "this": True,
1712        "on": False,
1713        "side": False,
1714        "kind": False,
1715        "using": False,
1716        "method": False,
1717        "global": False,
1718        "hint": False,
1719    }
1720
1721    @property
1722    def method(self) -> str:
1723        return self.text("method").upper()
1724
1725    @property
1726    def kind(self) -> str:
1727        return self.text("kind").upper()
1728
1729    @property
1730    def side(self) -> str:
1731        return self.text("side").upper()
1732
1733    @property
1734    def hint(self) -> str:
1735        return self.text("hint").upper()
1736
1737    @property
1738    def alias_or_name(self) -> str:
1739        return self.this.alias_or_name
1740
1741    def on(
1742        self,
1743        *expressions: t.Optional[ExpOrStr],
1744        append: bool = True,
1745        dialect: DialectType = None,
1746        copy: bool = True,
1747        **opts,
1748    ) -> Join:
1749        """
1750        Append to or set the ON expressions.
1751
1752        Example:
1753            >>> import sqlglot
1754            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1755            'JOIN x ON y = 1'
1756
1757        Args:
1758            *expressions: the SQL code strings to parse.
1759                If an `Expression` instance is passed, it will be used as-is.
1760                Multiple expressions are combined with an AND operator.
1761            append: if `True`, AND the new expressions to any existing expression.
1762                Otherwise, this resets the expression.
1763            dialect: the dialect used to parse the input expressions.
1764            copy: if `False`, modify this expression instance in-place.
1765            opts: other options to use to parse the input expressions.
1766
1767        Returns:
1768            The modified Join expression.
1769        """
1770        join = _apply_conjunction_builder(
1771            *expressions,
1772            instance=self,
1773            arg="on",
1774            append=append,
1775            dialect=dialect,
1776            copy=copy,
1777            **opts,
1778        )
1779
1780        if join.kind == "CROSS":
1781            join.set("kind", None)
1782
1783        return join
1784
1785    def using(
1786        self,
1787        *expressions: t.Optional[ExpOrStr],
1788        append: bool = True,
1789        dialect: DialectType = None,
1790        copy: bool = True,
1791        **opts,
1792    ) -> Join:
1793        """
1794        Append to or set the USING expressions.
1795
1796        Example:
1797            >>> import sqlglot
1798            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1799            'JOIN x USING (foo, bla)'
1800
1801        Args:
1802            *expressions: the SQL code strings to parse.
1803                If an `Expression` instance is passed, it will be used as-is.
1804            append: if `True`, concatenate the new expressions to the existing "using" list.
1805                Otherwise, this resets the expression.
1806            dialect: the dialect used to parse the input expressions.
1807            copy: if `False`, modify this expression instance in-place.
1808            opts: other options to use to parse the input expressions.
1809
1810        Returns:
1811            The modified Join expression.
1812        """
1813        join = _apply_list_builder(
1814            *expressions,
1815            instance=self,
1816            arg="using",
1817            append=append,
1818            dialect=dialect,
1819            copy=copy,
1820            **opts,
1821        )
1822
1823        if join.kind == "CROSS":
1824            join.set("kind", None)
1825
1826        return join
arg_types = {'this': True, 'on': False, 'side': False, 'kind': False, 'using': False, 'method': False, 'global': False, 'hint': False}
method: str
kind: str
side: str
hint: str
alias_or_name: str
def on( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1741    def on(
1742        self,
1743        *expressions: t.Optional[ExpOrStr],
1744        append: bool = True,
1745        dialect: DialectType = None,
1746        copy: bool = True,
1747        **opts,
1748    ) -> Join:
1749        """
1750        Append to or set the ON expressions.
1751
1752        Example:
1753            >>> import sqlglot
1754            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1755            'JOIN x ON y = 1'
1756
1757        Args:
1758            *expressions: the SQL code strings to parse.
1759                If an `Expression` instance is passed, it will be used as-is.
1760                Multiple expressions are combined with an AND operator.
1761            append: if `True`, AND the new expressions to any existing expression.
1762                Otherwise, this resets the expression.
1763            dialect: the dialect used to parse the input expressions.
1764            copy: if `False`, modify this expression instance in-place.
1765            opts: other options to use to parse the input expressions.
1766
1767        Returns:
1768            The modified Join expression.
1769        """
1770        join = _apply_conjunction_builder(
1771            *expressions,
1772            instance=self,
1773            arg="on",
1774            append=append,
1775            dialect=dialect,
1776            copy=copy,
1777            **opts,
1778        )
1779
1780        if join.kind == "CROSS":
1781            join.set("kind", None)
1782
1783        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

def using( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1785    def using(
1786        self,
1787        *expressions: t.Optional[ExpOrStr],
1788        append: bool = True,
1789        dialect: DialectType = None,
1790        copy: bool = True,
1791        **opts,
1792    ) -> Join:
1793        """
1794        Append to or set the USING expressions.
1795
1796        Example:
1797            >>> import sqlglot
1798            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1799            'JOIN x USING (foo, bla)'
1800
1801        Args:
1802            *expressions: the SQL code strings to parse.
1803                If an `Expression` instance is passed, it will be used as-is.
1804            append: if `True`, concatenate the new expressions to the existing "using" list.
1805                Otherwise, this resets the expression.
1806            dialect: the dialect used to parse the input expressions.
1807            copy: if `False`, modify this expression instance in-place.
1808            opts: other options to use to parse the input expressions.
1809
1810        Returns:
1811            The modified Join expression.
1812        """
1813        join = _apply_list_builder(
1814            *expressions,
1815            instance=self,
1816            arg="using",
1817            append=append,
1818            dialect=dialect,
1819            copy=copy,
1820            **opts,
1821        )
1822
1823        if join.kind == "CROSS":
1824            join.set("kind", None)
1825
1826        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

key = 'join'
class Lateral(UDTF):
1829class Lateral(UDTF):
1830    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
arg_types = {'this': True, 'view': False, 'outer': False, 'alias': False}
key = 'lateral'
class MatchRecognize(Expression):
1833class MatchRecognize(Expression):
1834    arg_types = {
1835        "partition_by": False,
1836        "order": False,
1837        "measures": False,
1838        "rows": False,
1839        "after": False,
1840        "pattern": False,
1841        "define": False,
1842        "alias": False,
1843    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1848class Final(Expression):
1849    pass
key = 'final'
class Offset(Expression):
1852class Offset(Expression):
1853    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1856class Order(Expression):
1857    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1862class Cluster(Order):
1863    pass
key = 'cluster'
class Distribute(Order):
1866class Distribute(Order):
1867    pass
key = 'distribute'
class Sort(Order):
1870class Sort(Order):
1871    pass
key = 'sort'
class Ordered(Expression):
1874class Ordered(Expression):
1875    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1878class Property(Expression):
1879    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1882class AlgorithmProperty(Property):
1883    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1886class AutoIncrementProperty(Property):
1887    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1890class BlockCompressionProperty(Property):
1891    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
arg_types = {'autotemp': False, 'always': False, 'default': True, 'manual': True, 'never': True}
key = 'blockcompressionproperty'
class CharacterSetProperty(Property):
1894class CharacterSetProperty(Property):
1895    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1898class ChecksumProperty(Property):
1899    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1902class CollateProperty(Property):
1903    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1906class CopyGrantsProperty(Property):
1907    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1910class DataBlocksizeProperty(Property):
1911    arg_types = {
1912        "size": False,
1913        "units": False,
1914        "minimum": False,
1915        "maximum": False,
1916        "default": False,
1917    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1920class DefinerProperty(Property):
1921    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1924class DistKeyProperty(Property):
1925    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1928class DistStyleProperty(Property):
1929    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1932class EngineProperty(Property):
1933    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
1936class HeapProperty(Property):
1937    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
1940class ToTableProperty(Property):
1941    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1944class ExecuteAsProperty(Property):
1945    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1948class ExternalProperty(Property):
1949    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1952class FallbackProperty(Property):
1953    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1956class FileFormatProperty(Property):
1957    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1960class FreespaceProperty(Property):
1961    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1964class InputOutputFormat(Expression):
1965    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1968class IsolatedLoadingProperty(Property):
1969    arg_types = {
1970        "no": True,
1971        "concurrent": True,
1972        "for_all": True,
1973        "for_insert": True,
1974        "for_none": True,
1975    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1978class JournalProperty(Property):
1979    arg_types = {
1980        "no": False,
1981        "dual": False,
1982        "before": False,
1983        "local": False,
1984        "after": False,
1985    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1988class LanguageProperty(Property):
1989    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1993class ClusteredByProperty(Property):
1994    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1997class DictProperty(Property):
1998    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2001class DictSubProperty(Property):
2002    pass
key = 'dictsubproperty'
class DictRange(Property):
2005class DictRange(Property):
2006    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2011class OnCluster(Property):
2012    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2015class LikeProperty(Property):
2016    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2019class LocationProperty(Property):
2020    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2023class LockingProperty(Property):
2024    arg_types = {
2025        "this": False,
2026        "kind": True,
2027        "for_or_in": True,
2028        "lock_type": True,
2029        "override": False,
2030    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2033class LogProperty(Property):
2034    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2037class MaterializedProperty(Property):
2038    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2041class MergeBlockRatioProperty(Property):
2042    arg_types = {"this": False, "no": False, "default": False, "percent": False}
arg_types = {'this': False, 'no': False, 'default': False, 'percent': False}
key = 'mergeblockratioproperty'
class NoPrimaryIndexProperty(Property):
2045class NoPrimaryIndexProperty(Property):
2046    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
2049class OnCommitProperty(Property):
2050    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2053class PartitionedByProperty(Property):
2054    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2057class ReturnsProperty(Property):
2058    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2061class RowFormatProperty(Property):
2062    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2065class RowFormatDelimitedProperty(Property):
2066    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2067    arg_types = {
2068        "fields": False,
2069        "escaped": False,
2070        "collection_items": False,
2071        "map_keys": False,
2072        "lines": False,
2073        "null": False,
2074        "serde": False,
2075    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2078class RowFormatSerdeProperty(Property):
2079    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2083class QueryTransform(Expression):
2084    arg_types = {
2085        "expressions": True,
2086        "command_script": True,
2087        "schema": False,
2088        "row_format_before": False,
2089        "record_writer": False,
2090        "row_format_after": False,
2091        "record_reader": False,
2092    }
arg_types = {'expressions': True, 'command_script': True, 'schema': False, 'row_format_before': False, 'record_writer': False, 'row_format_after': False, 'record_reader': False}
key = 'querytransform'
class SchemaCommentProperty(Property):
2095class SchemaCommentProperty(Property):
2096    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2099class SerdeProperties(Property):
2100    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2103class SetProperty(Property):
2104    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2107class SettingsProperty(Property):
2108    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2111class SortKeyProperty(Property):
2112    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2115class SqlSecurityProperty(Property):
2116    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2119class StabilityProperty(Property):
2120    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2123class TemporaryProperty(Property):
2124    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2127class TransientProperty(Property):
2128    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2131class VolatileProperty(Property):
2132    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2135class WithDataProperty(Property):
2136    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2139class WithJournalTableProperty(Property):
2140    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2143class Properties(Expression):
2144    arg_types = {"expressions": True}
2145
2146    NAME_TO_PROPERTY = {
2147        "ALGORITHM": AlgorithmProperty,
2148        "AUTO_INCREMENT": AutoIncrementProperty,
2149        "CHARACTER SET": CharacterSetProperty,
2150        "CLUSTERED_BY": ClusteredByProperty,
2151        "COLLATE": CollateProperty,
2152        "COMMENT": SchemaCommentProperty,
2153        "DEFINER": DefinerProperty,
2154        "DISTKEY": DistKeyProperty,
2155        "DISTSTYLE": DistStyleProperty,
2156        "ENGINE": EngineProperty,
2157        "EXECUTE AS": ExecuteAsProperty,
2158        "FORMAT": FileFormatProperty,
2159        "LANGUAGE": LanguageProperty,
2160        "LOCATION": LocationProperty,
2161        "PARTITIONED_BY": PartitionedByProperty,
2162        "RETURNS": ReturnsProperty,
2163        "ROW_FORMAT": RowFormatProperty,
2164        "SORTKEY": SortKeyProperty,
2165    }
2166
2167    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2168
2169    # CREATE property locations
2170    # Form: schema specified
2171    #   create [POST_CREATE]
2172    #     table a [POST_NAME]
2173    #     (b int) [POST_SCHEMA]
2174    #     with ([POST_WITH])
2175    #     index (b) [POST_INDEX]
2176    #
2177    # Form: alias selection
2178    #   create [POST_CREATE]
2179    #     table a [POST_NAME]
2180    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2181    #     index (c) [POST_INDEX]
2182    class Location(AutoName):
2183        POST_CREATE = auto()
2184        POST_NAME = auto()
2185        POST_SCHEMA = auto()
2186        POST_WITH = auto()
2187        POST_ALIAS = auto()
2188        POST_EXPRESSION = auto()
2189        POST_INDEX = auto()
2190        UNSUPPORTED = auto()
2191
2192    @classmethod
2193    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2194        expressions = []
2195        for key, value in properties_dict.items():
2196            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2197            if property_cls:
2198                expressions.append(property_cls(this=convert(value)))
2199            else:
2200                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2201
2202        return cls(expressions=expressions)
arg_types = {'expressions': True}
NAME_TO_PROPERTY = {'ALGORITHM': <class 'sqlglot.expressions.AlgorithmProperty'>, 'AUTO_INCREMENT': <class 'sqlglot.expressions.AutoIncrementProperty'>, 'CHARACTER SET': <class 'sqlglot.expressions.CharacterSetProperty'>, 'CLUSTERED_BY': <class 'sqlglot.expressions.ClusteredByProperty'>, 'COLLATE': <class 'sqlglot.expressions.CollateProperty'>, 'COMMENT': <class 'sqlglot.expressions.SchemaCommentProperty'>, 'DEFINER': <class 'sqlglot.expressions.DefinerProperty'>, 'DISTKEY': <class 'sqlglot.expressions.DistKeyProperty'>, 'DISTSTYLE': <class 'sqlglot.expressions.DistStyleProperty'>, 'ENGINE': <class 'sqlglot.expressions.EngineProperty'>, 'EXECUTE AS': <class 'sqlglot.expressions.ExecuteAsProperty'>, 'FORMAT': <class 'sqlglot.expressions.FileFormatProperty'>, 'LANGUAGE': <class 'sqlglot.expressions.LanguageProperty'>, 'LOCATION': <class 'sqlglot.expressions.LocationProperty'>, 'PARTITIONED_BY': <class 'sqlglot.expressions.PartitionedByProperty'>, 'RETURNS': <class 'sqlglot.expressions.ReturnsProperty'>, 'ROW_FORMAT': <class 'sqlglot.expressions.RowFormatProperty'>, 'SORTKEY': <class 'sqlglot.expressions.SortKeyProperty'>}
PROPERTY_TO_NAME = {<class 'sqlglot.expressions.AlgorithmProperty'>: 'ALGORITHM', <class 'sqlglot.expressions.AutoIncrementProperty'>: 'AUTO_INCREMENT', <class 'sqlglot.expressions.CharacterSetProperty'>: 'CHARACTER SET', <class 'sqlglot.expressions.ClusteredByProperty'>: 'CLUSTERED_BY', <class 'sqlglot.expressions.CollateProperty'>: 'COLLATE', <class 'sqlglot.expressions.SchemaCommentProperty'>: 'COMMENT', <class 'sqlglot.expressions.DefinerProperty'>: 'DEFINER', <class 'sqlglot.expressions.DistKeyProperty'>: 'DISTKEY', <class 'sqlglot.expressions.DistStyleProperty'>: 'DISTSTYLE', <class 'sqlglot.expressions.EngineProperty'>: 'ENGINE', <class 'sqlglot.expressions.ExecuteAsProperty'>: 'EXECUTE AS', <class 'sqlglot.expressions.FileFormatProperty'>: 'FORMAT', <class 'sqlglot.expressions.LanguageProperty'>: 'LANGUAGE', <class 'sqlglot.expressions.LocationProperty'>: 'LOCATION', <class 'sqlglot.expressions.PartitionedByProperty'>: 'PARTITIONED_BY', <class 'sqlglot.expressions.ReturnsProperty'>: 'RETURNS', <class 'sqlglot.expressions.RowFormatProperty'>: 'ROW_FORMAT', <class 'sqlglot.expressions.SortKeyProperty'>: 'SORTKEY'}
@classmethod
def from_dict(cls, properties_dict: Dict) -> sqlglot.expressions.Properties:
2192    @classmethod
2193    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2194        expressions = []
2195        for key, value in properties_dict.items():
2196            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2197            if property_cls:
2198                expressions.append(property_cls(this=convert(value)))
2199            else:
2200                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2201
2202        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2182    class Location(AutoName):
2183        POST_CREATE = auto()
2184        POST_NAME = auto()
2185        POST_SCHEMA = auto()
2186        POST_WITH = auto()
2187        POST_ALIAS = auto()
2188        POST_EXPRESSION = auto()
2189        POST_INDEX = auto()
2190        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
2205class Qualify(Expression):
2206    pass
key = 'qualify'
class Return(Expression):
2210class Return(Expression):
2211    pass
key = 'return'
class Reference(Expression):
2214class Reference(Expression):
2215    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2218class Tuple(Expression):
2219    arg_types = {"expressions": False}
2220
2221    def isin(
2222        self,
2223        *expressions: t.Any,
2224        query: t.Optional[ExpOrStr] = None,
2225        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2226        copy: bool = True,
2227        **opts,
2228    ) -> In:
2229        return In(
2230            this=maybe_copy(self, copy),
2231            expressions=[convert(e, copy=copy) for e in expressions],
2232            query=maybe_parse(query, copy=copy, **opts) if query else None,
2233            unnest=Unnest(
2234                expressions=[
2235                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2236                ]
2237            )
2238            if unnest
2239            else None,
2240        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, unnest: Union[str, sqlglot.expressions.Expression, NoneType, Collection[Union[str, sqlglot.expressions.Expression]]] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2221    def isin(
2222        self,
2223        *expressions: t.Any,
2224        query: t.Optional[ExpOrStr] = None,
2225        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2226        copy: bool = True,
2227        **opts,
2228    ) -> In:
2229        return In(
2230            this=maybe_copy(self, copy),
2231            expressions=[convert(e, copy=copy) for e in expressions],
2232            query=maybe_parse(query, copy=copy, **opts) if query else None,
2233            unnest=Unnest(
2234                expressions=[
2235                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2236                ]
2237            )
2238            if unnest
2239            else None,
2240        )
key = 'tuple'
class Subqueryable(Unionable):
2243class Subqueryable(Unionable):
2244    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2245        """
2246        Convert this expression to an aliased expression that can be used as a Subquery.
2247
2248        Example:
2249            >>> subquery = Select().select("x").from_("tbl").subquery()
2250            >>> Select().select("x").from_(subquery).sql()
2251            'SELECT x FROM (SELECT x FROM tbl)'
2252
2253        Args:
2254            alias (str | Identifier): an optional alias for the subquery
2255            copy (bool): if `False`, modify this expression instance in-place.
2256
2257        Returns:
2258            Alias: the subquery
2259        """
2260        instance = maybe_copy(self, copy)
2261        if not isinstance(alias, Expression):
2262            alias = TableAlias(this=to_identifier(alias)) if alias else None
2263
2264        return Subquery(this=instance, alias=alias)
2265
2266    def limit(
2267        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2268    ) -> Select:
2269        raise NotImplementedError
2270
2271    @property
2272    def ctes(self):
2273        with_ = self.args.get("with")
2274        if not with_:
2275            return []
2276        return with_.expressions
2277
2278    @property
2279    def selects(self) -> t.List[Expression]:
2280        raise NotImplementedError("Subqueryable objects must implement `selects`")
2281
2282    @property
2283    def named_selects(self) -> t.List[str]:
2284        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2285
2286    def with_(
2287        self,
2288        alias: ExpOrStr,
2289        as_: ExpOrStr,
2290        recursive: t.Optional[bool] = None,
2291        append: bool = True,
2292        dialect: DialectType = None,
2293        copy: bool = True,
2294        **opts,
2295    ) -> Subqueryable:
2296        """
2297        Append to or set the common table expressions.
2298
2299        Example:
2300            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2301            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2302
2303        Args:
2304            alias: the SQL code string to parse as the table name.
2305                If an `Expression` instance is passed, this is used as-is.
2306            as_: the SQL code string to parse as the table expression.
2307                If an `Expression` instance is passed, it will be used as-is.
2308            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2309            append: if `True`, add to any existing expressions.
2310                Otherwise, this resets the expressions.
2311            dialect: the dialect used to parse the input expression.
2312            copy: if `False`, modify this expression instance in-place.
2313            opts: other options to use to parse the input expressions.
2314
2315        Returns:
2316            The modified expression.
2317        """
2318        return _apply_cte_builder(
2319            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2320        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2244    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2245        """
2246        Convert this expression to an aliased expression that can be used as a Subquery.
2247
2248        Example:
2249            >>> subquery = Select().select("x").from_("tbl").subquery()
2250            >>> Select().select("x").from_(subquery).sql()
2251            'SELECT x FROM (SELECT x FROM tbl)'
2252
2253        Args:
2254            alias (str | Identifier): an optional alias for the subquery
2255            copy (bool): if `False`, modify this expression instance in-place.
2256
2257        Returns:
2258            Alias: the subquery
2259        """
2260        instance = maybe_copy(self, copy)
2261        if not isinstance(alias, Expression):
2262            alias = TableAlias(this=to_identifier(alias)) if alias else None
2263
2264        return Subquery(this=instance, alias=alias)

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2266    def limit(
2267        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2268    ) -> Select:
2269        raise NotImplementedError
ctes
named_selects: List[str]
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Subqueryable:
2286    def with_(
2287        self,
2288        alias: ExpOrStr,
2289        as_: ExpOrStr,
2290        recursive: t.Optional[bool] = None,
2291        append: bool = True,
2292        dialect: DialectType = None,
2293        copy: bool = True,
2294        **opts,
2295    ) -> Subqueryable:
2296        """
2297        Append to or set the common table expressions.
2298
2299        Example:
2300            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2301            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2302
2303        Args:
2304            alias: the SQL code string to parse as the table name.
2305                If an `Expression` instance is passed, this is used as-is.
2306            as_: the SQL code string to parse as the table expression.
2307                If an `Expression` instance is passed, it will be used as-is.
2308            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2309            append: if `True`, add to any existing expressions.
2310                Otherwise, this resets the expressions.
2311            dialect: the dialect used to parse the input expression.
2312            copy: if `False`, modify this expression instance in-place.
2313            opts: other options to use to parse the input expressions.
2314
2315        Returns:
2316            The modified expression.
2317        """
2318        return _apply_cte_builder(
2319            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2320        )

Append to or set the common table expressions.

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

The modified expression.

key = 'subqueryable'
QUERY_MODIFIERS = {'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
class WithTableHint(Expression):
2347class WithTableHint(Expression):
2348    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2352class IndexTableHint(Expression):
2353    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2356class Table(Expression):
2357    arg_types = {
2358        "this": True,
2359        "alias": False,
2360        "db": False,
2361        "catalog": False,
2362        "laterals": False,
2363        "joins": False,
2364        "pivots": False,
2365        "hints": False,
2366        "system_time": False,
2367    }
2368
2369    @property
2370    def name(self) -> str:
2371        if isinstance(self.this, Func):
2372            return ""
2373        return self.this.name
2374
2375    @property
2376    def db(self) -> str:
2377        return self.text("db")
2378
2379    @property
2380    def catalog(self) -> str:
2381        return self.text("catalog")
2382
2383    @property
2384    def selects(self) -> t.List[Expression]:
2385        return []
2386
2387    @property
2388    def named_selects(self) -> t.List[str]:
2389        return []
2390
2391    @property
2392    def parts(self) -> t.List[Identifier]:
2393        """Return the parts of a table in order catalog, db, table."""
2394        parts: t.List[Identifier] = []
2395
2396        for arg in ("catalog", "db", "this"):
2397            part = self.args.get(arg)
2398
2399            if isinstance(part, Identifier):
2400                parts.append(part)
2401            elif isinstance(part, Dot):
2402                parts.extend(part.flatten())
2403
2404        return parts
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False}
name: str
db: str
catalog: str
named_selects: List[str]

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

key = 'table'
class SystemTime(Expression):
2408class SystemTime(Expression):
2409    arg_types = {
2410        "this": False,
2411        "expression": False,
2412        "kind": True,
2413    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2416class Union(Subqueryable):
2417    arg_types = {
2418        "with": False,
2419        "this": True,
2420        "expression": True,
2421        "distinct": False,
2422        **QUERY_MODIFIERS,
2423    }
2424
2425    def limit(
2426        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2427    ) -> Select:
2428        """
2429        Set the LIMIT expression.
2430
2431        Example:
2432            >>> select("1").union(select("1")).limit(1).sql()
2433            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2434
2435        Args:
2436            expression: the SQL code string to parse.
2437                This can also be an integer.
2438                If a `Limit` instance is passed, this is used as-is.
2439                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2440            dialect: the dialect used to parse the input expression.
2441            copy: if `False`, modify this expression instance in-place.
2442            opts: other options to use to parse the input expressions.
2443
2444        Returns:
2445            The limited subqueryable.
2446        """
2447        return (
2448            select("*")
2449            .from_(self.subquery(alias="_l_0", copy=copy))
2450            .limit(expression, dialect=dialect, copy=False, **opts)
2451        )
2452
2453    def select(
2454        self,
2455        *expressions: t.Optional[ExpOrStr],
2456        append: bool = True,
2457        dialect: DialectType = None,
2458        copy: bool = True,
2459        **opts,
2460    ) -> Union:
2461        """Append to or set the SELECT of the union recursively.
2462
2463        Example:
2464            >>> from sqlglot import parse_one
2465            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2466            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2467
2468        Args:
2469            *expressions: the SQL code strings to parse.
2470                If an `Expression` instance is passed, it will be used as-is.
2471            append: if `True`, add to any existing expressions.
2472                Otherwise, this resets the expressions.
2473            dialect: the dialect used to parse the input expressions.
2474            copy: if `False`, modify this expression instance in-place.
2475            opts: other options to use to parse the input expressions.
2476
2477        Returns:
2478            Union: the modified expression.
2479        """
2480        this = self.copy() if copy else self
2481        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2482        this.expression.unnest().select(
2483            *expressions, append=append, dialect=dialect, copy=False, **opts
2484        )
2485        return this
2486
2487    @property
2488    def named_selects(self) -> t.List[str]:
2489        return self.this.unnest().named_selects
2490
2491    @property
2492    def is_star(self) -> bool:
2493        return self.this.is_star or self.expression.is_star
2494
2495    @property
2496    def selects(self) -> t.List[Expression]:
2497        return self.this.unnest().selects
2498
2499    @property
2500    def left(self):
2501        return self.this
2502
2503    @property
2504    def right(self):
2505        return self.expression
arg_types = {'with': False, 'this': True, 'expression': True, 'distinct': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2425    def limit(
2426        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2427    ) -> Select:
2428        """
2429        Set the LIMIT expression.
2430
2431        Example:
2432            >>> select("1").union(select("1")).limit(1).sql()
2433            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2434
2435        Args:
2436            expression: the SQL code string to parse.
2437                This can also be an integer.
2438                If a `Limit` instance is passed, this is used as-is.
2439                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2440            dialect: the dialect used to parse the input expression.
2441            copy: if `False`, modify this expression instance in-place.
2442            opts: other options to use to parse the input expressions.
2443
2444        Returns:
2445            The limited subqueryable.
2446        """
2447        return (
2448            select("*")
2449            .from_(self.subquery(alias="_l_0", copy=copy))
2450            .limit(expression, dialect=dialect, copy=False, **opts)
2451        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
2453    def select(
2454        self,
2455        *expressions: t.Optional[ExpOrStr],
2456        append: bool = True,
2457        dialect: DialectType = None,
2458        copy: bool = True,
2459        **opts,
2460    ) -> Union:
2461        """Append to or set the SELECT of the union recursively.
2462
2463        Example:
2464            >>> from sqlglot import parse_one
2465            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2466            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2467
2468        Args:
2469            *expressions: the SQL code strings to parse.
2470                If an `Expression` instance is passed, it will be used as-is.
2471            append: if `True`, add to any existing expressions.
2472                Otherwise, this resets the expressions.
2473            dialect: the dialect used to parse the input expressions.
2474            copy: if `False`, modify this expression instance in-place.
2475            opts: other options to use to parse the input expressions.
2476
2477        Returns:
2478            Union: the modified expression.
2479        """
2480        this = self.copy() if copy else self
2481        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2482        this.expression.unnest().select(
2483            *expressions, append=append, dialect=dialect, copy=False, **opts
2484        )
2485        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

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

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • expression : the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

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

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

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

Append to or set the SELECT expressions.

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

The modified Select expression.

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

Append to or set the LATERAL expressions.

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

The modified Select expression.

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

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on: optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using: optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type: if set, alter the parsed join type.
  • join_alias: an optional alias for the joined source.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

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

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

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

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def window( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
3085    def window(
3086        self,
3087        *expressions: t.Optional[ExpOrStr],
3088        append: bool = True,
3089        dialect: DialectType = None,
3090        copy: bool = True,
3091        **opts,
3092    ) -> Select:
3093        return _apply_list_builder(
3094            *expressions,
3095            instance=self,
3096            arg="windows",
3097            append=append,
3098            into=Window,
3099            dialect=dialect,
3100            copy=copy,
3101            **opts,
3102        )
def qualify( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
3104    def qualify(
3105        self,
3106        *expressions: t.Optional[ExpOrStr],
3107        append: bool = True,
3108        dialect: DialectType = None,
3109        copy: bool = True,
3110        **opts,
3111    ) -> Select:
3112        return _apply_conjunction_builder(
3113            *expressions,
3114            instance=self,
3115            arg="qualify",
3116            append=append,
3117            into=Qualify,
3118            dialect=dialect,
3119            copy=copy,
3120            **opts,
3121        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3123    def distinct(
3124        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3125    ) -> Select:
3126        """
3127        Set the OFFSET expression.
3128
3129        Example:
3130            >>> Select().from_("tbl").select("x").distinct().sql()
3131            'SELECT DISTINCT x FROM tbl'
3132
3133        Args:
3134            ons: the expressions to distinct on
3135            distinct: whether the Select should be distinct
3136            copy: if `False`, modify this expression instance in-place.
3137
3138        Returns:
3139            Select: the modified expression.
3140        """
3141        instance = maybe_copy(self, copy)
3142        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3143        instance.set("distinct", Distinct(on=on) if distinct else None)
3144        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • ons: the expressions to distinct on
  • distinct: whether the Select should be distinct
  • copy: if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table: Union[str, sqlglot.expressions.Expression], properties: Optional[Dict] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Create:
3146    def ctas(
3147        self,
3148        table: ExpOrStr,
3149        properties: t.Optional[t.Dict] = None,
3150        dialect: DialectType = None,
3151        copy: bool = True,
3152        **opts,
3153    ) -> Create:
3154        """
3155        Convert this expression to a CREATE TABLE AS statement.
3156
3157        Example:
3158            >>> Select().select("*").from_("tbl").ctas("x").sql()
3159            'CREATE TABLE x AS SELECT * FROM tbl'
3160
3161        Args:
3162            table: the SQL code string to parse as the table name.
3163                If another `Expression` instance is passed, it will be used as-is.
3164            properties: an optional mapping of table properties
3165            dialect: the dialect used to parse the input table.
3166            copy: if `False`, modify this expression instance in-place.
3167            opts: other options to use to parse the input table.
3168
3169        Returns:
3170            The new Create expression.
3171        """
3172        instance = maybe_copy(self, copy)
3173        table_expression = maybe_parse(
3174            table,
3175            into=Table,
3176            dialect=dialect,
3177            **opts,
3178        )
3179        properties_expression = None
3180        if properties:
3181            properties_expression = Properties.from_dict(properties)
3182
3183        return Create(
3184            this=table_expression,
3185            kind="table",
3186            expression=instance,
3187            properties=properties_expression,
3188        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table: the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties: an optional mapping of table properties
  • dialect: the dialect used to parse the input table.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input table.
Returns:

The new Create expression.

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3190    def lock(self, update: bool = True, copy: bool = True) -> Select:
3191        """
3192        Set the locking read mode for this expression.
3193
3194        Examples:
3195            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3196            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3197
3198            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3199            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3200
3201        Args:
3202            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3203            copy: if `False`, modify this expression instance in-place.
3204
3205        Returns:
3206            The modified expression.
3207        """
3208        inst = maybe_copy(self, copy)
3209        inst.set("locks", [Lock(update=update)])
3210
3211        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

def hint( self, *hints: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True) -> sqlglot.expressions.Select:
3213    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3214        """
3215        Set hints for this expression.
3216
3217        Examples:
3218            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3219            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3220
3221        Args:
3222            hints: The SQL code strings to parse as the hints.
3223                If an `Expression` instance is passed, it will be used as-is.
3224            dialect: The dialect used to parse the hints.
3225            copy: If `False`, modify this expression instance in-place.
3226
3227        Returns:
3228            The modified expression.
3229        """
3230        inst = maybe_copy(self, copy)
3231        inst.set(
3232            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3233        )
3234
3235        return inst

Set hints for this expression.

Examples:
>>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
'SELECT /*+ BROADCAST(y) */ x FROM tbl'
Arguments:
  • hints: The SQL code strings to parse as the hints. If an Expression instance is passed, it will be used as-is.
  • dialect: The dialect used to parse the hints.
  • copy: If False, modify this expression instance in-place.
Returns:

The modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

key = 'select'
class Subquery(DerivedTable, Unionable):
3250class Subquery(DerivedTable, Unionable):
3251    arg_types = {
3252        "this": True,
3253        "alias": False,
3254        "with": False,
3255        **QUERY_MODIFIERS,
3256    }
3257
3258    def unnest(self):
3259        """
3260        Returns the first non subquery.
3261        """
3262        expression = self
3263        while isinstance(expression, Subquery):
3264            expression = expression.this
3265        return expression
3266
3267    @property
3268    def is_star(self) -> bool:
3269        return self.this.is_star
3270
3271    @property
3272    def output_name(self) -> str:
3273        return self.alias
arg_types = {'this': True, 'alias': False, 'with': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def unnest(self):
3258    def unnest(self):
3259        """
3260        Returns the first non subquery.
3261        """
3262        expression = self
3263        while isinstance(expression, Subquery):
3264            expression = expression.this
3265        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name: str

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

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

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

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3303class Pivot(Expression):
3304    arg_types = {
3305        "this": False,
3306        "alias": False,
3307        "expressions": True,
3308        "field": False,
3309        "unpivot": False,
3310        "using": False,
3311        "group": False,
3312        "columns": False,
3313        "include_nulls": False,
3314    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False, 'include_nulls': False}
key = 'pivot'
class Window(Expression):
3317class Window(Expression):
3318    arg_types = {
3319        "this": True,
3320        "partition_by": False,
3321        "order": False,
3322        "spec": False,
3323        "alias": False,
3324        "over": False,
3325        "first": False,
3326    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3329class WindowSpec(Expression):
3330    arg_types = {
3331        "kind": False,
3332        "start": False,
3333        "start_side": False,
3334        "end": False,
3335        "end_side": False,
3336    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3339class Where(Expression):
3340    pass
key = 'where'
class Star(Expression):
3343class Star(Expression):
3344    arg_types = {"except": False, "replace": False}
3345
3346    @property
3347    def name(self) -> str:
3348        return "*"
3349
3350    @property
3351    def output_name(self) -> str:
3352        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):
3355class Parameter(Condition):
3356    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3359class SessionParameter(Condition):
3360    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3363class Placeholder(Condition):
3364    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3367class Null(Condition):
3368    arg_types: t.Dict[str, t.Any] = {}
3369
3370    @property
3371    def name(self) -> str:
3372        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3375class Boolean(Condition):
3376    pass
key = 'boolean'
class DataTypeSize(Expression):
3379class DataTypeSize(Expression):
3380    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3383class DataType(Expression):
3384    arg_types = {
3385        "this": True,
3386        "expressions": False,
3387        "nested": False,
3388        "values": False,
3389        "prefix": False,
3390    }
3391
3392    class Type(AutoName):
3393        ARRAY = auto()
3394        BIGDECIMAL = auto()
3395        BIGINT = auto()
3396        BIGSERIAL = auto()
3397        BINARY = auto()
3398        BIT = auto()
3399        BOOLEAN = auto()
3400        CHAR = auto()
3401        DATE = auto()
3402        DATEMULTIRANGE = auto()
3403        DATERANGE = auto()
3404        DATETIME = auto()
3405        DATETIME64 = auto()
3406        DECIMAL = auto()
3407        DOUBLE = auto()
3408        ENUM = auto()
3409        ENUM8 = auto()
3410        ENUM16 = auto()
3411        FIXEDSTRING = auto()
3412        FLOAT = auto()
3413        GEOGRAPHY = auto()
3414        GEOMETRY = auto()
3415        HLLSKETCH = auto()
3416        HSTORE = auto()
3417        IMAGE = auto()
3418        INET = auto()
3419        INT = auto()
3420        INT128 = auto()
3421        INT256 = auto()
3422        INT4MULTIRANGE = auto()
3423        INT4RANGE = auto()
3424        INT8MULTIRANGE = auto()
3425        INT8RANGE = auto()
3426        INTERVAL = auto()
3427        IPADDRESS = auto()
3428        IPPREFIX = auto()
3429        JSON = auto()
3430        JSONB = auto()
3431        LONGBLOB = auto()
3432        LONGTEXT = auto()
3433        LOWCARDINALITY = auto()
3434        MAP = auto()
3435        MEDIUMBLOB = auto()
3436        MEDIUMTEXT = auto()
3437        MONEY = auto()
3438        NCHAR = auto()
3439        NESTED = auto()
3440        NULL = auto()
3441        NULLABLE = auto()
3442        NUMMULTIRANGE = auto()
3443        NUMRANGE = auto()
3444        NVARCHAR = auto()
3445        OBJECT = auto()
3446        ROWVERSION = auto()
3447        SERIAL = auto()
3448        SET = auto()
3449        SMALLINT = auto()
3450        SMALLMONEY = auto()
3451        SMALLSERIAL = auto()
3452        STRUCT = auto()
3453        SUPER = auto()
3454        TEXT = auto()
3455        TIME = auto()
3456        TIMETZ = auto()
3457        TIMESTAMP = auto()
3458        TIMESTAMPLTZ = auto()
3459        TIMESTAMPTZ = auto()
3460        TINYINT = auto()
3461        TSMULTIRANGE = auto()
3462        TSRANGE = auto()
3463        TSTZMULTIRANGE = auto()
3464        TSTZRANGE = auto()
3465        UBIGINT = auto()
3466        UINT = auto()
3467        UINT128 = auto()
3468        UINT256 = auto()
3469        UNIQUEIDENTIFIER = auto()
3470        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3471        USERDEFINED = "USER-DEFINED"
3472        USMALLINT = auto()
3473        UTINYINT = auto()
3474        UUID = auto()
3475        VARBINARY = auto()
3476        VARCHAR = auto()
3477        VARIANT = auto()
3478        XML = auto()
3479
3480    TEXT_TYPES = {
3481        Type.CHAR,
3482        Type.NCHAR,
3483        Type.VARCHAR,
3484        Type.NVARCHAR,
3485        Type.TEXT,
3486    }
3487
3488    INTEGER_TYPES = {
3489        Type.INT,
3490        Type.TINYINT,
3491        Type.SMALLINT,
3492        Type.BIGINT,
3493        Type.INT128,
3494        Type.INT256,
3495    }
3496
3497    FLOAT_TYPES = {
3498        Type.FLOAT,
3499        Type.DOUBLE,
3500    }
3501
3502    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3503
3504    TEMPORAL_TYPES = {
3505        Type.TIME,
3506        Type.TIMETZ,
3507        Type.TIMESTAMP,
3508        Type.TIMESTAMPTZ,
3509        Type.TIMESTAMPLTZ,
3510        Type.DATE,
3511        Type.DATETIME,
3512        Type.DATETIME64,
3513    }
3514
3515    META_TYPES = {"UNKNOWN", "NULL"}
3516
3517    @classmethod
3518    def build(
3519        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3520    ) -> DataType:
3521        from sqlglot import parse_one
3522
3523        if isinstance(dtype, str):
3524            upper = dtype.upper()
3525            if upper in DataType.META_TYPES:
3526                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3527            else:
3528                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3529
3530            if data_type_exp is None:
3531                raise ValueError(f"Unparsable data type value: {dtype}")
3532        elif isinstance(dtype, DataType.Type):
3533            data_type_exp = DataType(this=dtype)
3534        elif isinstance(dtype, DataType):
3535            return dtype
3536        else:
3537            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3538
3539        return DataType(**{**data_type_exp.args, **kwargs})
3540
3541    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3542        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.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.CHAR: 'CHAR'>}
INTEGER_TYPES = {<Type.BIGINT: 'BIGINT'>, <Type.INT128: 'INT128'>, <Type.INT: 'INT'>, <Type.INT256: 'INT256'>, <Type.SMALLINT: 'SMALLINT'>, <Type.TINYINT: 'TINYINT'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.BIGINT: 'BIGINT'>, <Type.INT256: 'INT256'>, <Type.DOUBLE: 'DOUBLE'>, <Type.SMALLINT: 'SMALLINT'>, <Type.TINYINT: 'TINYINT'>, <Type.FLOAT: 'FLOAT'>, <Type.INT128: 'INT128'>, <Type.INT: 'INT'>}
TEMPORAL_TYPES = {<Type.TIMETZ: 'TIMETZ'>, <Type.DATETIME64: 'DATETIME64'>, <Type.DATETIME: 'DATETIME'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.DATE: 'DATE'>, <Type.TIME: 'TIME'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>}
META_TYPES = {'NULL', 'UNKNOWN'}
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
3517    @classmethod
3518    def build(
3519        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3520    ) -> DataType:
3521        from sqlglot import parse_one
3522
3523        if isinstance(dtype, str):
3524            upper = dtype.upper()
3525            if upper in DataType.META_TYPES:
3526                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3527            else:
3528                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3529
3530            if data_type_exp is None:
3531                raise ValueError(f"Unparsable data type value: {dtype}")
3532        elif isinstance(dtype, DataType.Type):
3533            data_type_exp = DataType(this=dtype)
3534        elif isinstance(dtype, DataType):
3535            return dtype
3536        else:
3537            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3538
3539        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3541    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3542        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3392    class Type(AutoName):
3393        ARRAY = auto()
3394        BIGDECIMAL = auto()
3395        BIGINT = auto()
3396        BIGSERIAL = auto()
3397        BINARY = auto()
3398        BIT = auto()
3399        BOOLEAN = auto()
3400        CHAR = auto()
3401        DATE = auto()
3402        DATEMULTIRANGE = auto()
3403        DATERANGE = auto()
3404        DATETIME = auto()
3405        DATETIME64 = auto()
3406        DECIMAL = auto()
3407        DOUBLE = auto()
3408        ENUM = auto()
3409        ENUM8 = auto()
3410        ENUM16 = auto()
3411        FIXEDSTRING = auto()
3412        FLOAT = auto()
3413        GEOGRAPHY = auto()
3414        GEOMETRY = auto()
3415        HLLSKETCH = auto()
3416        HSTORE = auto()
3417        IMAGE = auto()
3418        INET = auto()
3419        INT = auto()
3420        INT128 = auto()
3421        INT256 = auto()
3422        INT4MULTIRANGE = auto()
3423        INT4RANGE = auto()
3424        INT8MULTIRANGE = auto()
3425        INT8RANGE = auto()
3426        INTERVAL = auto()
3427        IPADDRESS = auto()
3428        IPPREFIX = auto()
3429        JSON = auto()
3430        JSONB = auto()
3431        LONGBLOB = auto()
3432        LONGTEXT = auto()
3433        LOWCARDINALITY = auto()
3434        MAP = auto()
3435        MEDIUMBLOB = auto()
3436        MEDIUMTEXT = auto()
3437        MONEY = auto()
3438        NCHAR = auto()
3439        NESTED = auto()
3440        NULL = auto()
3441        NULLABLE = auto()
3442        NUMMULTIRANGE = auto()
3443        NUMRANGE = auto()
3444        NVARCHAR = auto()
3445        OBJECT = auto()
3446        ROWVERSION = auto()
3447        SERIAL = auto()
3448        SET = auto()
3449        SMALLINT = auto()
3450        SMALLMONEY = auto()
3451        SMALLSERIAL = auto()
3452        STRUCT = auto()
3453        SUPER = auto()
3454        TEXT = auto()
3455        TIME = auto()
3456        TIMETZ = auto()
3457        TIMESTAMP = auto()
3458        TIMESTAMPLTZ = auto()
3459        TIMESTAMPTZ = auto()
3460        TINYINT = auto()
3461        TSMULTIRANGE = auto()
3462        TSRANGE = auto()
3463        TSTZMULTIRANGE = auto()
3464        TSTZRANGE = auto()
3465        UBIGINT = auto()
3466        UINT = auto()
3467        UINT128 = auto()
3468        UINT256 = auto()
3469        UNIQUEIDENTIFIER = auto()
3470        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3471        USERDEFINED = "USER-DEFINED"
3472        USMALLINT = auto()
3473        UTINYINT = auto()
3474        UUID = auto()
3475        VARBINARY = auto()
3476        VARCHAR = auto()
3477        VARIANT = auto()
3478        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'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
ENUM = <Type.ENUM: 'ENUM'>
ENUM8 = <Type.ENUM8: 'ENUM8'>
ENUM16 = <Type.ENUM16: 'ENUM16'>
FIXEDSTRING = <Type.FIXEDSTRING: 'FIXEDSTRING'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
IPADDRESS = <Type.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <Type.IPPREFIX: 'IPPREFIX'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
LOWCARDINALITY = <Type.LOWCARDINALITY: 'LOWCARDINALITY'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NESTED = <Type.NESTED: 'NESTED'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TIME = <Type.TIME: 'TIME'>
TIMETZ = <Type.TIMETZ: 'TIMETZ'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3546class PseudoType(Expression):
3547    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3551class SubqueryPredicate(Predicate):
3552    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3555class All(SubqueryPredicate):
3556    pass
key = 'all'
class Any(SubqueryPredicate):
3559class Any(SubqueryPredicate):
3560    pass
key = 'any'
class Exists(SubqueryPredicate):
3563class Exists(SubqueryPredicate):
3564    pass
key = 'exists'
class Command(Expression):
3569class Command(Expression):
3570    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3573class Transaction(Expression):
3574    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3577class Commit(Expression):
3578    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3581class Rollback(Expression):
3582    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3585class AlterTable(Expression):
3586    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3589class AddConstraint(Expression):
3590    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3593class DropPartition(Expression):
3594    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3598class Binary(Condition):
3599    arg_types = {"this": True, "expression": True}
3600
3601    @property
3602    def left(self):
3603        return self.this
3604
3605    @property
3606    def right(self):
3607        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3610class Add(Binary):
3611    pass
key = 'add'
class Connector(Binary):
3614class Connector(Binary):
3615    pass
key = 'connector'
class And(Connector):
3618class And(Connector):
3619    pass
key = 'and'
class Or(Connector):
3622class Or(Connector):
3623    pass
key = 'or'
class BitwiseAnd(Binary):
3626class BitwiseAnd(Binary):
3627    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3630class BitwiseLeftShift(Binary):
3631    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3634class BitwiseOr(Binary):
3635    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3638class BitwiseRightShift(Binary):
3639    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3642class BitwiseXor(Binary):
3643    pass
key = 'bitwisexor'
class Div(Binary):
3646class Div(Binary):
3647    pass
key = 'div'
class Overlaps(Binary):
3650class Overlaps(Binary):
3651    pass
key = 'overlaps'
class Dot(Binary):
3654class Dot(Binary):
3655    @property
3656    def name(self) -> str:
3657        return self.expression.name
3658
3659    @property
3660    def output_name(self) -> str:
3661        return self.name
3662
3663    @classmethod
3664    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3665        """Build a Dot object with a sequence of expressions."""
3666        if len(expressions) < 2:
3667            raise ValueError(f"Dot requires >= 2 expressions.")
3668
3669        a, b, *expressions = expressions
3670        dot = Dot(this=a, expression=b)
3671
3672        for expression in expressions:
3673            dot = Dot(this=dot, expression=expression)
3674
3675        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:
3663    @classmethod
3664    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3665        """Build a Dot object with a sequence of expressions."""
3666        if len(expressions) < 2:
3667            raise ValueError(f"Dot requires >= 2 expressions.")
3668
3669        a, b, *expressions = expressions
3670        dot = Dot(this=a, expression=b)
3671
3672        for expression in expressions:
3673            dot = Dot(this=dot, expression=expression)
3674
3675        return dot

Build a Dot object with a sequence of expressions.

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

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

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

Automatically converts unit arg into a var.

TimeUnit(**args)
3860    def __init__(self, **args):
3861        unit = args.get("unit")
3862        if isinstance(unit, (Column, Literal)):
3863            args["unit"] = Var(this=unit.name)
3864        elif isinstance(unit, Week):
3865            unit.set("this", Var(this=unit.this.name))
3866
3867        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class IntervalYearToMonthSpan(Expression):
3872class IntervalYearToMonthSpan(Expression):
3873    arg_types = {}
arg_types = {}
key = 'intervalyeartomonthspan'
class IntervalDayToSecondSpan(Expression):
3878class IntervalDayToSecondSpan(Expression):
3879    arg_types = {}
arg_types = {}
key = 'intervaldaytosecondspan'
class Interval(TimeUnit):
3882class Interval(TimeUnit):
3883    arg_types = {"this": False, "unit": False}
3884
3885    @property
3886    def unit(self) -> t.Optional[Var]:
3887        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3890class IgnoreNulls(Expression):
3891    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3894class RespectNulls(Expression):
3895    pass
key = 'respectnulls'
class Func(Condition):
3899class Func(Condition):
3900    """
3901    The base class for all function expressions.
3902
3903    Attributes:
3904        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3905            treated as a variable length argument and the argument's value will be stored as a list.
3906        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3907            for this function expression. These values are used to map this node to a name during parsing
3908            as well as to provide the function's name during SQL string generation. By default the SQL
3909            name is set to the expression's class name transformed to snake case.
3910    """
3911
3912    is_var_len_args = False
3913
3914    @classmethod
3915    def from_arg_list(cls, args):
3916        if cls.is_var_len_args:
3917            all_arg_keys = list(cls.arg_types)
3918            # If this function supports variable length argument treat the last argument as such.
3919            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3920            num_non_var = len(non_var_len_arg_keys)
3921
3922            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3923            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3924        else:
3925            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3926
3927        return cls(**args_dict)
3928
3929    @classmethod
3930    def sql_names(cls):
3931        if cls is Func:
3932            raise NotImplementedError(
3933                "SQL name is only supported by concrete function implementations"
3934            )
3935        if "_sql_names" not in cls.__dict__:
3936            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3937        return cls._sql_names
3938
3939    @classmethod
3940    def sql_name(cls):
3941        return cls.sql_names()[0]
3942
3943    @classmethod
3944    def default_parser_mappings(cls):
3945        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):
3914    @classmethod
3915    def from_arg_list(cls, args):
3916        if cls.is_var_len_args:
3917            all_arg_keys = list(cls.arg_types)
3918            # If this function supports variable length argument treat the last argument as such.
3919            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3920            num_non_var = len(non_var_len_arg_keys)
3921
3922            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3923            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3924        else:
3925            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3926
3927        return cls(**args_dict)
@classmethod
def sql_names(cls):
3929    @classmethod
3930    def sql_names(cls):
3931        if cls is Func:
3932            raise NotImplementedError(
3933                "SQL name is only supported by concrete function implementations"
3934            )
3935        if "_sql_names" not in cls.__dict__:
3936            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3937        return cls._sql_names
@classmethod
def sql_name(cls):
3939    @classmethod
3940    def sql_name(cls):
3941        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3943    @classmethod
3944    def default_parser_mappings(cls):
3945        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3948class AggFunc(Func):
3949    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3952class ParameterizedAgg(AggFunc):
3953    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3956class Abs(Func):
3957    pass
key = 'abs'
class Transform(Func):
3961class Transform(Func):
3962    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
3965class Anonymous(Func):
3966    arg_types = {"this": True, "expressions": False}
3967    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3972class Hll(AggFunc):
3973    arg_types = {"this": True, "expressions": False}
3974    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3977class ApproxDistinct(AggFunc):
3978    arg_types = {"this": True, "accuracy": False}
3979    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3982class Array(Func):
3983    arg_types = {"expressions": False}
3984    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3988class ToChar(Func):
3989    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3992class GenerateSeries(Func):
3993    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3996class ArrayAgg(AggFunc):
3997    pass
key = 'arrayagg'
class ArrayAll(Func):
4000class ArrayAll(Func):
4001    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4004class ArrayAny(Func):
4005    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4008class ArrayConcat(Func):
4009    arg_types = {"this": True, "expressions": False}
4010    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4013class ArrayContains(Binary, Func):
4014    pass
key = 'arraycontains'
class ArrayContained(Binary):
4017class ArrayContained(Binary):
4018    pass
key = 'arraycontained'
class ArrayFilter(Func):
4021class ArrayFilter(Func):
4022    arg_types = {"this": True, "expression": True}
4023    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4026class ArrayJoin(Func):
4027    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4030class ArraySize(Func):
4031    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4034class ArraySort(Func):
4035    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4038class ArraySum(Func):
4039    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4042class ArrayUnionAgg(AggFunc):
4043    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4046class Avg(AggFunc):
4047    pass
key = 'avg'
class AnyValue(AggFunc):
4050class AnyValue(AggFunc):
4051    arg_types = {"this": True, "having": False, "max": False, "ignore_nulls": False}
arg_types = {'this': True, 'having': False, 'max': False, 'ignore_nulls': False}
key = 'anyvalue'
class First(Func):
4054class First(Func):
4055    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4058class Last(Func):
4059    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4062class Case(Func):
4063    arg_types = {"this": False, "ifs": True, "default": False}
4064
4065    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4066        instance = maybe_copy(self, copy)
4067        instance.append(
4068            "ifs",
4069            If(
4070                this=maybe_parse(condition, copy=copy, **opts),
4071                true=maybe_parse(then, copy=copy, **opts),
4072            ),
4073        )
4074        return instance
4075
4076    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4077        instance = maybe_copy(self, copy)
4078        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4079        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:
4065    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4066        instance = maybe_copy(self, copy)
4067        instance.append(
4068            "ifs",
4069            If(
4070                this=maybe_parse(condition, copy=copy, **opts),
4071                true=maybe_parse(then, copy=copy, **opts),
4072            ),
4073        )
4074        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4076    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4077        instance = maybe_copy(self, copy)
4078        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4079        return instance
key = 'case'
class Cast(Func):
4082class Cast(Func):
4083    arg_types = {"this": True, "to": True, "format": False}
4084
4085    @property
4086    def name(self) -> str:
4087        return self.this.name
4088
4089    @property
4090    def to(self) -> DataType:
4091        return self.args["to"]
4092
4093    @property
4094    def output_name(self) -> str:
4095        return self.name
4096
4097    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4098        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:
4097    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4098        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
4101class CastToStrType(Func):
4102    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
4105class Collate(Binary):
4106    pass
key = 'collate'
class TryCast(Cast):
4109class TryCast(Cast):
4110    pass
key = 'trycast'
class Ceil(Func):
4113class Ceil(Func):
4114    arg_types = {"this": True, "decimals": False}
4115    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4118class Coalesce(Func):
4119    arg_types = {"this": True, "expressions": False}
4120    is_var_len_args = True
4121    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4124class Concat(Func):
4125    arg_types = {"expressions": True}
4126    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4129class SafeConcat(Concat):
4130    pass
key = 'safeconcat'
class ConcatWs(Concat):
4133class ConcatWs(Concat):
4134    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4137class Count(AggFunc):
4138    arg_types = {"this": False, "expressions": False}
4139    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4142class CountIf(AggFunc):
4143    pass
key = 'countif'
class CurrentDate(Func):
4146class CurrentDate(Func):
4147    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4150class CurrentDatetime(Func):
4151    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4154class CurrentTime(Func):
4155    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4158class CurrentTimestamp(Func):
4159    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4162class CurrentUser(Func):
4163    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4166class DateAdd(Func, TimeUnit):
4167    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4170class DateSub(Func, TimeUnit):
4171    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4174class DateDiff(Func, TimeUnit):
4175    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4176    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4179class DateTrunc(Func):
4180    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4183class DatetimeAdd(Func, TimeUnit):
4184    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4187class DatetimeSub(Func, TimeUnit):
4188    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4191class DatetimeDiff(Func, TimeUnit):
4192    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4195class DatetimeTrunc(Func, TimeUnit):
4196    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4199class DayOfWeek(Func):
4200    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4203class DayOfMonth(Func):
4204    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4207class DayOfYear(Func):
4208    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4211class WeekOfYear(Func):
4212    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4215class MonthsBetween(Func):
4216    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4219class LastDateOfMonth(Func):
4220    pass
key = 'lastdateofmonth'
class Extract(Func):
4223class Extract(Func):
4224    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4227class TimestampAdd(Func, TimeUnit):
4228    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4231class TimestampSub(Func, TimeUnit):
4232    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4235class TimestampDiff(Func, TimeUnit):
4236    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4239class TimestampTrunc(Func, TimeUnit):
4240    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4243class TimeAdd(Func, TimeUnit):
4244    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4247class TimeSub(Func, TimeUnit):
4248    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4251class TimeDiff(Func, TimeUnit):
4252    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4255class TimeTrunc(Func, TimeUnit):
4256    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4259class DateFromParts(Func):
4260    _sql_names = ["DATEFROMPARTS"]
4261    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4264class DateStrToDate(Func):
4265    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4268class DateToDateStr(Func):
4269    pass
key = 'datetodatestr'
class DateToDi(Func):
4272class DateToDi(Func):
4273    pass
key = 'datetodi'
class Date(Func):
4277class Date(Func):
4278    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4281class Day(Func):
4282    pass
key = 'day'
class Decode(Func):
4285class Decode(Func):
4286    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4289class DiToDate(Func):
4290    pass
key = 'ditodate'
class Encode(Func):
4293class Encode(Func):
4294    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4297class Exp(Func):
4298    pass
key = 'exp'
class Explode(Func):
4301class Explode(Func):
4302    pass
key = 'explode'
class Floor(Func):
4305class Floor(Func):
4306    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4309class FromBase64(Func):
4310    pass
key = 'frombase64'
class ToBase64(Func):
4313class ToBase64(Func):
4314    pass
key = 'tobase64'
class Greatest(Func):
4317class Greatest(Func):
4318    arg_types = {"this": True, "expressions": False}
4319    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4322class GroupConcat(Func):
4323    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4326class Hex(Func):
4327    pass
key = 'hex'
class Xor(Connector, Func):
4330class Xor(Connector, Func):
4331    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4334class If(Func):
4335    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4338class Initcap(Func):
4339    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4342class IsNan(Func):
4343    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class JSONKeyValue(Expression):
4346class JSONKeyValue(Expression):
4347    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4350class JSONObject(Func):
4351    arg_types = {
4352        "expressions": False,
4353        "null_handling": False,
4354        "unique_keys": False,
4355        "return_type": False,
4356        "format_json": False,
4357        "encoding": False,
4358    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4361class OpenJSONColumnDef(Expression):
4362    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):
4365class OpenJSON(Func):
4366    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4369class JSONBContains(Binary):
4370    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4373class JSONExtract(Binary, Func):
4374    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4377class JSONExtractScalar(JSONExtract):
4378    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4381class JSONBExtract(JSONExtract):
4382    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4385class JSONBExtractScalar(JSONExtract):
4386    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4389class JSONFormat(Func):
4390    arg_types = {"this": False, "options": False}
4391    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4395class JSONArrayContains(Binary, Predicate, Func):
4396    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4399class Least(Func):
4400    arg_types = {"this": True, "expressions": False}
4401    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4404class Left(Func):
4405    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4412class Length(Func):
4413    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4416class Levenshtein(Func):
4417    arg_types = {
4418        "this": True,
4419        "expression": False,
4420        "ins_cost": False,
4421        "del_cost": False,
4422        "sub_cost": False,
4423    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4426class Ln(Func):
4427    pass
key = 'ln'
class Log(Func):
4430class Log(Func):
4431    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4434class Log2(Func):
4435    pass
key = 'log2'
class Log10(Func):
4438class Log10(Func):
4439    pass
key = 'log10'
class LogicalOr(AggFunc):
4442class LogicalOr(AggFunc):
4443    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4446class LogicalAnd(AggFunc):
4447    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4450class Lower(Func):
4451    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4454class Map(Func):
4455    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4458class MapFromEntries(Func):
4459    pass
key = 'mapfromentries'
class StarMap(Func):
4462class StarMap(Func):
4463    pass
key = 'starmap'
class VarMap(Func):
4466class VarMap(Func):
4467    arg_types = {"keys": True, "values": True}
4468    is_var_len_args = True
4469
4470    @property
4471    def keys(self) -> t.List[Expression]:
4472        return self.args["keys"].expressions
4473
4474    @property
4475    def values(self) -> t.List[Expression]:
4476        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4480class MatchAgainst(Func):
4481    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4484class Max(AggFunc):
4485    arg_types = {"this": True, "expressions": False}
4486    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4489class MD5(Func):
4490    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4494class MD5Digest(Func):
4495    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4498class Min(AggFunc):
4499    arg_types = {"this": True, "expressions": False}
4500    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4503class Month(Func):
4504    pass
key = 'month'
class Nvl2(Func):
4507class Nvl2(Func):
4508    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4511class Posexplode(Func):
4512    pass
key = 'posexplode'
class Pow(Binary, Func):
4515class Pow(Binary, Func):
4516    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4519class PercentileCont(AggFunc):
4520    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4523class PercentileDisc(AggFunc):
4524    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4527class Quantile(AggFunc):
4528    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4531class ApproxQuantile(Quantile):
4532    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):
4535class RangeN(Func):
4536    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4539class ReadCSV(Func):
4540    _sql_names = ["READ_CSV"]
4541    is_var_len_args = True
4542    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4545class Reduce(Func):
4546    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):
4549class RegexpExtract(Func):
4550    arg_types = {
4551        "this": True,
4552        "expression": True,
4553        "position": False,
4554        "occurrence": False,
4555        "parameters": False,
4556        "group": False,
4557    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4560class RegexpReplace(Func):
4561    arg_types = {
4562        "this": True,
4563        "expression": True,
4564        "replacement": True,
4565        "position": False,
4566        "occurrence": False,
4567        "parameters": False,
4568    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4571class RegexpLike(Binary, Func):
4572    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4575class RegexpILike(Func):
4576    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4581class RegexpSplit(Func):
4582    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4585class Repeat(Func):
4586    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4589class Round(Func):
4590    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4593class RowNumber(Func):
4594    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4597class SafeDivide(Func):
4598    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4601class SetAgg(AggFunc):
4602    pass
key = 'setagg'
class SHA(Func):
4605class SHA(Func):
4606    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4609class SHA2(Func):
4610    _sql_names = ["SHA2"]
4611    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4614class SortArray(Func):
4615    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4618class Split(Func):
4619    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4624class Substring(Func):
4625    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4628class StandardHash(Func):
4629    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4632class StartsWith(Func):
4633    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4634    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4637class StrPosition(Func):
4638    arg_types = {
4639        "this": True,
4640        "substr": True,
4641        "position": False,
4642        "instance": False,
4643    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4646class StrToDate(Func):
4647    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4650class StrToTime(Func):
4651    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4656class StrToUnix(Func):
4657    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
4662class StrToMap(Func):
4663    arg_types = {
4664        "this": True,
4665        "pair_delim": False,
4666        "key_value_delim": False,
4667        "duplicate_resolution_callback": False,
4668    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
4671class NumberToStr(Func):
4672    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
4675class FromBase(Func):
4676    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4679class Struct(Func):
4680    arg_types = {"expressions": True}
4681    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4684class StructExtract(Func):
4685    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4688class Sum(AggFunc):
4689    pass
key = 'sum'
class Sqrt(Func):
4692class Sqrt(Func):
4693    pass
key = 'sqrt'
class Stddev(AggFunc):
4696class Stddev(AggFunc):
4697    pass
key = 'stddev'
class StddevPop(AggFunc):
4700class StddevPop(AggFunc):
4701    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4704class StddevSamp(AggFunc):
4705    pass
key = 'stddevsamp'
class TimeToStr(Func):
4708class TimeToStr(Func):
4709    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
4712class TimeToTimeStr(Func):
4713    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4716class TimeToUnix(Func):
4717    pass
key = 'timetounix'
class TimeStrToDate(Func):
4720class TimeStrToDate(Func):
4721    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4724class TimeStrToTime(Func):
4725    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4728class TimeStrToUnix(Func):
4729    pass
key = 'timestrtounix'
class Trim(Func):
4732class Trim(Func):
4733    arg_types = {
4734        "this": True,
4735        "expression": False,
4736        "position": False,
4737        "collation": False,
4738    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4741class TsOrDsAdd(Func, TimeUnit):
4742    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4745class TsOrDsToDateStr(Func):
4746    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4749class TsOrDsToDate(Func):
4750    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4753class TsOrDiToDi(Func):
4754    pass
key = 'tsorditodi'
class Unhex(Func):
4757class Unhex(Func):
4758    pass
key = 'unhex'
class UnixToStr(Func):
4761class UnixToStr(Func):
4762    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4767class UnixToTime(Func):
4768    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4769
4770    SECONDS = Literal.string("seconds")
4771    MILLIS = Literal.string("millis")
4772    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):
4775class UnixToTimeStr(Func):
4776    pass
key = 'unixtotimestr'
class Upper(Func):
4779class Upper(Func):
4780    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4783class Variance(AggFunc):
4784    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4787class VariancePop(AggFunc):
4788    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4791class Week(Func):
4792    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4795class XMLTable(Func):
4796    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):
4799class Year(Func):
4800    pass
key = 'year'
class Use(Expression):
4803class Use(Expression):
4804    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4807class Merge(Expression):
4808    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):
4811class When(Func):
4812    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):
4817class NextValueFor(Func):
4818    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.First'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.IsNan'>, <class 'sqlglot.expressions.JSONArrayContains'>, <class 'sqlglot.expressions.JSONBExtract'>, <class 'sqlglot.expressions.JSONBExtractScalar'>, <class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.JSONExtractScalar'>, <class 'sqlglot.expressions.JSONFormat'>, <class 'sqlglot.expressions.JSONObject'>, <class 'sqlglot.expressions.Last'>, <class 'sqlglot.expressions.LastDateOfMonth'>, <class 'sqlglot.expressions.Least'>, <class 'sqlglot.expressions.Left'>, <class 'sqlglot.expressions.Length'>, <class 'sqlglot.expressions.Levenshtein'>, <class 'sqlglot.expressions.Ln'>, <class 'sqlglot.expressions.Log'>, <class 'sqlglot.expressions.Log10'>, <class 'sqlglot.expressions.Log2'>, <class 'sqlglot.expressions.LogicalAnd'>, <class 'sqlglot.expressions.LogicalOr'>, <class 'sqlglot.expressions.Lower'>, <class 'sqlglot.expressions.MD5'>, <class 'sqlglot.expressions.MD5Digest'>, <class 'sqlglot.expressions.Map'>, <class 'sqlglot.expressions.MapFromEntries'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <class 'sqlglot.expressions.MonthsBetween'>, <class 'sqlglot.expressions.NextValueFor'>, <class 'sqlglot.expressions.NumberToStr'>, <class 'sqlglot.expressions.Nvl2'>, <class 'sqlglot.expressions.OpenJSON'>, <class 'sqlglot.expressions.ParameterizedAgg'>, <class 'sqlglot.expressions.PercentileCont'>, <class 'sqlglot.expressions.PercentileDisc'>, <class 'sqlglot.expressions.Posexplode'>, <class 'sqlglot.expressions.Pow'>, <class 'sqlglot.expressions.Quantile'>, <class 'sqlglot.expressions.RangeN'>, <class 'sqlglot.expressions.ReadCSV'>, <class 'sqlglot.expressions.Reduce'>, <class 'sqlglot.expressions.RegexpExtract'>, <class 'sqlglot.expressions.RegexpILike'>, <class 'sqlglot.expressions.RegexpLike'>, <class 'sqlglot.expressions.RegexpReplace'>, <class 'sqlglot.expressions.RegexpSplit'>, <class 'sqlglot.expressions.Repeat'>, <class 'sqlglot.expressions.Right'>, <class 'sqlglot.expressions.Round'>, <class 'sqlglot.expressions.RowNumber'>, <class 'sqlglot.expressions.SHA'>, <class 'sqlglot.expressions.SHA2'>, <class 'sqlglot.expressions.SafeConcat'>, <class 'sqlglot.expressions.SafeDivide'>, <class 'sqlglot.expressions.SetAgg'>, <class 'sqlglot.expressions.SortArray'>, <class 'sqlglot.expressions.Split'>, <class 'sqlglot.expressions.Sqrt'>, <class 'sqlglot.expressions.StandardHash'>, <class 'sqlglot.expressions.StarMap'>, <class 'sqlglot.expressions.StartsWith'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToMap'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.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:
4855def maybe_parse(
4856    sql_or_expression: ExpOrStr,
4857    *,
4858    into: t.Optional[IntoType] = None,
4859    dialect: DialectType = None,
4860    prefix: t.Optional[str] = None,
4861    copy: bool = False,
4862    **opts,
4863) -> Expression:
4864    """Gracefully handle a possible string or expression.
4865
4866    Example:
4867        >>> maybe_parse("1")
4868        (LITERAL this: 1, is_string: False)
4869        >>> maybe_parse(to_identifier("x"))
4870        (IDENTIFIER this: x, quoted: False)
4871
4872    Args:
4873        sql_or_expression: the SQL code string or an expression
4874        into: the SQLGlot Expression to parse into
4875        dialect: the dialect used to parse the input expressions (in the case that an
4876            input expression is a SQL string).
4877        prefix: a string to prefix the sql with before it gets parsed
4878            (automatically includes a space)
4879        copy: whether or not to copy the expression.
4880        **opts: other options to use to parse the input expressions (again, in the case
4881            that an input expression is a SQL string).
4882
4883    Returns:
4884        Expression: the parsed or given expression.
4885    """
4886    if isinstance(sql_or_expression, Expression):
4887        if copy:
4888            return sql_or_expression.copy()
4889        return sql_or_expression
4890
4891    if sql_or_expression is None:
4892        raise ParseError(f"SQL cannot be None")
4893
4894    import sqlglot
4895
4896    sql = str(sql_or_expression)
4897    if prefix:
4898        sql = f"{prefix} {sql}"
4899
4900    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

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

Expression: the parsed or given expression.

def maybe_copy(instance, copy=True):
4913def maybe_copy(instance, copy=True):
4914    return instance.copy() if copy and instance else instance
def union( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Union:
5094def union(
5095    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5096) -> Union:
5097    """
5098    Initializes a syntax tree from one UNION expression.
5099
5100    Example:
5101        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5102        'SELECT * FROM foo UNION SELECT * FROM bla'
5103
5104    Args:
5105        left: the SQL code string corresponding to the left-hand side.
5106            If an `Expression` instance is passed, it will be used as-is.
5107        right: the SQL code string corresponding to the right-hand side.
5108            If an `Expression` instance is passed, it will be used as-is.
5109        distinct: set the DISTINCT flag if and only if this is true.
5110        dialect: the dialect used to parse the input expression.
5111        opts: other options to use to parse the input expressions.
5112
5113    Returns:
5114        The new Union instance.
5115    """
5116    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5117    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5118
5119    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:
5122def intersect(
5123    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5124) -> Intersect:
5125    """
5126    Initializes a syntax tree from one INTERSECT expression.
5127
5128    Example:
5129        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5130        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5131
5132    Args:
5133        left: the SQL code string corresponding to the left-hand side.
5134            If an `Expression` instance is passed, it will be used as-is.
5135        right: the SQL code string corresponding to the right-hand side.
5136            If an `Expression` instance is passed, it will be used as-is.
5137        distinct: set the DISTINCT flag if and only if this is true.
5138        dialect: the dialect used to parse the input expression.
5139        opts: other options to use to parse the input expressions.
5140
5141    Returns:
5142        The new Intersect instance.
5143    """
5144    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5145    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5146
5147    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:
5150def except_(
5151    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5152) -> Except:
5153    """
5154    Initializes a syntax tree from one EXCEPT expression.
5155
5156    Example:
5157        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5158        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5159
5160    Args:
5161        left: the SQL code string corresponding to the left-hand side.
5162            If an `Expression` instance is passed, it will be used as-is.
5163        right: the SQL code string corresponding to the right-hand side.
5164            If an `Expression` instance is passed, it will be used as-is.
5165        distinct: set the DISTINCT flag if and only if this is true.
5166        dialect: the dialect used to parse the input expression.
5167        opts: other options to use to parse the input expressions.
5168
5169    Returns:
5170        The new Except instance.
5171    """
5172    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5173    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5174
5175    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:
5178def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5179    """
5180    Initializes a syntax tree from one or multiple SELECT expressions.
5181
5182    Example:
5183        >>> select("col1", "col2").from_("tbl").sql()
5184        'SELECT col1, col2 FROM tbl'
5185
5186    Args:
5187        *expressions: the SQL code string to parse as the expressions of a
5188            SELECT statement. If an Expression instance is passed, this is used as-is.
5189        dialect: the dialect used to parse the input expressions (in the case that an
5190            input expression is a SQL string).
5191        **opts: other options to use to parse the input expressions (again, in the case
5192            that an input expression is a SQL string).
5193
5194    Returns:
5195        Select: the syntax tree for the SELECT statement.
5196    """
5197    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:
5200def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5201    """
5202    Initializes a syntax tree from a FROM expression.
5203
5204    Example:
5205        >>> from_("tbl").select("col1", "col2").sql()
5206        'SELECT col1, col2 FROM tbl'
5207
5208    Args:
5209        *expression: the SQL code string to parse as the FROM expressions of a
5210            SELECT statement. If an Expression instance is passed, this is used as-is.
5211        dialect: the dialect used to parse the input expression (in the case that the
5212            input expression is a SQL string).
5213        **opts: other options to use to parse the input expressions (again, in the case
5214            that the input expression is a SQL string).
5215
5216    Returns:
5217        Select: the syntax tree for the SELECT statement.
5218    """
5219    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:
5222def update(
5223    table: str | Table,
5224    properties: dict,
5225    where: t.Optional[ExpOrStr] = None,
5226    from_: t.Optional[ExpOrStr] = None,
5227    dialect: DialectType = None,
5228    **opts,
5229) -> Update:
5230    """
5231    Creates an update statement.
5232
5233    Example:
5234        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5235        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5236
5237    Args:
5238        *properties: dictionary of properties to set which are
5239            auto converted to sql objects eg None -> NULL
5240        where: sql conditional parsed into a WHERE statement
5241        from_: sql statement parsed into a FROM statement
5242        dialect: the dialect used to parse the input expressions.
5243        **opts: other options to use to parse the input expressions.
5244
5245    Returns:
5246        Update: the syntax tree for the UPDATE statement.
5247    """
5248    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5249    update_expr.set(
5250        "expressions",
5251        [
5252            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5253            for k, v in properties.items()
5254        ],
5255    )
5256    if from_:
5257        update_expr.set(
5258            "from",
5259            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5260        )
5261    if isinstance(where, Condition):
5262        where = Where(this=where)
5263    if where:
5264        update_expr.set(
5265            "where",
5266            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5267        )
5268    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:
5271def delete(
5272    table: ExpOrStr,
5273    where: t.Optional[ExpOrStr] = None,
5274    returning: t.Optional[ExpOrStr] = None,
5275    dialect: DialectType = None,
5276    **opts,
5277) -> Delete:
5278    """
5279    Builds a delete statement.
5280
5281    Example:
5282        >>> delete("my_table", where="id > 1").sql()
5283        'DELETE FROM my_table WHERE id > 1'
5284
5285    Args:
5286        where: sql conditional parsed into a WHERE statement
5287        returning: sql conditional parsed into a RETURNING statement
5288        dialect: the dialect used to parse the input expressions.
5289        **opts: other options to use to parse the input expressions.
5290
5291    Returns:
5292        Delete: the syntax tree for the DELETE statement.
5293    """
5294    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5295    if where:
5296        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5297    if returning:
5298        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5299    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:
5302def insert(
5303    expression: ExpOrStr,
5304    into: ExpOrStr,
5305    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5306    overwrite: t.Optional[bool] = None,
5307    dialect: DialectType = None,
5308    copy: bool = True,
5309    **opts,
5310) -> Insert:
5311    """
5312    Builds an INSERT statement.
5313
5314    Example:
5315        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5316        'INSERT INTO tbl VALUES (1, 2, 3)'
5317
5318    Args:
5319        expression: the sql string or expression of the INSERT statement
5320        into: the tbl to insert data to.
5321        columns: optionally the table's column names.
5322        overwrite: whether to INSERT OVERWRITE or not.
5323        dialect: the dialect used to parse the input expressions.
5324        copy: whether or not to copy the expression.
5325        **opts: other options to use to parse the input expressions.
5326
5327    Returns:
5328        Insert: the syntax tree for the INSERT statement.
5329    """
5330    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5331    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5332
5333    if columns:
5334        this = _apply_list_builder(
5335            *columns,
5336            instance=Schema(this=this),
5337            arg="expressions",
5338            into=Identifier,
5339            copy=False,
5340            dialect=dialect,
5341            **opts,
5342        )
5343
5344    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:
5347def condition(
5348    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5349) -> Condition:
5350    """
5351    Initialize a logical condition expression.
5352
5353    Example:
5354        >>> condition("x=1").sql()
5355        'x = 1'
5356
5357        This is helpful for composing larger logical syntax trees:
5358        >>> where = condition("x=1")
5359        >>> where = where.and_("y=1")
5360        >>> Select().from_("tbl").select("*").where(where).sql()
5361        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
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 (in the case that the
5367            input expression is a SQL string).
5368        copy: Whether or not to copy `expression` (only applies to expressions).
5369        **opts: other options to use to parse the input expressions (again, in the case
5370            that the input expression is a SQL string).
5371
5372    Returns:
5373        The new Condition instance
5374    """
5375    return maybe_parse(
5376        expression,
5377        into=Condition,
5378        dialect=dialect,
5379        copy=copy,
5380        **opts,
5381    )

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:
5384def and_(
5385    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5386) -> Condition:
5387    """
5388    Combine multiple conditions with an AND logical operator.
5389
5390    Example:
5391        >>> and_("x=1", and_("y=1", "z=1")).sql()
5392        'x = 1 AND (y = 1 AND z = 1)'
5393
5394    Args:
5395        *expressions: the SQL code strings to parse.
5396            If an Expression instance is passed, this is used as-is.
5397        dialect: the dialect used to parse the input expression.
5398        copy: whether or not to copy `expressions` (only applies to Expressions).
5399        **opts: other options to use to parse the input expressions.
5400
5401    Returns:
5402        And: the new condition
5403    """
5404    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:
5407def or_(
5408    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5409) -> Condition:
5410    """
5411    Combine multiple conditions with an OR logical operator.
5412
5413    Example:
5414        >>> or_("x=1", or_("y=1", "z=1")).sql()
5415        'x = 1 OR (y = 1 OR z = 1)'
5416
5417    Args:
5418        *expressions: the SQL code strings to parse.
5419            If an Expression instance is passed, this is used as-is.
5420        dialect: the dialect used to parse the input expression.
5421        copy: whether or not to copy `expressions` (only applies to Expressions).
5422        **opts: other options to use to parse the input expressions.
5423
5424    Returns:
5425        Or: the new condition
5426    """
5427    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:
5430def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5431    """
5432    Wrap a condition with a NOT operator.
5433
5434    Example:
5435        >>> not_("this_suit='black'").sql()
5436        "NOT this_suit = 'black'"
5437
5438    Args:
5439        expression: the SQL code string to parse.
5440            If an Expression instance is passed, this is used as-is.
5441        dialect: the dialect used to parse the input expression.
5442        copy: whether to copy the expression or not.
5443        **opts: other options to use to parse the input expressions.
5444
5445    Returns:
5446        The new condition.
5447    """
5448    this = condition(
5449        expression,
5450        dialect=dialect,
5451        copy=copy,
5452        **opts,
5453    )
5454    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:
5457def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5458    """
5459    Wrap an expression in parentheses.
5460
5461    Example:
5462        >>> paren("5 + 3").sql()
5463        '(5 + 3)'
5464
5465    Args:
5466        expression: the SQL code string to parse.
5467            If an Expression instance is passed, this is used as-is.
5468        copy: whether to copy the expression or not.
5469
5470    Returns:
5471        The wrapped expression.
5472    """
5473    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):
5491def to_identifier(name, quoted=None, copy=True):
5492    """Builds an identifier.
5493
5494    Args:
5495        name: The name to turn into an identifier.
5496        quoted: Whether or not force quote the identifier.
5497        copy: Whether or not to copy a passed in Identefier node.
5498
5499    Returns:
5500        The identifier ast node.
5501    """
5502
5503    if name is None:
5504        return None
5505
5506    if isinstance(name, Identifier):
5507        identifier = maybe_copy(name, copy)
5508    elif isinstance(name, str):
5509        identifier = Identifier(
5510            this=name,
5511            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5512        )
5513    else:
5514        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5515    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:
5521def to_interval(interval: str | Literal) -> Interval:
5522    """Builds an interval expression from a string like '1 day' or '5 months'."""
5523    if isinstance(interval, Literal):
5524        if not interval.is_string:
5525            raise ValueError("Invalid interval string.")
5526
5527        interval = interval.this
5528
5529    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5530
5531    if not interval_parts:
5532        raise ValueError("Invalid interval string.")
5533
5534    return Interval(
5535        this=Literal.string(interval_parts.group(1)),
5536        unit=Var(this=interval_parts.group(2)),
5537    )

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]:
5550def to_table(
5551    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5552) -> t.Optional[Table]:
5553    """
5554    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5555    If a table is passed in then that table is returned.
5556
5557    Args:
5558        sql_path: a `[catalog].[schema].[table]` string.
5559        dialect: the source dialect according to which the table name will be parsed.
5560        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5561
5562    Returns:
5563        A table expression.
5564    """
5565    if sql_path is None or isinstance(sql_path, Table):
5566        return sql_path
5567    if not isinstance(sql_path, str):
5568        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5569
5570    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5571    if table:
5572        for k, v in kwargs.items():
5573            table.set(k, v)
5574
5575    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:
5578def to_column(sql_path: str | Column, **kwargs) -> Column:
5579    """
5580    Create a column from a `[table].[column]` sql path. Schema is optional.
5581
5582    If a column is passed in then that column is returned.
5583
5584    Args:
5585        sql_path: `[table].[column]` string
5586    Returns:
5587        Table: A column expression
5588    """
5589    if sql_path is None or isinstance(sql_path, Column):
5590        return sql_path
5591    if not isinstance(sql_path, str):
5592        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5593    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):
5596def alias_(
5597    expression: ExpOrStr,
5598    alias: str | Identifier,
5599    table: bool | t.Sequence[str | Identifier] = False,
5600    quoted: t.Optional[bool] = None,
5601    dialect: DialectType = None,
5602    copy: bool = True,
5603    **opts,
5604):
5605    """Create an Alias expression.
5606
5607    Example:
5608        >>> alias_('foo', 'bar').sql()
5609        'foo AS bar'
5610
5611        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5612        '(SELECT 1, 2) AS bar(a, b)'
5613
5614    Args:
5615        expression: the SQL code strings to parse.
5616            If an Expression instance is passed, this is used as-is.
5617        alias: the alias name to use. If the name has
5618            special characters it is quoted.
5619        table: Whether or not to create a table alias, can also be a list of columns.
5620        quoted: whether or not to quote the alias
5621        dialect: the dialect used to parse the input expression.
5622        copy: Whether or not to copy the expression.
5623        **opts: other options to use to parse the input expressions.
5624
5625    Returns:
5626        Alias: the aliased expression
5627    """
5628    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5629    alias = to_identifier(alias, quoted=quoted)
5630
5631    if table:
5632        table_alias = TableAlias(this=alias)
5633        exp.set("alias", table_alias)
5634
5635        if not isinstance(table, bool):
5636            for column in table:
5637                table_alias.append("columns", to_identifier(column, quoted=quoted))
5638
5639        return exp
5640
5641    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5642    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5643    # for the complete Window expression.
5644    #
5645    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5646
5647    if "alias" in exp.arg_types and not isinstance(exp, Window):
5648        exp.set("alias", alias)
5649        return exp
5650    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:
5653def subquery(
5654    expression: ExpOrStr,
5655    alias: t.Optional[Identifier | str] = None,
5656    dialect: DialectType = None,
5657    **opts,
5658) -> Select:
5659    """
5660    Build a subquery expression.
5661
5662    Example:
5663        >>> subquery('select x from tbl', 'bar').select('x').sql()
5664        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5665
5666    Args:
5667        expression: the SQL code strings to parse.
5668            If an Expression instance is passed, this is used as-is.
5669        alias: the alias name to use.
5670        dialect: the dialect used to parse the input expression.
5671        **opts: other options to use to parse the input expressions.
5672
5673    Returns:
5674        A new Select instance with the subquery expression included.
5675    """
5676
5677    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5678    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:
5681def column(
5682    col: str | Identifier,
5683    table: t.Optional[str | Identifier] = None,
5684    db: t.Optional[str | Identifier] = None,
5685    catalog: t.Optional[str | Identifier] = None,
5686    quoted: t.Optional[bool] = None,
5687) -> Column:
5688    """
5689    Build a Column.
5690
5691    Args:
5692        col: Column name.
5693        table: Table name.
5694        db: Database name.
5695        catalog: Catalog name.
5696        quoted: Whether to force quotes on the column's identifiers.
5697
5698    Returns:
5699        The new Column instance.
5700    """
5701    return Column(
5702        this=to_identifier(col, quoted=quoted),
5703        table=to_identifier(table, quoted=quoted),
5704        db=to_identifier(db, quoted=quoted),
5705        catalog=to_identifier(catalog, quoted=quoted),
5706    )

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:
5709def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5710    """Cast an expression to a data type.
5711
5712    Example:
5713        >>> cast('x + 1', 'int').sql()
5714        'CAST(x + 1 AS INT)'
5715
5716    Args:
5717        expression: The expression to cast.
5718        to: The datatype to cast to.
5719
5720    Returns:
5721        The new Cast instance.
5722    """
5723    expression = maybe_parse(expression, **opts)
5724    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:
5727def table_(
5728    table: Identifier | str,
5729    db: t.Optional[Identifier | str] = None,
5730    catalog: t.Optional[Identifier | str] = None,
5731    quoted: t.Optional[bool] = None,
5732    alias: t.Optional[Identifier | str] = None,
5733) -> Table:
5734    """Build a Table.
5735
5736    Args:
5737        table: Table name.
5738        db: Database name.
5739        catalog: Catalog name.
5740        quote: Whether to force quotes on the table's identifiers.
5741        alias: Table's alias.
5742
5743    Returns:
5744        The new Table instance.
5745    """
5746    return Table(
5747        this=to_identifier(table, quoted=quoted),
5748        db=to_identifier(db, quoted=quoted),
5749        catalog=to_identifier(catalog, quoted=quoted),
5750        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5751    )

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:
5754def values(
5755    values: t.Iterable[t.Tuple[t.Any, ...]],
5756    alias: t.Optional[str] = None,
5757    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5758) -> Values:
5759    """Build VALUES statement.
5760
5761    Example:
5762        >>> values([(1, '2')]).sql()
5763        "VALUES (1, '2')"
5764
5765    Args:
5766        values: values statements that will be converted to SQL
5767        alias: optional alias
5768        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5769         If either are provided then an alias is also required.
5770
5771    Returns:
5772        Values: the Values expression object
5773    """
5774    if columns and not alias:
5775        raise ValueError("Alias is required when providing columns")
5776
5777    return Values(
5778        expressions=[convert(tup) for tup in values],
5779        alias=(
5780            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5781            if columns
5782            else (TableAlias(this=to_identifier(alias)) if alias else None)
5783        ),
5784    )

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:
5787def var(name: t.Optional[ExpOrStr]) -> Var:
5788    """Build a SQL variable.
5789
5790    Example:
5791        >>> repr(var('x'))
5792        '(VAR this: x)'
5793
5794        >>> repr(var(column('x', table='y')))
5795        '(VAR this: x)'
5796
5797    Args:
5798        name: The name of the var or an expression who's name will become the var.
5799
5800    Returns:
5801        The new variable node.
5802    """
5803    if not name:
5804        raise ValueError("Cannot convert empty name into var.")
5805
5806    if isinstance(name, Expression):
5807        name = name.name
5808    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:
5811def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5812    """Build ALTER TABLE... RENAME... expression
5813
5814    Args:
5815        old_name: The old name of the table
5816        new_name: The new name of the table
5817
5818    Returns:
5819        Alter table expression
5820    """
5821    old_table = to_table(old_name)
5822    new_table = to_table(new_name)
5823    return AlterTable(
5824        this=old_table,
5825        actions=[
5826            RenameTable(this=new_table),
5827        ],
5828    )

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:
5831def convert(value: t.Any, copy: bool = False) -> Expression:
5832    """Convert a python value into an expression object.
5833
5834    Raises an error if a conversion is not possible.
5835
5836    Args:
5837        value: A python object.
5838        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5839
5840    Returns:
5841        Expression: the equivalent expression object.
5842    """
5843    if isinstance(value, Expression):
5844        return maybe_copy(value, copy)
5845    if isinstance(value, str):
5846        return Literal.string(value)
5847    if isinstance(value, bool):
5848        return Boolean(this=value)
5849    if value is None or (isinstance(value, float) and math.isnan(value)):
5850        return NULL
5851    if isinstance(value, numbers.Number):
5852        return Literal.number(value)
5853    if isinstance(value, datetime.datetime):
5854        datetime_literal = Literal.string(
5855            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5856        )
5857        return TimeStrToTime(this=datetime_literal)
5858    if isinstance(value, datetime.date):
5859        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5860        return DateStrToDate(this=date_literal)
5861    if isinstance(value, tuple):
5862        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5863    if isinstance(value, list):
5864        return Array(expressions=[convert(v, copy=copy) for v in value])
5865    if isinstance(value, dict):
5866        return Map(
5867            keys=[convert(k, copy=copy) for k in value],
5868            values=[convert(v, copy=copy) for v in value.values()],
5869        )
5870    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:
5873def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5874    """
5875    Replace children of an expression with the result of a lambda fun(child) -> exp.
5876    """
5877    for k, v in expression.args.items():
5878        is_list_arg = type(v) is list
5879
5880        child_nodes = v if is_list_arg else [v]
5881        new_child_nodes = []
5882
5883        for cn in child_nodes:
5884            if isinstance(cn, Expression):
5885                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5886                    new_child_nodes.append(child_node)
5887                    child_node.parent = expression
5888                    child_node.arg_key = k
5889            else:
5890                new_child_nodes.append(cn)
5891
5892        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]:
5895def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5896    """
5897    Return all table names referenced through columns in an expression.
5898
5899    Example:
5900        >>> import sqlglot
5901        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5902        ['a', 'c']
5903
5904    Args:
5905        expression: expression to find table names.
5906        exclude: a table name to exclude
5907
5908    Returns:
5909        A list of unique names.
5910    """
5911    return {
5912        table
5913        for table in (column.table for column in expression.find_all(Column))
5914        if table and table != exclude
5915    }

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:
5918def table_name(table: Table | str, dialect: DialectType = None) -> str:
5919    """Get the full name of a table as a string.
5920
5921    Args:
5922        table: Table expression node or string.
5923        dialect: The dialect to generate the table name for.
5924
5925    Examples:
5926        >>> from sqlglot import exp, parse_one
5927        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5928        'a.b.c'
5929
5930    Returns:
5931        The table name.
5932    """
5933
5934    table = maybe_parse(table, into=Table)
5935
5936    if not table:
5937        raise ValueError(f"Cannot parse {table}")
5938
5939    return ".".join(
5940        part.sql(dialect=dialect, identify=True)
5941        if not SAFE_IDENTIFIER_RE.match(part.name)
5942        else part.name
5943        for part in table.parts
5944    )

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:
5947def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5948    """Replace all tables in expression according to the mapping.
5949
5950    Args:
5951        expression: expression node to be transformed and replaced.
5952        mapping: mapping of table names.
5953        copy: whether or not to copy the expression.
5954
5955    Examples:
5956        >>> from sqlglot import exp, parse_one
5957        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5958        'SELECT * FROM c'
5959
5960    Returns:
5961        The mapped expression.
5962    """
5963
5964    def _replace_tables(node: Expression) -> Expression:
5965        if isinstance(node, Table):
5966            new_name = mapping.get(table_name(node))
5967            if new_name:
5968                return to_table(
5969                    new_name,
5970                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5971                )
5972        return node
5973
5974    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:
5977def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5978    """Replace placeholders in an expression.
5979
5980    Args:
5981        expression: expression node to be transformed and replaced.
5982        args: positional names that will substitute unnamed placeholders in the given order.
5983        kwargs: keyword arguments that will substitute named placeholders.
5984
5985    Examples:
5986        >>> from sqlglot import exp, parse_one
5987        >>> replace_placeholders(
5988        ...     parse_one("select * from :tbl where ? = ?"),
5989        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5990        ... ).sql()
5991        "SELECT * FROM foo WHERE str_col = 'b'"
5992
5993    Returns:
5994        The mapped expression.
5995    """
5996
5997    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5998        if isinstance(node, Placeholder):
5999            if node.name:
6000                new_name = kwargs.get(node.name)
6001                if new_name:
6002                    return convert(new_name)
6003            else:
6004                try:
6005                    return convert(next(args))
6006                except StopIteration:
6007                    pass
6008        return node
6009
6010    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:
6013def expand(
6014    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
6015) -> Expression:
6016    """Transforms an expression by expanding all referenced sources into subqueries.
6017
6018    Examples:
6019        >>> from sqlglot import parse_one
6020        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
6021        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
6022
6023        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
6024        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
6025
6026    Args:
6027        expression: The expression to expand.
6028        sources: A dictionary of name to Subqueryables.
6029        copy: Whether or not to copy the expression during transformation. Defaults to True.
6030
6031    Returns:
6032        The transformed expression.
6033    """
6034
6035    def _expand(node: Expression):
6036        if isinstance(node, Table):
6037            name = table_name(node)
6038            source = sources.get(name)
6039            if source:
6040                subquery = source.subquery(node.alias or name)
6041                subquery.comments = [f"source: {name}"]
6042                return subquery.transform(_expand, copy=False)
6043        return node
6044
6045    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:
6048def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6049    """
6050    Returns a Func expression.
6051
6052    Examples:
6053        >>> func("abs", 5).sql()
6054        'ABS(5)'
6055
6056        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6057        'CAST(5 AS DOUBLE)'
6058
6059    Args:
6060        name: the name of the function to build.
6061        args: the args used to instantiate the function of interest.
6062        dialect: the source dialect.
6063        kwargs: the kwargs used to instantiate the function of interest.
6064
6065    Note:
6066        The arguments `args` and `kwargs` are mutually exclusive.
6067
6068    Returns:
6069        An instance of the function of interest, or an anonymous function, if `name` doesn't
6070        correspond to an existing `sqlglot.expressions.Func` class.
6071    """
6072    if args and kwargs:
6073        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6074
6075    from sqlglot.dialects.dialect import Dialect
6076
6077    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6078    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6079
6080    parser = Dialect.get_or_raise(dialect)().parser()
6081    from_args_list = parser.FUNCTIONS.get(name.upper())
6082
6083    if from_args_list:
6084        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6085    else:
6086        kwargs = kwargs or {"expressions": converted}
6087        function = Anonymous(this=name, **kwargs)
6088
6089    for error_message in function.error_messages(converted):
6090        raise ValueError(error_message)
6091
6092    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:
6095def true() -> Boolean:
6096    """
6097    Returns a true Boolean expression.
6098    """
6099    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
6102def false() -> Boolean:
6103    """
6104    Returns a false Boolean expression.
6105    """
6106    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6109def null() -> Null:
6110    """
6111    Returns a Null expression.
6112    """
6113    return Null()

Returns a Null expression.

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