Edit on GitHub

Expressions

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

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


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

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

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

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

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

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

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

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

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

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

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

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

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

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

Returns a deep copy of the expression.

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

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

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

Sets arg_key to value.

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

Returns the depth of this tree.

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

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

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

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

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

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

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

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

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

The generator object.

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

Returns a nearest parent matching expression_types.

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

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

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

Returns the root expression of this tree.

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

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

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

the generator object.

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

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

Returns:

The generator object.

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

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

Returns:

The generator object.

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

Returns the first non parenthesis child or self.

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

Returns the inner expression if this is an Alias.

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

Returns unnested operands as a tuple.

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

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

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

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

Returns SQL string representation of this tree.

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

The SQL string.

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

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

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

The transformed tree.

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

Swap out this expression with a new expression.

For example::

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

The new expression or expressions.

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

Remove this expression from its AST.

Returns:

The popped expression.

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

Assert that this Expression is an instance of type_.

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

Examples:

This is useful for type security in chained expressions:

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

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

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

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

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

Dump this Expression to a JSON-serializable dict.

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

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

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

AND this condition with one or multiple expressions.

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

The new And condition.

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

OR this condition with one or multiple expressions.

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

The new Or condition.

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

Wrap this condition with NOT.

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

The new Not instance.

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

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

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

Builds a UNION expression.

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

The new Union expression.

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

Builds an INTERSECT expression.

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

The new Intersect expression.

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

Builds an EXCEPT expression.

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

The new Except expression.

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

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

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

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

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

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

Converts the column into a dot expression.

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

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

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

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

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

Append to or set the common table expressions.

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

The modified expression.

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

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

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:
2647    def group_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 GROUP BY expression.
2657
2658        Example:
2659            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2660            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
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 `Group`.
2666                If nothing is passed in then a group by is not applied to the expression
2667            append: if `True`, add to any existing expressions.
2668                Otherwise, this flattens all the `Group` expression into a single expression.
2669            dialect: the dialect used to parse the input expression.
2670            copy: if `False`, modify this expression instance in-place.
2671            opts: other options to use to parse the input expressions.
2672
2673        Returns:
2674            The modified Select expression.
2675        """
2676        if not expressions:
2677            return self if not copy else self.copy()
2678
2679        return _apply_child_list_builder(
2680            *expressions,
2681            instance=self,
2682            arg="group",
2683            append=append,
2684            copy=copy,
2685            prefix="GROUP BY",
2686            into=Group,
2687            dialect=dialect,
2688            **opts,
2689        )

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

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

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

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

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

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

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

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

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

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

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

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

Returns the first non subquery.

def unwrap(self) -> sqlglot.expressions.Subquery:
3311    def unwrap(self) -> Subquery:
3312        expression = self
3313        while expression.same_parent and expression.is_wrapper:
3314            expression = t.cast(Subquery, expression.parent)
3315        return expression
is_wrapper: bool

Whether this Subquery acts as a simple wrapper around another expression.

SELECT * FROM (((SELECT * FROM t))) ^ This corresponds to a "wrapper" Subquery node

is_star: bool

Checks whether an expression is a star.

output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'subquery'
class TableSample(Expression):
3337class TableSample(Expression):
3338    arg_types = {
3339        "this": False,
3340        "method": False,
3341        "bucket_numerator": False,
3342        "bucket_denominator": False,
3343        "bucket_field": False,
3344        "percent": False,
3345        "rows": False,
3346        "size": False,
3347        "seed": False,
3348        "kind": False,
3349    }
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):
3352class Tag(Expression):
3353    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3354
3355    arg_types = {
3356        "this": False,
3357        "prefix": False,
3358        "postfix": False,
3359    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3364class Pivot(Expression):
3365    arg_types = {
3366        "this": False,
3367        "alias": False,
3368        "expressions": True,
3369        "field": False,
3370        "unpivot": False,
3371        "using": False,
3372        "group": False,
3373        "columns": False,
3374        "include_nulls": False,
3375    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False, 'include_nulls': False}
key = 'pivot'
class Window(Condition):
3378class Window(Condition):
3379    arg_types = {
3380        "this": True,
3381        "partition_by": False,
3382        "order": False,
3383        "spec": False,
3384        "alias": False,
3385        "over": False,
3386        "first": False,
3387    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3390class WindowSpec(Expression):
3391    arg_types = {
3392        "kind": False,
3393        "start": False,
3394        "start_side": False,
3395        "end": False,
3396        "end_side": False,
3397    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3400class Where(Expression):
3401    pass
key = 'where'
class Star(Expression):
3404class Star(Expression):
3405    arg_types = {"except": False, "replace": False}
3406
3407    @property
3408    def name(self) -> str:
3409        return "*"
3410
3411    @property
3412    def output_name(self) -> str:
3413        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):
3416class Parameter(Condition):
3417    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3420class SessionParameter(Condition):
3421    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3424class Placeholder(Condition):
3425    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3428class Null(Condition):
3429    arg_types: t.Dict[str, t.Any] = {}
3430
3431    @property
3432    def name(self) -> str:
3433        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3436class Boolean(Condition):
3437    pass
key = 'boolean'
class DataTypeParam(Expression):
3440class DataTypeParam(Expression):
3441    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypeparam'
class DataType(Expression):
3444class DataType(Expression):
3445    arg_types = {
3446        "this": True,
3447        "expressions": False,
3448        "nested": False,
3449        "values": False,
3450        "prefix": False,
3451        "kind": False,
3452    }
3453
3454    class Type(AutoName):
3455        ARRAY = auto()
3456        BIGDECIMAL = auto()
3457        BIGINT = auto()
3458        BIGSERIAL = auto()
3459        BINARY = auto()
3460        BIT = auto()
3461        BOOLEAN = auto()
3462        CHAR = auto()
3463        DATE = auto()
3464        DATEMULTIRANGE = auto()
3465        DATERANGE = auto()
3466        DATETIME = auto()
3467        DATETIME64 = auto()
3468        DECIMAL = auto()
3469        DOUBLE = auto()
3470        ENUM = auto()
3471        ENUM8 = auto()
3472        ENUM16 = auto()
3473        FIXEDSTRING = auto()
3474        FLOAT = auto()
3475        GEOGRAPHY = auto()
3476        GEOMETRY = auto()
3477        HLLSKETCH = auto()
3478        HSTORE = auto()
3479        IMAGE = auto()
3480        INET = auto()
3481        INT = auto()
3482        INT128 = auto()
3483        INT256 = auto()
3484        INT4MULTIRANGE = auto()
3485        INT4RANGE = auto()
3486        INT8MULTIRANGE = auto()
3487        INT8RANGE = auto()
3488        INTERVAL = auto()
3489        IPADDRESS = auto()
3490        IPPREFIX = auto()
3491        JSON = auto()
3492        JSONB = auto()
3493        LONGBLOB = auto()
3494        LONGTEXT = auto()
3495        LOWCARDINALITY = auto()
3496        MAP = auto()
3497        MEDIUMBLOB = auto()
3498        MEDIUMINT = auto()
3499        MEDIUMTEXT = auto()
3500        MONEY = auto()
3501        NCHAR = auto()
3502        NESTED = auto()
3503        NULL = auto()
3504        NULLABLE = auto()
3505        NUMMULTIRANGE = auto()
3506        NUMRANGE = auto()
3507        NVARCHAR = auto()
3508        OBJECT = auto()
3509        ROWVERSION = auto()
3510        SERIAL = auto()
3511        SET = auto()
3512        SMALLINT = auto()
3513        SMALLMONEY = auto()
3514        SMALLSERIAL = auto()
3515        STRUCT = auto()
3516        SUPER = auto()
3517        TEXT = auto()
3518        TIME = auto()
3519        TIMETZ = auto()
3520        TIMESTAMP = auto()
3521        TIMESTAMPLTZ = auto()
3522        TIMESTAMPTZ = auto()
3523        TINYINT = auto()
3524        TSMULTIRANGE = auto()
3525        TSRANGE = auto()
3526        TSTZMULTIRANGE = auto()
3527        TSTZRANGE = auto()
3528        UBIGINT = auto()
3529        UINT = auto()
3530        UINT128 = auto()
3531        UINT256 = auto()
3532        UNIQUEIDENTIFIER = auto()
3533        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3534        USERDEFINED = "USER-DEFINED"
3535        USMALLINT = auto()
3536        UTINYINT = auto()
3537        UUID = auto()
3538        VARBINARY = auto()
3539        VARCHAR = auto()
3540        VARIANT = auto()
3541        XML = auto()
3542        YEAR = auto()
3543
3544    TEXT_TYPES = {
3545        Type.CHAR,
3546        Type.NCHAR,
3547        Type.VARCHAR,
3548        Type.NVARCHAR,
3549        Type.TEXT,
3550    }
3551
3552    INTEGER_TYPES = {
3553        Type.INT,
3554        Type.TINYINT,
3555        Type.SMALLINT,
3556        Type.BIGINT,
3557        Type.INT128,
3558        Type.INT256,
3559    }
3560
3561    FLOAT_TYPES = {
3562        Type.FLOAT,
3563        Type.DOUBLE,
3564    }
3565
3566    NUMERIC_TYPES = {
3567        *INTEGER_TYPES,
3568        *FLOAT_TYPES,
3569    }
3570
3571    TEMPORAL_TYPES = {
3572        Type.TIME,
3573        Type.TIMETZ,
3574        Type.TIMESTAMP,
3575        Type.TIMESTAMPTZ,
3576        Type.TIMESTAMPLTZ,
3577        Type.DATE,
3578        Type.DATETIME,
3579        Type.DATETIME64,
3580    }
3581
3582    @classmethod
3583    def build(
3584        cls,
3585        dtype: str | DataType | DataType.Type,
3586        dialect: DialectType = None,
3587        udt: bool = False,
3588        **kwargs,
3589    ) -> DataType:
3590        """
3591        Constructs a DataType object.
3592
3593        Args:
3594            dtype: the data type of interest.
3595            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3596            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3597                DataType, thus creating a user-defined type.
3598            kawrgs: additional arguments to pass in the constructor of DataType.
3599
3600        Returns:
3601            The constructed DataType object.
3602        """
3603        from sqlglot import parse_one
3604
3605        if isinstance(dtype, str):
3606            if dtype.upper() == "UNKNOWN":
3607                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3608
3609            try:
3610                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3611            except ParseError:
3612                if udt:
3613                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3614                raise
3615        elif isinstance(dtype, DataType.Type):
3616            data_type_exp = DataType(this=dtype)
3617        elif isinstance(dtype, DataType):
3618            return dtype
3619        else:
3620            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3621
3622        return DataType(**{**data_type_exp.args, **kwargs})
3623
3624    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3625        """
3626        Checks whether this DataType matches one of the provided data types. Nested types or precision
3627        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3628
3629        Args:
3630            dtypes: the data types to compare this DataType to.
3631
3632        Returns:
3633            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3634        """
3635        for dtype in dtypes:
3636            other = DataType.build(dtype, udt=True)
3637
3638            if (
3639                other.expressions
3640                or self.this == DataType.Type.USERDEFINED
3641                or other.this == DataType.Type.USERDEFINED
3642            ):
3643                matches = self == other
3644            else:
3645                matches = self.this == other.this
3646
3647            if matches:
3648                return True
3649        return False
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False, 'kind': False}
TEXT_TYPES = {<Type.NCHAR: 'NCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.TEXT: 'TEXT'>}
INTEGER_TYPES = {<Type.BIGINT: 'BIGINT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT256: 'INT256'>, <Type.INT: 'INT'>, <Type.INT128: 'INT128'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.BIGINT: 'BIGINT'>, <Type.INT: 'INT'>, <Type.FLOAT: 'FLOAT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT256: 'INT256'>, <Type.DOUBLE: 'DOUBLE'>, <Type.INT128: 'INT128'>}
TEMPORAL_TYPES = {<Type.DATE: 'DATE'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.DATETIME: 'DATETIME'>, <Type.TIME: 'TIME'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMETZ: 'TIMETZ'>, <Type.DATETIME64: 'DATETIME64'>}
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, udt: bool = False, **kwargs) -> sqlglot.expressions.DataType:
3582    @classmethod
3583    def build(
3584        cls,
3585        dtype: str | DataType | DataType.Type,
3586        dialect: DialectType = None,
3587        udt: bool = False,
3588        **kwargs,
3589    ) -> DataType:
3590        """
3591        Constructs a DataType object.
3592
3593        Args:
3594            dtype: the data type of interest.
3595            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3596            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3597                DataType, thus creating a user-defined type.
3598            kawrgs: additional arguments to pass in the constructor of DataType.
3599
3600        Returns:
3601            The constructed DataType object.
3602        """
3603        from sqlglot import parse_one
3604
3605        if isinstance(dtype, str):
3606            if dtype.upper() == "UNKNOWN":
3607                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3608
3609            try:
3610                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3611            except ParseError:
3612                if udt:
3613                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3614                raise
3615        elif isinstance(dtype, DataType.Type):
3616            data_type_exp = DataType(this=dtype)
3617        elif isinstance(dtype, DataType):
3618            return dtype
3619        else:
3620            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3621
3622        return DataType(**{**data_type_exp.args, **kwargs})

Constructs a DataType object.

Arguments:
  • dtype: the data type of interest.
  • dialect: the dialect to use for parsing dtype, in case it's a string.
  • udt: when set to True, dtype will be used as-is if it can't be parsed into a DataType, thus creating a user-defined type.
  • kawrgs: additional arguments to pass in the constructor of DataType.
Returns:

The constructed DataType object.

def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3624    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3625        """
3626        Checks whether this DataType matches one of the provided data types. Nested types or precision
3627        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3628
3629        Args:
3630            dtypes: the data types to compare this DataType to.
3631
3632        Returns:
3633            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3634        """
3635        for dtype in dtypes:
3636            other = DataType.build(dtype, udt=True)
3637
3638            if (
3639                other.expressions
3640                or self.this == DataType.Type.USERDEFINED
3641                or other.this == DataType.Type.USERDEFINED
3642            ):
3643                matches = self == other
3644            else:
3645                matches = self.this == other.this
3646
3647            if matches:
3648                return True
3649        return False

Checks whether this DataType matches one of the provided data types. Nested types or precision will be compared using "structural equivalence" semantics, so e.g. array != array.

Arguments:
  • dtypes: the data types to compare this DataType to.
Returns:

True, if and only if there is a type in dtypes which is equal to this DataType.

key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3454    class Type(AutoName):
3455        ARRAY = auto()
3456        BIGDECIMAL = auto()
3457        BIGINT = auto()
3458        BIGSERIAL = auto()
3459        BINARY = auto()
3460        BIT = auto()
3461        BOOLEAN = auto()
3462        CHAR = auto()
3463        DATE = auto()
3464        DATEMULTIRANGE = auto()
3465        DATERANGE = auto()
3466        DATETIME = auto()
3467        DATETIME64 = auto()
3468        DECIMAL = auto()
3469        DOUBLE = auto()
3470        ENUM = auto()
3471        ENUM8 = auto()
3472        ENUM16 = auto()
3473        FIXEDSTRING = auto()
3474        FLOAT = auto()
3475        GEOGRAPHY = auto()
3476        GEOMETRY = auto()
3477        HLLSKETCH = auto()
3478        HSTORE = auto()
3479        IMAGE = auto()
3480        INET = auto()
3481        INT = auto()
3482        INT128 = auto()
3483        INT256 = auto()
3484        INT4MULTIRANGE = auto()
3485        INT4RANGE = auto()
3486        INT8MULTIRANGE = auto()
3487        INT8RANGE = auto()
3488        INTERVAL = auto()
3489        IPADDRESS = auto()
3490        IPPREFIX = auto()
3491        JSON = auto()
3492        JSONB = auto()
3493        LONGBLOB = auto()
3494        LONGTEXT = auto()
3495        LOWCARDINALITY = auto()
3496        MAP = auto()
3497        MEDIUMBLOB = auto()
3498        MEDIUMINT = auto()
3499        MEDIUMTEXT = auto()
3500        MONEY = auto()
3501        NCHAR = auto()
3502        NESTED = auto()
3503        NULL = auto()
3504        NULLABLE = auto()
3505        NUMMULTIRANGE = auto()
3506        NUMRANGE = auto()
3507        NVARCHAR = auto()
3508        OBJECT = auto()
3509        ROWVERSION = auto()
3510        SERIAL = auto()
3511        SET = auto()
3512        SMALLINT = auto()
3513        SMALLMONEY = auto()
3514        SMALLSERIAL = auto()
3515        STRUCT = auto()
3516        SUPER = auto()
3517        TEXT = auto()
3518        TIME = auto()
3519        TIMETZ = auto()
3520        TIMESTAMP = auto()
3521        TIMESTAMPLTZ = auto()
3522        TIMESTAMPTZ = auto()
3523        TINYINT = auto()
3524        TSMULTIRANGE = auto()
3525        TSRANGE = auto()
3526        TSTZMULTIRANGE = auto()
3527        TSTZRANGE = auto()
3528        UBIGINT = auto()
3529        UINT = auto()
3530        UINT128 = auto()
3531        UINT256 = auto()
3532        UNIQUEIDENTIFIER = auto()
3533        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3534        USERDEFINED = "USER-DEFINED"
3535        USMALLINT = auto()
3536        UTINYINT = auto()
3537        UUID = auto()
3538        VARBINARY = auto()
3539        VARCHAR = auto()
3540        VARIANT = auto()
3541        XML = auto()
3542        YEAR = auto()

An enumeration.

ARRAY = <Type.ARRAY: 'ARRAY'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <Type.BIGINT: 'BIGINT'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
BINARY = <Type.BINARY: 'BINARY'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
CHAR = <Type.CHAR: 'CHAR'>
DATE = <Type.DATE: 'DATE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
ENUM = <Type.ENUM: 'ENUM'>
ENUM8 = <Type.ENUM8: 'ENUM8'>
ENUM16 = <Type.ENUM16: 'ENUM16'>
FIXEDSTRING = <Type.FIXEDSTRING: 'FIXEDSTRING'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
IPADDRESS = <Type.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <Type.IPPREFIX: 'IPPREFIX'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
LOWCARDINALITY = <Type.LOWCARDINALITY: 'LOWCARDINALITY'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMINT = <Type.MEDIUMINT: 'MEDIUMINT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NESTED = <Type.NESTED: 'NESTED'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TIME = <Type.TIME: 'TIME'>
TIMETZ = <Type.TIMETZ: 'TIMETZ'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
YEAR = <Type.YEAR: 'YEAR'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3653class PseudoType(Expression):
3654    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3658class SubqueryPredicate(Predicate):
3659    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3662class All(SubqueryPredicate):
3663    pass
key = 'all'
class Any(SubqueryPredicate):
3666class Any(SubqueryPredicate):
3667    pass
key = 'any'
class Exists(SubqueryPredicate):
3670class Exists(SubqueryPredicate):
3671    pass
key = 'exists'
class Command(Expression):
3676class Command(Expression):
3677    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3680class Transaction(Expression):
3681    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3684class Commit(Expression):
3685    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3688class Rollback(Expression):
3689    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3692class AlterTable(Expression):
3693    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3696class AddConstraint(Expression):
3697    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3700class DropPartition(Expression):
3701    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3705class Binary(Condition):
3706    arg_types = {"this": True, "expression": True}
3707
3708    @property
3709    def left(self):
3710        return self.this
3711
3712    @property
3713    def right(self):
3714        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3717class Add(Binary):
3718    pass
key = 'add'
class Connector(Binary):
3721class Connector(Binary):
3722    pass
key = 'connector'
class And(Connector):
3725class And(Connector):
3726    pass
key = 'and'
class Or(Connector):
3729class Or(Connector):
3730    pass
key = 'or'
class BitwiseAnd(Binary):
3733class BitwiseAnd(Binary):
3734    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3737class BitwiseLeftShift(Binary):
3738    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3741class BitwiseOr(Binary):
3742    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3745class BitwiseRightShift(Binary):
3746    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3749class BitwiseXor(Binary):
3750    pass
key = 'bitwisexor'
class Div(Binary):
3753class Div(Binary):
3754    pass
key = 'div'
class Overlaps(Binary):
3757class Overlaps(Binary):
3758    pass
key = 'overlaps'
class Dot(Binary):
3761class Dot(Binary):
3762    @property
3763    def name(self) -> str:
3764        return self.expression.name
3765
3766    @property
3767    def output_name(self) -> str:
3768        return self.name
3769
3770    @classmethod
3771    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3772        """Build a Dot object with a sequence of expressions."""
3773        if len(expressions) < 2:
3774            raise ValueError(f"Dot requires >= 2 expressions.")
3775
3776        a, b, *expressions = expressions
3777        dot = Dot(this=a, expression=b)
3778
3779        for expression in expressions:
3780            dot = Dot(this=dot, expression=expression)
3781
3782        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:
3770    @classmethod
3771    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3772        """Build a Dot object with a sequence of expressions."""
3773        if len(expressions) < 2:
3774            raise ValueError(f"Dot requires >= 2 expressions.")
3775
3776        a, b, *expressions = expressions
3777        dot = Dot(this=a, expression=b)
3778
3779        for expression in expressions:
3780            dot = Dot(this=dot, expression=expression)
3781
3782        return dot

Build a Dot object with a sequence of expressions.

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

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

key = 'kwarg'
class Like(Binary, Predicate):
3845class Like(Binary, Predicate):
3846    pass
key = 'like'
class LikeAny(Binary, Predicate):
3849class LikeAny(Binary, Predicate):
3850    pass
key = 'likeany'
class LT(Binary, Predicate):
3853class LT(Binary, Predicate):
3854    pass
key = 'lt'
class LTE(Binary, Predicate):
3857class LTE(Binary, Predicate):
3858    pass
key = 'lte'
class Mod(Binary):
3861class Mod(Binary):
3862    pass
key = 'mod'
class Mul(Binary):
3865class Mul(Binary):
3866    pass
key = 'mul'
class NEQ(Binary, Predicate):
3869class NEQ(Binary, Predicate):
3870    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3873class SimilarTo(Binary, Predicate):
3874    pass
key = 'similarto'
class Slice(Binary):
3877class Slice(Binary):
3878    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3881class Sub(Binary):
3882    pass
key = 'sub'
class ArrayOverlaps(Binary):
3885class ArrayOverlaps(Binary):
3886    pass
key = 'arrayoverlaps'
class Unary(Condition):
3891class Unary(Condition):
3892    pass
key = 'unary'
class BitwiseNot(Unary):
3895class BitwiseNot(Unary):
3896    pass
key = 'bitwisenot'
class Not(Unary):
3899class Not(Unary):
3900    pass
key = 'not'
class Paren(Unary):
3903class Paren(Unary):
3904    arg_types = {"this": True, "with": False}
3905
3906    @property
3907    def output_name(self) -> str:
3908        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):
3911class Neg(Unary):
3912    pass
key = 'neg'
class Alias(Expression):
3915class Alias(Expression):
3916    arg_types = {"this": True, "alias": False}
3917
3918    @property
3919    def output_name(self) -> str:
3920        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):
3923class Aliases(Expression):
3924    arg_types = {"this": True, "expressions": True}
3925
3926    @property
3927    def aliases(self):
3928        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3931class AtTimeZone(Expression):
3932    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3935class Between(Predicate):
3936    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3939class Bracket(Condition):
3940    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3943class SafeBracket(Bracket):
3944    """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):
3947class Distinct(Expression):
3948    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3951class In(Predicate):
3952    arg_types = {
3953        "this": True,
3954        "expressions": False,
3955        "query": False,
3956        "unnest": False,
3957        "field": False,
3958        "is_global": False,
3959    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3962class TimeUnit(Expression):
3963    """Automatically converts unit arg into a var."""
3964
3965    arg_types = {"unit": False}
3966
3967    def __init__(self, **args):
3968        unit = args.get("unit")
3969        if isinstance(unit, (Column, Literal)):
3970            args["unit"] = Var(this=unit.name)
3971        elif isinstance(unit, Week):
3972            unit.set("this", Var(this=unit.this.name))
3973
3974        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3967    def __init__(self, **args):
3968        unit = args.get("unit")
3969        if isinstance(unit, (Column, Literal)):
3970            args["unit"] = Var(this=unit.name)
3971        elif isinstance(unit, Week):
3972            unit.set("this", Var(this=unit.this.name))
3973
3974        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class IntervalYearToMonthSpan(Expression):
3979class IntervalYearToMonthSpan(Expression):
3980    arg_types = {}
arg_types = {}
key = 'intervalyeartomonthspan'
class IntervalDayToSecondSpan(Expression):
3985class IntervalDayToSecondSpan(Expression):
3986    arg_types = {}
arg_types = {}
key = 'intervaldaytosecondspan'
class Interval(TimeUnit):
3989class Interval(TimeUnit):
3990    arg_types = {"this": False, "unit": False}
3991
3992    @property
3993    def unit(self) -> t.Optional[Var]:
3994        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3997class IgnoreNulls(Expression):
3998    pass
key = 'ignorenulls'
class RespectNulls(Expression):
4001class RespectNulls(Expression):
4002    pass
key = 'respectnulls'
class Func(Condition):
4006class Func(Condition):
4007    """
4008    The base class for all function expressions.
4009
4010    Attributes:
4011        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
4012            treated as a variable length argument and the argument's value will be stored as a list.
4013        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
4014            for this function expression. These values are used to map this node to a name during parsing
4015            as well as to provide the function's name during SQL string generation. By default the SQL
4016            name is set to the expression's class name transformed to snake case.
4017    """
4018
4019    is_var_len_args = False
4020
4021    @classmethod
4022    def from_arg_list(cls, args):
4023        if cls.is_var_len_args:
4024            all_arg_keys = list(cls.arg_types)
4025            # If this function supports variable length argument treat the last argument as such.
4026            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4027            num_non_var = len(non_var_len_arg_keys)
4028
4029            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4030            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4031        else:
4032            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4033
4034        return cls(**args_dict)
4035
4036    @classmethod
4037    def sql_names(cls):
4038        if cls is Func:
4039            raise NotImplementedError(
4040                "SQL name is only supported by concrete function implementations"
4041            )
4042        if "_sql_names" not in cls.__dict__:
4043            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4044        return cls._sql_names
4045
4046    @classmethod
4047    def sql_name(cls):
4048        return cls.sql_names()[0]
4049
4050    @classmethod
4051    def default_parser_mappings(cls):
4052        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):
4021    @classmethod
4022    def from_arg_list(cls, args):
4023        if cls.is_var_len_args:
4024            all_arg_keys = list(cls.arg_types)
4025            # If this function supports variable length argument treat the last argument as such.
4026            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4027            num_non_var = len(non_var_len_arg_keys)
4028
4029            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4030            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4031        else:
4032            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4033
4034        return cls(**args_dict)
@classmethod
def sql_names(cls):
4036    @classmethod
4037    def sql_names(cls):
4038        if cls is Func:
4039            raise NotImplementedError(
4040                "SQL name is only supported by concrete function implementations"
4041            )
4042        if "_sql_names" not in cls.__dict__:
4043            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4044        return cls._sql_names
@classmethod
def sql_name(cls):
4046    @classmethod
4047    def sql_name(cls):
4048        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
4050    @classmethod
4051    def default_parser_mappings(cls):
4052        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
4055class AggFunc(Func):
4056    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
4059class ParameterizedAgg(AggFunc):
4060    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
4063class Abs(Func):
4064    pass
key = 'abs'
class Transform(Func):
4068class Transform(Func):
4069    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
4072class Anonymous(Func):
4073    arg_types = {"this": True, "expressions": False}
4074    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
4079class Hll(AggFunc):
4080    arg_types = {"this": True, "expressions": False}
4081    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
4084class ApproxDistinct(AggFunc):
4085    arg_types = {"this": True, "accuracy": False}
4086    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
4089class Array(Func):
4090    arg_types = {"expressions": False}
4091    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
4095class ToChar(Func):
4096    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
4099class GenerateSeries(Func):
4100    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
4103class ArrayAgg(AggFunc):
4104    pass
key = 'arrayagg'
class ArrayAll(Func):
4107class ArrayAll(Func):
4108    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4111class ArrayAny(Func):
4112    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4115class ArrayConcat(Func):
4116    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4117    arg_types = {"this": True, "expressions": False}
4118    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4121class ArrayContains(Binary, Func):
4122    pass
key = 'arraycontains'
class ArrayContained(Binary):
4125class ArrayContained(Binary):
4126    pass
key = 'arraycontained'
class ArrayFilter(Func):
4129class ArrayFilter(Func):
4130    arg_types = {"this": True, "expression": True}
4131    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4134class ArrayJoin(Func):
4135    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4138class ArraySize(Func):
4139    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4142class ArraySort(Func):
4143    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4146class ArraySum(Func):
4147    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4150class ArrayUnionAgg(AggFunc):
4151    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4154class Avg(AggFunc):
4155    pass
key = 'avg'
class AnyValue(AggFunc):
4158class AnyValue(AggFunc):
4159    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):
4162class First(Func):
4163    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4166class Last(Func):
4167    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4170class Case(Func):
4171    arg_types = {"this": False, "ifs": True, "default": False}
4172
4173    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4174        instance = maybe_copy(self, copy)
4175        instance.append(
4176            "ifs",
4177            If(
4178                this=maybe_parse(condition, copy=copy, **opts),
4179                true=maybe_parse(then, copy=copy, **opts),
4180            ),
4181        )
4182        return instance
4183
4184    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4185        instance = maybe_copy(self, copy)
4186        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4187        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:
4173    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4174        instance = maybe_copy(self, copy)
4175        instance.append(
4176            "ifs",
4177            If(
4178                this=maybe_parse(condition, copy=copy, **opts),
4179                true=maybe_parse(then, copy=copy, **opts),
4180            ),
4181        )
4182        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4184    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4185        instance = maybe_copy(self, copy)
4186        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4187        return instance
key = 'case'
class Cast(Func):
4190class Cast(Func):
4191    arg_types = {"this": True, "to": True, "format": False}
4192
4193    @property
4194    def name(self) -> str:
4195        return self.this.name
4196
4197    @property
4198    def to(self) -> DataType:
4199        return self.args["to"]
4200
4201    @property
4202    def output_name(self) -> str:
4203        return self.name
4204
4205    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4206        """
4207        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4208        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4209        array<int> != array<float>.
4210
4211        Args:
4212            dtypes: the data types to compare this Cast's DataType to.
4213
4214        Returns:
4215            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4216        """
4217        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:
4205    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4206        """
4207        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4208        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4209        array<int> != array<float>.
4210
4211        Args:
4212            dtypes: the data types to compare this Cast's DataType to.
4213
4214        Returns:
4215            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4216        """
4217        return self.to.is_type(*dtypes)

Checks whether this Cast's DataType matches one of the provided data types. Nested types like arrays or structs will be compared using "structural equivalence" semantics, so e.g. array != array.

Arguments:
  • dtypes: the data types to compare this Cast's DataType to.
Returns:

True, if and only if there is a type in dtypes which is equal to this Cast's DataType.

key = 'cast'
class TryCast(Cast):
4220class TryCast(Cast):
4221    pass
key = 'trycast'
class CastToStrType(Func):
4224class CastToStrType(Func):
4225    arg_types = {"this": True, "to": True}
arg_types = {'this': True, 'to': True}
key = 'casttostrtype'
class Collate(Binary):
4228class Collate(Binary):
4229    pass
key = 'collate'
class Ceil(Func):
4232class Ceil(Func):
4233    arg_types = {"this": True, "decimals": False}
4234    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4237class Coalesce(Func):
4238    arg_types = {"this": True, "expressions": False}
4239    is_var_len_args = True
4240    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4243class Concat(Func):
4244    arg_types = {"expressions": True}
4245    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4248class SafeConcat(Concat):
4249    pass
key = 'safeconcat'
class ConcatWs(Concat):
4252class ConcatWs(Concat):
4253    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4256class Count(AggFunc):
4257    arg_types = {"this": False, "expressions": False}
4258    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4261class CountIf(AggFunc):
4262    pass
key = 'countif'
class CurrentDate(Func):
4265class CurrentDate(Func):
4266    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4269class CurrentDatetime(Func):
4270    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4273class CurrentTime(Func):
4274    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4277class CurrentTimestamp(Func):
4278    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4281class CurrentUser(Func):
4282    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4285class DateAdd(Func, TimeUnit):
4286    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4289class DateSub(Func, TimeUnit):
4290    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4293class DateDiff(Func, TimeUnit):
4294    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4295    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4298class DateTrunc(Func):
4299    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4302class DatetimeAdd(Func, TimeUnit):
4303    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4306class DatetimeSub(Func, TimeUnit):
4307    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4310class DatetimeDiff(Func, TimeUnit):
4311    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4314class DatetimeTrunc(Func, TimeUnit):
4315    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4318class DayOfWeek(Func):
4319    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4322class DayOfMonth(Func):
4323    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4326class DayOfYear(Func):
4327    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4330class WeekOfYear(Func):
4331    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4334class MonthsBetween(Func):
4335    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4338class LastDateOfMonth(Func):
4339    pass
key = 'lastdateofmonth'
class Extract(Func):
4342class Extract(Func):
4343    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4346class TimestampAdd(Func, TimeUnit):
4347    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4350class TimestampSub(Func, TimeUnit):
4351    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4354class TimestampDiff(Func, TimeUnit):
4355    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4358class TimestampTrunc(Func, TimeUnit):
4359    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4362class TimeAdd(Func, TimeUnit):
4363    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4366class TimeSub(Func, TimeUnit):
4367    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4370class TimeDiff(Func, TimeUnit):
4371    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4374class TimeTrunc(Func, TimeUnit):
4375    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4378class DateFromParts(Func):
4379    _sql_names = ["DATEFROMPARTS"]
4380    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4383class DateStrToDate(Func):
4384    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4387class DateToDateStr(Func):
4388    pass
key = 'datetodatestr'
class DateToDi(Func):
4391class DateToDi(Func):
4392    pass
key = 'datetodi'
class Date(Func):
4396class Date(Func):
4397    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4400class Day(Func):
4401    pass
key = 'day'
class Decode(Func):
4404class Decode(Func):
4405    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4408class DiToDate(Func):
4409    pass
key = 'ditodate'
class Encode(Func):
4412class Encode(Func):
4413    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4416class Exp(Func):
4417    pass
key = 'exp'
class Explode(Func):
4420class Explode(Func):
4421    pass
key = 'explode'
class Floor(Func):
4424class Floor(Func):
4425    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4428class FromBase64(Func):
4429    pass
key = 'frombase64'
class ToBase64(Func):
4432class ToBase64(Func):
4433    pass
key = 'tobase64'
class Greatest(Func):
4436class Greatest(Func):
4437    arg_types = {"this": True, "expressions": False}
4438    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4441class GroupConcat(Func):
4442    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4445class Hex(Func):
4446    pass
key = 'hex'
class Xor(Connector, Func):
4449class Xor(Connector, Func):
4450    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4453class If(Func):
4454    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4457class Initcap(Func):
4458    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4461class IsNan(Func):
4462    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class JSONKeyValue(Expression):
4465class JSONKeyValue(Expression):
4466    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4469class JSONObject(Func):
4470    arg_types = {
4471        "expressions": False,
4472        "null_handling": False,
4473        "unique_keys": False,
4474        "return_type": False,
4475        "format_json": False,
4476        "encoding": False,
4477    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4480class OpenJSONColumnDef(Expression):
4481    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):
4484class OpenJSON(Func):
4485    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4488class JSONBContains(Binary):
4489    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4492class JSONExtract(Binary, Func):
4493    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4496class JSONExtractScalar(JSONExtract):
4497    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4500class JSONBExtract(JSONExtract):
4501    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4504class JSONBExtractScalar(JSONExtract):
4505    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4508class JSONFormat(Func):
4509    arg_types = {"this": False, "options": False}
4510    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4514class JSONArrayContains(Binary, Predicate, Func):
4515    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4518class Least(Func):
4519    arg_types = {"this": True, "expressions": False}
4520    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4523class Left(Func):
4524    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4531class Length(Func):
4532    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4535class Levenshtein(Func):
4536    arg_types = {
4537        "this": True,
4538        "expression": False,
4539        "ins_cost": False,
4540        "del_cost": False,
4541        "sub_cost": False,
4542    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4545class Ln(Func):
4546    pass
key = 'ln'
class Log(Func):
4549class Log(Func):
4550    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4553class Log2(Func):
4554    pass
key = 'log2'
class Log10(Func):
4557class Log10(Func):
4558    pass
key = 'log10'
class LogicalOr(AggFunc):
4561class LogicalOr(AggFunc):
4562    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4565class LogicalAnd(AggFunc):
4566    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4569class Lower(Func):
4570    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4573class Map(Func):
4574    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4577class MapFromEntries(Func):
4578    pass
key = 'mapfromentries'
class StarMap(Func):
4581class StarMap(Func):
4582    pass
key = 'starmap'
class VarMap(Func):
4585class VarMap(Func):
4586    arg_types = {"keys": True, "values": True}
4587    is_var_len_args = True
4588
4589    @property
4590    def keys(self) -> t.List[Expression]:
4591        return self.args["keys"].expressions
4592
4593    @property
4594    def values(self) -> t.List[Expression]:
4595        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4599class MatchAgainst(Func):
4600    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4603class Max(AggFunc):
4604    arg_types = {"this": True, "expressions": False}
4605    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4608class MD5(Func):
4609    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4613class MD5Digest(Func):
4614    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4617class Min(AggFunc):
4618    arg_types = {"this": True, "expressions": False}
4619    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4622class Month(Func):
4623    pass
key = 'month'
class Nvl2(Func):
4626class Nvl2(Func):
4627    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4630class Posexplode(Func):
4631    pass
key = 'posexplode'
class Pow(Binary, Func):
4634class Pow(Binary, Func):
4635    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4638class PercentileCont(AggFunc):
4639    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4642class PercentileDisc(AggFunc):
4643    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4646class Quantile(AggFunc):
4647    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4650class ApproxQuantile(Quantile):
4651    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):
4654class RangeN(Func):
4655    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4658class ReadCSV(Func):
4659    _sql_names = ["READ_CSV"]
4660    is_var_len_args = True
4661    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4664class Reduce(Func):
4665    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):
4668class RegexpExtract(Func):
4669    arg_types = {
4670        "this": True,
4671        "expression": True,
4672        "position": False,
4673        "occurrence": False,
4674        "parameters": False,
4675        "group": False,
4676    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4679class RegexpReplace(Func):
4680    arg_types = {
4681        "this": True,
4682        "expression": True,
4683        "replacement": True,
4684        "position": False,
4685        "occurrence": False,
4686        "parameters": False,
4687    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4690class RegexpLike(Binary, Func):
4691    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4694class RegexpILike(Func):
4695    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4700class RegexpSplit(Func):
4701    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4704class Repeat(Func):
4705    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4708class Round(Func):
4709    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4712class RowNumber(Func):
4713    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4716class SafeDivide(Func):
4717    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4720class SetAgg(AggFunc):
4721    pass
key = 'setagg'
class SHA(Func):
4724class SHA(Func):
4725    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4728class SHA2(Func):
4729    _sql_names = ["SHA2"]
4730    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4733class SortArray(Func):
4734    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4737class Split(Func):
4738    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4743class Substring(Func):
4744    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4747class StandardHash(Func):
4748    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4751class StartsWith(Func):
4752    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4753    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4756class StrPosition(Func):
4757    arg_types = {
4758        "this": True,
4759        "substr": True,
4760        "position": False,
4761        "instance": False,
4762    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4765class StrToDate(Func):
4766    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4769class StrToTime(Func):
4770    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4775class StrToUnix(Func):
4776    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
4781class StrToMap(Func):
4782    arg_types = {
4783        "this": True,
4784        "pair_delim": False,
4785        "key_value_delim": False,
4786        "duplicate_resolution_callback": False,
4787    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
4790class NumberToStr(Func):
4791    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
4794class FromBase(Func):
4795    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4798class Struct(Func):
4799    arg_types = {"expressions": True}
4800    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4803class StructExtract(Func):
4804    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Stuff(Func):
4809class Stuff(Func):
4810    _sql_names = ["STUFF", "INSERT"]
4811    arg_types = {"this": True, "start": True, "length": True, "expression": True}
arg_types = {'this': True, 'start': True, 'length': True, 'expression': True}
key = 'stuff'
class Sum(AggFunc):
4814class Sum(AggFunc):
4815    pass
key = 'sum'
class Sqrt(Func):
4818class Sqrt(Func):
4819    pass
key = 'sqrt'
class Stddev(AggFunc):
4822class Stddev(AggFunc):
4823    pass
key = 'stddev'
class StddevPop(AggFunc):
4826class StddevPop(AggFunc):
4827    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4830class StddevSamp(AggFunc):
4831    pass
key = 'stddevsamp'
class TimeToStr(Func):
4834class TimeToStr(Func):
4835    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
4838class TimeToTimeStr(Func):
4839    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4842class TimeToUnix(Func):
4843    pass
key = 'timetounix'
class TimeStrToDate(Func):
4846class TimeStrToDate(Func):
4847    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4850class TimeStrToTime(Func):
4851    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4854class TimeStrToUnix(Func):
4855    pass
key = 'timestrtounix'
class Trim(Func):
4858class Trim(Func):
4859    arg_types = {
4860        "this": True,
4861        "expression": False,
4862        "position": False,
4863        "collation": False,
4864    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4867class TsOrDsAdd(Func, TimeUnit):
4868    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4871class TsOrDsToDateStr(Func):
4872    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4875class TsOrDsToDate(Func):
4876    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4879class TsOrDiToDi(Func):
4880    pass
key = 'tsorditodi'
class Unhex(Func):
4883class Unhex(Func):
4884    pass
key = 'unhex'
class UnixToStr(Func):
4887class UnixToStr(Func):
4888    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4893class UnixToTime(Func):
4894    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4895
4896    SECONDS = Literal.string("seconds")
4897    MILLIS = Literal.string("millis")
4898    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):
4901class UnixToTimeStr(Func):
4902    pass
key = 'unixtotimestr'
class Upper(Func):
4905class Upper(Func):
4906    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4909class Variance(AggFunc):
4910    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4913class VariancePop(AggFunc):
4914    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4917class Week(Func):
4918    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4921class XMLTable(Func):
4922    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):
4925class Year(Func):
4926    pass
key = 'year'
class Use(Expression):
4929class Use(Expression):
4930    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4933class Merge(Expression):
4934    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):
4937class When(Func):
4938    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):
4943class NextValueFor(Func):
4944    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.First'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.IsNan'>, <class 'sqlglot.expressions.JSONArrayContains'>, <class 'sqlglot.expressions.JSONBExtract'>, <class 'sqlglot.expressions.JSONBExtractScalar'>, <class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.JSONExtractScalar'>, <class 'sqlglot.expressions.JSONFormat'>, <class 'sqlglot.expressions.JSONObject'>, <class 'sqlglot.expressions.Last'>, <class 'sqlglot.expressions.LastDateOfMonth'>, <class 'sqlglot.expressions.Least'>, <class 'sqlglot.expressions.Left'>, <class 'sqlglot.expressions.Length'>, <class 'sqlglot.expressions.Levenshtein'>, <class 'sqlglot.expressions.Ln'>, <class 'sqlglot.expressions.Log'>, <class 'sqlglot.expressions.Log10'>, <class 'sqlglot.expressions.Log2'>, <class 'sqlglot.expressions.LogicalAnd'>, <class 'sqlglot.expressions.LogicalOr'>, <class 'sqlglot.expressions.Lower'>, <class 'sqlglot.expressions.MD5'>, <class 'sqlglot.expressions.MD5Digest'>, <class 'sqlglot.expressions.Map'>, <class 'sqlglot.expressions.MapFromEntries'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <class 'sqlglot.expressions.MonthsBetween'>, <class 'sqlglot.expressions.NextValueFor'>, <class 'sqlglot.expressions.NumberToStr'>, <class 'sqlglot.expressions.Nvl2'>, <class 'sqlglot.expressions.OpenJSON'>, <class 'sqlglot.expressions.ParameterizedAgg'>, <class 'sqlglot.expressions.PercentileCont'>, <class 'sqlglot.expressions.PercentileDisc'>, <class 'sqlglot.expressions.Posexplode'>, <class 'sqlglot.expressions.Pow'>, <class 'sqlglot.expressions.Quantile'>, <class 'sqlglot.expressions.RangeN'>, <class 'sqlglot.expressions.ReadCSV'>, <class 'sqlglot.expressions.Reduce'>, <class 'sqlglot.expressions.RegexpExtract'>, <class 'sqlglot.expressions.RegexpILike'>, <class 'sqlglot.expressions.RegexpLike'>, <class 'sqlglot.expressions.RegexpReplace'>, <class 'sqlglot.expressions.RegexpSplit'>, <class 'sqlglot.expressions.Repeat'>, <class 'sqlglot.expressions.Right'>, <class 'sqlglot.expressions.Round'>, <class 'sqlglot.expressions.RowNumber'>, <class 'sqlglot.expressions.SHA'>, <class 'sqlglot.expressions.SHA2'>, <class 'sqlglot.expressions.SafeConcat'>, <class 'sqlglot.expressions.SafeDivide'>, <class 'sqlglot.expressions.SetAgg'>, <class 'sqlglot.expressions.SortArray'>, <class 'sqlglot.expressions.Split'>, <class 'sqlglot.expressions.Sqrt'>, <class 'sqlglot.expressions.StandardHash'>, <class 'sqlglot.expressions.StarMap'>, <class 'sqlglot.expressions.StartsWith'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToMap'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Stuff'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.Transform'>, <class 'sqlglot.expressions.Trim'>, <class 'sqlglot.expressions.TryCast'>, <class 'sqlglot.expressions.TsOrDiToDi'>, <class 'sqlglot.expressions.TsOrDsAdd'>, <class 'sqlglot.expressions.TsOrDsToDate'>, <class 'sqlglot.expressions.TsOrDsToDateStr'>, <class 'sqlglot.expressions.Unhex'>, <class 'sqlglot.expressions.UnixToStr'>, <class 'sqlglot.expressions.UnixToTime'>, <class 'sqlglot.expressions.UnixToTimeStr'>, <class 'sqlglot.expressions.Upper'>, <class 'sqlglot.expressions.VarMap'>, <class 'sqlglot.expressions.Variance'>, <class 'sqlglot.expressions.VariancePop'>, <class 'sqlglot.expressions.Week'>, <class 'sqlglot.expressions.WeekOfYear'>, <class 'sqlglot.expressions.When'>, <class 'sqlglot.expressions.XMLTable'>, <class 'sqlglot.expressions.Xor'>, <class 'sqlglot.expressions.Year'>]
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4981def maybe_parse(
4982    sql_or_expression: ExpOrStr,
4983    *,
4984    into: t.Optional[IntoType] = None,
4985    dialect: DialectType = None,
4986    prefix: t.Optional[str] = None,
4987    copy: bool = False,
4988    **opts,
4989) -> Expression:
4990    """Gracefully handle a possible string or expression.
4991
4992    Example:
4993        >>> maybe_parse("1")
4994        (LITERAL this: 1, is_string: False)
4995        >>> maybe_parse(to_identifier("x"))
4996        (IDENTIFIER this: x, quoted: False)
4997
4998    Args:
4999        sql_or_expression: the SQL code string or an expression
5000        into: the SQLGlot Expression to parse into
5001        dialect: the dialect used to parse the input expressions (in the case that an
5002            input expression is a SQL string).
5003        prefix: a string to prefix the sql with before it gets parsed
5004            (automatically includes a space)
5005        copy: whether or not to copy the expression.
5006        **opts: other options to use to parse the input expressions (again, in the case
5007            that an input expression is a SQL string).
5008
5009    Returns:
5010        Expression: the parsed or given expression.
5011    """
5012    if isinstance(sql_or_expression, Expression):
5013        if copy:
5014            return sql_or_expression.copy()
5015        return sql_or_expression
5016
5017    if sql_or_expression is None:
5018        raise ParseError(f"SQL cannot be None")
5019
5020    import sqlglot
5021
5022    sql = str(sql_or_expression)
5023    if prefix:
5024        sql = f"{prefix} {sql}"
5025
5026    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):
5039def maybe_copy(instance, copy=True):
5040    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:
5220def union(
5221    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5222) -> Union:
5223    """
5224    Initializes a syntax tree from one UNION expression.
5225
5226    Example:
5227        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5228        'SELECT * FROM foo UNION SELECT * FROM bla'
5229
5230    Args:
5231        left: the SQL code string corresponding to the left-hand side.
5232            If an `Expression` instance is passed, it will be used as-is.
5233        right: the SQL code string corresponding to the right-hand side.
5234            If an `Expression` instance is passed, it will be used as-is.
5235        distinct: set the DISTINCT flag if and only if this is true.
5236        dialect: the dialect used to parse the input expression.
5237        opts: other options to use to parse the input expressions.
5238
5239    Returns:
5240        The new Union instance.
5241    """
5242    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5243    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5244
5245    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:
5248def intersect(
5249    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5250) -> Intersect:
5251    """
5252    Initializes a syntax tree from one INTERSECT expression.
5253
5254    Example:
5255        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5256        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5257
5258    Args:
5259        left: the SQL code string corresponding to the left-hand side.
5260            If an `Expression` instance is passed, it will be used as-is.
5261        right: the SQL code string corresponding to the right-hand side.
5262            If an `Expression` instance is passed, it will be used as-is.
5263        distinct: set the DISTINCT flag if and only if this is true.
5264        dialect: the dialect used to parse the input expression.
5265        opts: other options to use to parse the input expressions.
5266
5267    Returns:
5268        The new Intersect instance.
5269    """
5270    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5271    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5272
5273    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:
5276def except_(
5277    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5278) -> Except:
5279    """
5280    Initializes a syntax tree from one EXCEPT expression.
5281
5282    Example:
5283        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5284        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5285
5286    Args:
5287        left: the SQL code string corresponding to the left-hand side.
5288            If an `Expression` instance is passed, it will be used as-is.
5289        right: the SQL code string corresponding to the right-hand side.
5290            If an `Expression` instance is passed, it will be used as-is.
5291        distinct: set the DISTINCT flag if and only if this is true.
5292        dialect: the dialect used to parse the input expression.
5293        opts: other options to use to parse the input expressions.
5294
5295    Returns:
5296        The new Except instance.
5297    """
5298    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5299    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5300
5301    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:
5304def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5305    """
5306    Initializes a syntax tree from one or multiple SELECT expressions.
5307
5308    Example:
5309        >>> select("col1", "col2").from_("tbl").sql()
5310        'SELECT col1, col2 FROM tbl'
5311
5312    Args:
5313        *expressions: the SQL code string to parse as the expressions of a
5314            SELECT statement. If an Expression instance is passed, this is used as-is.
5315        dialect: the dialect used to parse the input expressions (in the case that an
5316            input expression is a SQL string).
5317        **opts: other options to use to parse the input expressions (again, in the case
5318            that an input expression is a SQL string).
5319
5320    Returns:
5321        Select: the syntax tree for the SELECT statement.
5322    """
5323    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:
5326def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5327    """
5328    Initializes a syntax tree from a FROM expression.
5329
5330    Example:
5331        >>> from_("tbl").select("col1", "col2").sql()
5332        'SELECT col1, col2 FROM tbl'
5333
5334    Args:
5335        *expression: the SQL code string to parse as the FROM expressions of a
5336            SELECT statement. If an Expression instance is passed, this is used as-is.
5337        dialect: the dialect used to parse the input expression (in the case that the
5338            input expression is a SQL string).
5339        **opts: other options to use to parse the input expressions (again, in the case
5340            that the input expression is a SQL string).
5341
5342    Returns:
5343        Select: the syntax tree for the SELECT statement.
5344    """
5345    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:
5348def update(
5349    table: str | Table,
5350    properties: dict,
5351    where: t.Optional[ExpOrStr] = None,
5352    from_: t.Optional[ExpOrStr] = None,
5353    dialect: DialectType = None,
5354    **opts,
5355) -> Update:
5356    """
5357    Creates an update statement.
5358
5359    Example:
5360        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5361        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5362
5363    Args:
5364        *properties: dictionary of properties to set which are
5365            auto converted to sql objects eg None -> NULL
5366        where: sql conditional parsed into a WHERE statement
5367        from_: sql statement parsed into a FROM statement
5368        dialect: the dialect used to parse the input expressions.
5369        **opts: other options to use to parse the input expressions.
5370
5371    Returns:
5372        Update: the syntax tree for the UPDATE statement.
5373    """
5374    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5375    update_expr.set(
5376        "expressions",
5377        [
5378            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5379            for k, v in properties.items()
5380        ],
5381    )
5382    if from_:
5383        update_expr.set(
5384            "from",
5385            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5386        )
5387    if isinstance(where, Condition):
5388        where = Where(this=where)
5389    if where:
5390        update_expr.set(
5391            "where",
5392            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5393        )
5394    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:
5397def delete(
5398    table: ExpOrStr,
5399    where: t.Optional[ExpOrStr] = None,
5400    returning: t.Optional[ExpOrStr] = None,
5401    dialect: DialectType = None,
5402    **opts,
5403) -> Delete:
5404    """
5405    Builds a delete statement.
5406
5407    Example:
5408        >>> delete("my_table", where="id > 1").sql()
5409        'DELETE FROM my_table WHERE id > 1'
5410
5411    Args:
5412        where: sql conditional parsed into a WHERE statement
5413        returning: sql conditional parsed into a RETURNING statement
5414        dialect: the dialect used to parse the input expressions.
5415        **opts: other options to use to parse the input expressions.
5416
5417    Returns:
5418        Delete: the syntax tree for the DELETE statement.
5419    """
5420    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5421    if where:
5422        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5423    if returning:
5424        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5425    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:
5428def insert(
5429    expression: ExpOrStr,
5430    into: ExpOrStr,
5431    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5432    overwrite: t.Optional[bool] = None,
5433    dialect: DialectType = None,
5434    copy: bool = True,
5435    **opts,
5436) -> Insert:
5437    """
5438    Builds an INSERT statement.
5439
5440    Example:
5441        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5442        'INSERT INTO tbl VALUES (1, 2, 3)'
5443
5444    Args:
5445        expression: the sql string or expression of the INSERT statement
5446        into: the tbl to insert data to.
5447        columns: optionally the table's column names.
5448        overwrite: whether to INSERT OVERWRITE or not.
5449        dialect: the dialect used to parse the input expressions.
5450        copy: whether or not to copy the expression.
5451        **opts: other options to use to parse the input expressions.
5452
5453    Returns:
5454        Insert: the syntax tree for the INSERT statement.
5455    """
5456    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5457    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5458
5459    if columns:
5460        this = _apply_list_builder(
5461            *columns,
5462            instance=Schema(this=this),
5463            arg="expressions",
5464            into=Identifier,
5465            copy=False,
5466            dialect=dialect,
5467            **opts,
5468        )
5469
5470    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:
5473def condition(
5474    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5475) -> Condition:
5476    """
5477    Initialize a logical condition expression.
5478
5479    Example:
5480        >>> condition("x=1").sql()
5481        'x = 1'
5482
5483        This is helpful for composing larger logical syntax trees:
5484        >>> where = condition("x=1")
5485        >>> where = where.and_("y=1")
5486        >>> Select().from_("tbl").select("*").where(where).sql()
5487        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5488
5489    Args:
5490        *expression: the SQL code string to parse.
5491            If an Expression instance is passed, this is used as-is.
5492        dialect: the dialect used to parse the input expression (in the case that the
5493            input expression is a SQL string).
5494        copy: Whether or not to copy `expression` (only applies to expressions).
5495        **opts: other options to use to parse the input expressions (again, in the case
5496            that the input expression is a SQL string).
5497
5498    Returns:
5499        The new Condition instance
5500    """
5501    return maybe_parse(
5502        expression,
5503        into=Condition,
5504        dialect=dialect,
5505        copy=copy,
5506        **opts,
5507    )

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

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

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

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

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

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

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

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

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
6228def false() -> Boolean:
6229    """
6230    Returns a false Boolean expression.
6231    """
6232    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6235def null() -> Null:
6236    """
6237    Returns a Null expression.
6238    """
6239    return Null()

Returns a Null expression.

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