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

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 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)
 94    def __init__(self, **args: t.Any):
 95        self.args: t.Dict[str, t.Any] = args
 96        self.parent: t.Optional[Expression] = None
 97        self.arg_key: t.Optional[str] = None
 98        self.comments: t.Optional[t.List[str]] = None
 99        self._type: t.Optional[DataType] = None
100        self._meta: t.Optional[t.Dict[str, t.Any]] = None
101        self._hash: t.Optional[int] = None
102
103        for arg_key, value in self.args.items():
104            self._set_parent(arg_key, value)
key = 'expression'
arg_types = {'this': True}
args: Dict[str, Any]
parent: Optional[Expression]
arg_key: Optional[str]
comments: Optional[List[str]]
hashable_args: Any
this: Any

Retrieves the argument with key "this".

expression: Any

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        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")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
type: Optional[DataType]
meta: Dict[str, Any]
def copy(self):
261    def copy(self):
262        """
263        Returns a deep copy of the expression.
264        """
265        new = deepcopy(self)
266        new.parent = self.parent
267        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
269    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
270        if self.comments is None:
271            self.comments = []
272        if comments:
273            for comment in comments:
274                _, *meta = comment.split(SQLGLOT_META)
275                if meta:
276                    for kv in "".join(meta).split(","):
277                        k, *v = kv.split("=")
278                        value = v[0].strip() if v else True
279                        self.meta[k.strip()] = value
280                self.comments.append(comment)
def append(self, arg_key: str, value: Any) -> None:
282    def append(self, arg_key: str, value: t.Any) -> None:
283        """
284        Appends value to arg_key if it's a list or sets it as a new list.
285
286        Args:
287            arg_key (str): name of the list expression arg
288            value (Any): value to append to the list
289        """
290        if not isinstance(self.args.get(arg_key), list):
291            self.args[arg_key] = []
292        self.args[arg_key].append(value)
293        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:
295    def set(self, arg_key: str, value: t.Any) -> None:
296        """
297        Sets arg_key to value.
298
299        Args:
300            arg_key: name of the expression arg.
301            value: value to set the arg to.
302        """
303        if value is None:
304            self.args.pop(arg_key, None)
305            return
306
307        self.args[arg_key] = value
308        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, Expression]]:
329    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
330        """Yields the key and expression for all arguments, exploding list args."""
331        for k, vs in self.args.items():
332            if type(vs) is list:
333                for v in vs:
334                    if hasattr(v, "parent"):
335                        yield k, v
336            else:
337                if hasattr(vs, "parent"):
338                    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]:
340    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
341        """
342        Returns the first node in this tree which matches at least one of
343        the specified types.
344
345        Args:
346            expression_types: the expression type(s) to match.
347            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
348
349        Returns:
350            The node which matches the criteria or None if no such node was found.
351        """
352        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]:
354    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
355        """
356        Returns a generator object which visits all nodes in this tree and only
357        yields those that match at least one of the specified expression types.
358
359        Args:
360            expression_types: the expression type(s) to match.
361            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
362
363        Returns:
364            The generator object.
365        """
366        for expression, *_ in self.walk(bfs=bfs):
367            if isinstance(expression, expression_types):
368                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]:
370    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
371        """
372        Returns a nearest parent matching expression_types.
373
374        Args:
375            expression_types: the expression type(s) to match.
376
377        Returns:
378            The parent node.
379        """
380        ancestor = self.parent
381        while ancestor and not isinstance(ancestor, expression_types):
382            ancestor = ancestor.parent
383        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[Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

def root(self) -> Expression:
397    def root(self) -> Expression:
398        """
399        Returns the root expression of this tree.
400        """
401        expression = self
402        while expression.parent:
403            expression = expression.parent
404        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
406    def walk(self, bfs=True, prune=None):
407        """
408        Returns a generator object which visits all nodes in this tree.
409
410        Args:
411            bfs (bool): if set to True the BFS traversal order will be applied,
412                otherwise the DFS traversal will be used instead.
413            prune ((node, parent, arg_key) -> bool): callable that returns True if
414                the generator should stop traversing this branch of the tree.
415
416        Returns:
417            the generator object.
418        """
419        if bfs:
420            yield from self.bfs(prune=prune)
421        else:
422            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):
424    def dfs(self, parent=None, key=None, prune=None):
425        """
426        Returns a generator object which visits all nodes in this tree in
427        the DFS (Depth-first) order.
428
429        Returns:
430            The generator object.
431        """
432        parent = parent or self.parent
433        yield self, parent, key
434        if prune and prune(self, parent, key):
435            return
436
437        for k, v in self.iter_expressions():
438            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):
440    def bfs(self, prune=None):
441        """
442        Returns a generator object which visits all nodes in this tree in
443        the BFS (Breadth-first) order.
444
445        Returns:
446            The generator object.
447        """
448        queue = deque([(self, self.parent, None)])
449
450        while queue:
451            item, parent, key = queue.popleft()
452
453            yield item, parent, key
454            if prune and prune(item, parent, key):
455                continue
456
457            for k, v in item.iter_expressions():
458                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):
460    def unnest(self):
461        """
462        Returns the first non parenthesis child or self.
463        """
464        expression = self
465        while type(expression) is Paren:
466            expression = expression.this
467        return expression

Returns the first non parenthesis child or self.

def unalias(self):
469    def unalias(self):
470        """
471        Returns the inner expression if this is an Alias.
472        """
473        if isinstance(self, Alias):
474            return self.this
475        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
477    def unnest_operands(self):
478        """
479        Returns unnested operands as a tuple.
480        """
481        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
483    def flatten(self, unnest=True):
484        """
485        Returns a generator which yields child nodes who's parents are the same class.
486
487        A AND B AND C -> [A, B, C]
488        """
489        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
490            if not type(node) is self.__class__:
491                yield node.unnest() if unnest and not isinstance(node, Subquery) 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:
499    def sql(self, dialect: DialectType = None, **opts) -> str:
500        """
501        Returns SQL string representation of this tree.
502
503        Args:
504            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
505            opts: other `sqlglot.generator.Generator` options.
506
507        Returns:
508            The SQL string.
509        """
510        from sqlglot.dialects import Dialect
511
512        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):
538    def transform(self, fun, *args, copy=True, **kwargs):
539        """
540        Recursively visits all tree nodes (excluding already transformed ones)
541        and applies the given transformation function to each node.
542
543        Args:
544            fun (function): a function which takes a node as an argument and returns a
545                new transformed node or the same node without modifications. If the function
546                returns None, then the corresponding node will be removed from the syntax tree.
547            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
548                modified in place.
549
550        Returns:
551            The transformed tree.
552        """
553        node = self.copy() if copy else self
554        new_node = fun(node, *args, **kwargs)
555
556        if new_node is None or not isinstance(new_node, Expression):
557            return new_node
558        if new_node is not node:
559            new_node.parent = node.parent
560            return new_node
561
562        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
563        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):
573    def replace(self, expression):
574        """
575        Swap out this expression with a new expression.
576
577        For example::
578
579            >>> tree = Select().select("x").from_("tbl")
580            >>> tree.find(Column).replace(Column(this="y"))
581            (COLUMN this: y)
582            >>> tree.sql()
583            'SELECT y FROM tbl'
584
585        Args:
586            expression: new node
587
588        Returns:
589            The new expression or expressions.
590        """
591        if not self.parent:
592            return expression
593
594        parent = self.parent
595        self.parent = None
596
597        replace_children(parent, lambda child: expression if child is self else child)
598        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:
600    def pop(self: E) -> E:
601        """
602        Remove this expression from its AST.
603
604        Returns:
605            The popped expression.
606        """
607        self.replace(None)
608        return self

Remove this expression from its AST.

Returns:

The popped expression.

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

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
669    @classmethod
670    def load(cls, obj):
671        """
672        Load a dict (as returned by `Expression.dump`) into an Expression instance.
673        """
674        from sqlglot.serde import load
675
676        return load(obj)

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

def and_( self, *expressions: Union[str, Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
678    def and_(
679        self,
680        *expressions: t.Optional[ExpOrStr],
681        dialect: DialectType = None,
682        copy: bool = True,
683        **opts,
684    ) -> Condition:
685        """
686        AND this condition with one or multiple expressions.
687
688        Example:
689            >>> condition("x=1").and_("y=1").sql()
690            'x = 1 AND y = 1'
691
692        Args:
693            *expressions: the SQL code strings to parse.
694                If an `Expression` instance is passed, it will be used as-is.
695            dialect: the dialect used to parse the input expression.
696            copy: whether or not to copy the involved expressions (only applies to Expressions).
697            opts: other options to use to parse the input expressions.
698
699        Returns:
700            The new And condition.
701        """
702        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, Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
704    def or_(
705        self,
706        *expressions: t.Optional[ExpOrStr],
707        dialect: DialectType = None,
708        copy: bool = True,
709        **opts,
710    ) -> Condition:
711        """
712        OR this condition with one or multiple expressions.
713
714        Example:
715            >>> condition("x=1").or_("y=1").sql()
716            'x = 1 OR y = 1'
717
718        Args:
719            *expressions: the SQL code strings to parse.
720                If an `Expression` instance is passed, it will be used as-is.
721            dialect: the dialect used to parse the input expression.
722            copy: whether or not to copy the involved expressions (only applies to Expressions).
723            opts: other options to use to parse the input expressions.
724
725        Returns:
726            The new Or condition.
727        """
728        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):
730    def not_(self, copy: bool = True):
731        """
732        Wrap this condition with NOT.
733
734        Example:
735            >>> condition("x=1").not_().sql()
736            'NOT x = 1'
737
738        Args:
739            copy: whether or not to copy this object.
740
741        Returns:
742            The new Not instance.
743        """
744        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 | Identifier, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Alias:
746    def as_(
747        self,
748        alias: str | Identifier,
749        quoted: t.Optional[bool] = None,
750        dialect: DialectType = None,
751        copy: bool = True,
752        **opts,
753    ) -> Alias:
754        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
def isin( self, *expressions: Any, query: Union[str, Expression, NoneType] = None, unnest: Union[str, Expression, NoneType, Collection[Union[str, Expression]]] = None, copy: bool = True, **opts) -> In:
779    def isin(
780        self,
781        *expressions: t.Any,
782        query: t.Optional[ExpOrStr] = None,
783        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
784        copy: bool = True,
785        **opts,
786    ) -> In:
787        return In(
788            this=maybe_copy(self, copy),
789            expressions=[convert(e, copy=copy) for e in expressions],
790            query=maybe_parse(query, copy=copy, **opts) if query else None,
791            unnest=Unnest(
792                expressions=[
793                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
794                ]
795            )
796            if unnest
797            else None,
798        )
def between( self, low: Any, high: Any, copy: bool = True, **opts) -> Between:
800    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
801        return Between(
802            this=maybe_copy(self, copy),
803            low=convert(low, copy=copy, **opts),
804            high=convert(high, copy=copy, **opts),
805        )
def is_( self, other: Union[str, Expression]) -> Is:
807    def is_(self, other: ExpOrStr) -> Is:
808        return self._binop(Is, other)
def like( self, other: Union[str, Expression]) -> Like:
810    def like(self, other: ExpOrStr) -> Like:
811        return self._binop(Like, other)
def ilike( self, other: Union[str, Expression]) -> ILike:
813    def ilike(self, other: ExpOrStr) -> ILike:
814        return self._binop(ILike, other)
def eq(self, other: Any) -> EQ:
816    def eq(self, other: t.Any) -> EQ:
817        return self._binop(EQ, other)
def neq(self, other: Any) -> NEQ:
819    def neq(self, other: t.Any) -> NEQ:
820        return self._binop(NEQ, other)
def rlike( self, other: Union[str, Expression]) -> RegexpLike:
822    def rlike(self, other: ExpOrStr) -> RegexpLike:
823        return self._binop(RegexpLike, other)
IntoType = typing.Union[str, typing.Type[Expression], typing.Collection[typing.Union[str, typing.Type[Expression]]]]
ExpOrStr = typing.Union[str, Expression]
class Condition(Expression):
906class Condition(Expression):
907    """Logical conditions like x AND y, or simply x"""

Logical conditions like x AND y, or simply x

key = 'condition'
class Predicate(Condition):
910class Predicate(Condition):
911    """Relationships like x = y, x > 1, x >= y."""

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

key = 'predicate'
class DerivedTable(Expression):
914class DerivedTable(Expression):
915    @property
916    def selects(self) -> t.List[Expression]:
917        return self.this.selects if isinstance(self.this, Subqueryable) else []
918
919    @property
920    def named_selects(self) -> t.List[str]:
921        return [select.output_name for select in self.selects]
selects: List[Expression]
named_selects: List[str]
key = 'derivedtable'
class Unionable(Expression):
924class Unionable(Expression):
925    def union(
926        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
927    ) -> Unionable:
928        """
929        Builds a UNION expression.
930
931        Example:
932            >>> import sqlglot
933            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
934            'SELECT * FROM foo UNION SELECT * FROM bla'
935
936        Args:
937            expression: the SQL code string.
938                If an `Expression` instance is passed, it will be used as-is.
939            distinct: set the DISTINCT flag if and only if this is true.
940            dialect: the dialect used to parse the input expression.
941            opts: other options to use to parse the input expressions.
942
943        Returns:
944            The new Union expression.
945        """
946        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
947
948    def intersect(
949        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
950    ) -> Unionable:
951        """
952        Builds an INTERSECT expression.
953
954        Example:
955            >>> import sqlglot
956            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
957            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
958
959        Args:
960            expression: the SQL code string.
961                If an `Expression` instance is passed, it will be used as-is.
962            distinct: set the DISTINCT flag if and only if this is true.
963            dialect: the dialect used to parse the input expression.
964            opts: other options to use to parse the input expressions.
965
966        Returns:
967            The new Intersect expression.
968        """
969        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
970
971    def except_(
972        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
973    ) -> Unionable:
974        """
975        Builds an EXCEPT expression.
976
977        Example:
978            >>> import sqlglot
979            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
980            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
981
982        Args:
983            expression: the SQL code string.
984                If an `Expression` instance is passed, it will be used as-is.
985            distinct: set the DISTINCT flag if and only if this is true.
986            dialect: the dialect used to parse the input expression.
987            opts: other options to use to parse the input expressions.
988
989        Returns:
990            The new Except expression.
991        """
992        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union( self, expression: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Unionable:
925    def union(
926        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
927    ) -> Unionable:
928        """
929        Builds a UNION expression.
930
931        Example:
932            >>> import sqlglot
933            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
934            'SELECT * FROM foo UNION SELECT * FROM bla'
935
936        Args:
937            expression: the SQL code string.
938                If an `Expression` instance is passed, it will be used as-is.
939            distinct: set the DISTINCT flag if and only if this is true.
940            dialect: the dialect used to parse the input expression.
941            opts: other options to use to parse the input expressions.
942
943        Returns:
944            The new Union expression.
945        """
946        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, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Unionable:
948    def intersect(
949        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
950    ) -> Unionable:
951        """
952        Builds an INTERSECT expression.
953
954        Example:
955            >>> import sqlglot
956            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
957            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
958
959        Args:
960            expression: the SQL code string.
961                If an `Expression` instance is passed, it will be used as-is.
962            distinct: set the DISTINCT flag if and only if this is true.
963            dialect: the dialect used to parse the input expression.
964            opts: other options to use to parse the input expressions.
965
966        Returns:
967            The new Intersect expression.
968        """
969        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, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Unionable:
971    def except_(
972        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
973    ) -> Unionable:
974        """
975        Builds an EXCEPT expression.
976
977        Example:
978            >>> import sqlglot
979            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
980            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
981
982        Args:
983            expression: the SQL code string.
984                If an `Expression` instance is passed, it will be used as-is.
985            distinct: set the DISTINCT flag if and only if this is true.
986            dialect: the dialect used to parse the input expression.
987            opts: other options to use to parse the input expressions.
988
989        Returns:
990            The new Except expression.
991        """
992        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):
995class UDTF(DerivedTable, Unionable):
996    @property
997    def selects(self) -> t.List[Expression]:
998        alias = self.args.get("alias")
999        return alias.columns if alias else []
selects: List[Expression]
key = 'udtf'
class Cache(Expression):
1002class Cache(Expression):
1003    arg_types = {
1004        "with": False,
1005        "this": True,
1006        "lazy": False,
1007        "options": False,
1008        "expression": False,
1009    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
1012class Uncache(Expression):
1013    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class DDL(Expression):
1016class DDL(Expression):
1017    @property
1018    def ctes(self):
1019        with_ = self.args.get("with")
1020        if not with_:
1021            return []
1022        return with_.expressions
1023
1024    @property
1025    def named_selects(self) -> t.List[str]:
1026        if isinstance(self.expression, Subqueryable):
1027            return self.expression.named_selects
1028        return []
1029
1030    @property
1031    def selects(self) -> t.List[Expression]:
1032        if isinstance(self.expression, Subqueryable):
1033            return self.expression.selects
1034        return []
ctes
named_selects: List[str]
selects: List[Expression]
key = 'ddl'
class Create(DDL):
1037class Create(DDL):
1038    arg_types = {
1039        "with": False,
1040        "this": True,
1041        "kind": True,
1042        "expression": False,
1043        "exists": False,
1044        "properties": False,
1045        "replace": False,
1046        "unique": False,
1047        "indexes": False,
1048        "no_schema_binding": False,
1049        "begin": False,
1050        "end": False,
1051        "clone": False,
1052    }
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, 'end': False, 'clone': False}
key = 'create'
class Clone(Expression):
1058class Clone(Expression):
1059    arg_types = {
1060        "this": True,
1061        "when": False,
1062        "kind": False,
1063        "shallow": False,
1064        "expression": False,
1065        "copy": False,
1066    }
arg_types = {'this': True, 'when': False, 'kind': False, 'shallow': False, 'expression': False, 'copy': False}
key = 'clone'
class Describe(Expression):
1069class Describe(Expression):
1070    arg_types = {"this": True, "kind": False, "expressions": False}
arg_types = {'this': True, 'kind': False, 'expressions': False}
key = 'describe'
class Kill(Expression):
1073class Kill(Expression):
1074    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'kill'
class Pragma(Expression):
1077class Pragma(Expression):
1078    pass
key = 'pragma'
class Set(Expression):
1081class Set(Expression):
1082    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1085class SetItem(Expression):
1086    arg_types = {
1087        "this": False,
1088        "expressions": False,
1089        "kind": False,
1090        "collate": False,  # MySQL SET NAMES statement
1091        "global": False,
1092    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1095class Show(Expression):
1096    arg_types = {
1097        "this": True,
1098        "target": False,
1099        "offset": False,
1100        "limit": False,
1101        "like": False,
1102        "where": False,
1103        "db": False,
1104        "scope": False,
1105        "scope_kind": False,
1106        "full": False,
1107        "mutex": False,
1108        "query": False,
1109        "channel": False,
1110        "global": False,
1111        "log": False,
1112        "position": False,
1113        "types": False,
1114    }
arg_types = {'this': True, 'target': False, 'offset': False, 'limit': False, 'like': False, 'where': False, 'db': False, 'scope': False, 'scope_kind': False, 'full': False, 'mutex': False, 'query': False, 'channel': False, 'global': False, 'log': False, 'position': False, 'types': False}
key = 'show'
class UserDefinedFunction(Expression):
1117class UserDefinedFunction(Expression):
1118    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1121class CharacterSet(Expression):
1122    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1125class With(Expression):
1126    arg_types = {"expressions": True, "recursive": False}
1127
1128    @property
1129    def recursive(self) -> bool:
1130        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1133class WithinGroup(Expression):
1134    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1137class CTE(DerivedTable):
1138    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1141class TableAlias(Expression):
1142    arg_types = {"this": False, "columns": False}
1143
1144    @property
1145    def columns(self):
1146        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1149class BitString(Condition):
1150    pass
key = 'bitstring'
class HexString(Condition):
1153class HexString(Condition):
1154    pass
key = 'hexstring'
class ByteString(Condition):
1157class ByteString(Condition):
1158    pass
key = 'bytestring'
class RawString(Condition):
1161class RawString(Condition):
1162    pass
key = 'rawstring'
class Column(Condition):
1165class Column(Condition):
1166    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1167
1168    @property
1169    def table(self) -> str:
1170        return self.text("table")
1171
1172    @property
1173    def db(self) -> str:
1174        return self.text("db")
1175
1176    @property
1177    def catalog(self) -> str:
1178        return self.text("catalog")
1179
1180    @property
1181    def output_name(self) -> str:
1182        return self.name
1183
1184    @property
1185    def parts(self) -> t.List[Identifier]:
1186        """Return the parts of a column in order catalog, db, table, name."""
1187        return [
1188            t.cast(Identifier, self.args[part])
1189            for part in ("catalog", "db", "table", "this")
1190            if self.args.get(part)
1191        ]
1192
1193    def to_dot(self) -> Dot | Identifier:
1194        """Converts the column into a dot expression."""
1195        parts = self.parts
1196        parent = self.parent
1197
1198        while parent:
1199            if isinstance(parent, Dot):
1200                parts.append(parent.expression)
1201            parent = parent.parent
1202
1203        return Dot.build(deepcopy(parts)) if len(parts) > 1 else parts[0]
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")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
parts: List[Identifier]

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

def to_dot(self) -> Dot | Identifier:
1193    def to_dot(self) -> Dot | Identifier:
1194        """Converts the column into a dot expression."""
1195        parts = self.parts
1196        parent = self.parent
1197
1198        while parent:
1199            if isinstance(parent, Dot):
1200                parts.append(parent.expression)
1201            parent = parent.parent
1202
1203        return Dot.build(deepcopy(parts)) if len(parts) > 1 else parts[0]

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1206class ColumnPosition(Expression):
1207    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1210class ColumnDef(Expression):
1211    arg_types = {
1212        "this": True,
1213        "kind": False,
1214        "constraints": False,
1215        "exists": False,
1216        "position": False,
1217    }
1218
1219    @property
1220    def constraints(self) -> t.List[ColumnConstraint]:
1221        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
constraints: List[ColumnConstraint]
key = 'columndef'
class AlterColumn(Expression):
1224class AlterColumn(Expression):
1225    arg_types = {
1226        "this": True,
1227        "dtype": False,
1228        "collate": False,
1229        "using": False,
1230        "default": False,
1231        "drop": False,
1232    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1235class RenameTable(Expression):
1236    pass
key = 'renametable'
class SwapTable(Expression):
1239class SwapTable(Expression):
1240    pass
key = 'swaptable'
class Comment(Expression):
1243class Comment(Expression):
1244    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
arg_types = {'this': True, 'kind': True, 'expression': True, 'exists': False}
key = 'comment'
class Comprehension(Expression):
1247class Comprehension(Expression):
1248    arg_types = {"this": True, "expression": True, "iterator": True, "condition": False}
arg_types = {'this': True, 'expression': True, 'iterator': True, 'condition': False}
key = 'comprehension'
class MergeTreeTTLAction(Expression):
1252class MergeTreeTTLAction(Expression):
1253    arg_types = {
1254        "this": True,
1255        "delete": False,
1256        "recompress": False,
1257        "to_disk": False,
1258        "to_volume": False,
1259    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1263class MergeTreeTTL(Expression):
1264    arg_types = {
1265        "expressions": True,
1266        "where": False,
1267        "group": False,
1268        "aggregates": False,
1269    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class IndexConstraintOption(Expression):
1273class IndexConstraintOption(Expression):
1274    arg_types = {
1275        "key_block_size": False,
1276        "using": False,
1277        "parser": False,
1278        "comment": False,
1279        "visible": False,
1280        "engine_attr": False,
1281        "secondary_engine_attr": False,
1282    }
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):
1285class ColumnConstraint(Expression):
1286    arg_types = {"this": False, "kind": True}
1287
1288    @property
1289    def kind(self) -> ColumnConstraintKind:
1290        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1293class ColumnConstraintKind(Expression):
1294    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1297class AutoIncrementColumnConstraint(ColumnConstraintKind):
1298    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1301class CaseSpecificColumnConstraint(ColumnConstraintKind):
1302    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1305class CharacterSetColumnConstraint(ColumnConstraintKind):
1306    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1309class CheckColumnConstraint(ColumnConstraintKind):
1310    pass
key = 'checkcolumnconstraint'
class ClusteredColumnConstraint(ColumnConstraintKind):
1313class ClusteredColumnConstraint(ColumnConstraintKind):
1314    pass
key = 'clusteredcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1317class CollateColumnConstraint(ColumnConstraintKind):
1318    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1321class CommentColumnConstraint(ColumnConstraintKind):
1322    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1325class CompressColumnConstraint(ColumnConstraintKind):
1326    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1329class DateFormatColumnConstraint(ColumnConstraintKind):
1330    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1333class DefaultColumnConstraint(ColumnConstraintKind):
1334    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1337class EncodeColumnConstraint(ColumnConstraintKind):
1338    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1341class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1342    # this: True -> ALWAYS, this: False -> BY DEFAULT
1343    arg_types = {
1344        "this": False,
1345        "expression": False,
1346        "on_null": False,
1347        "start": False,
1348        "increment": False,
1349        "minvalue": False,
1350        "maxvalue": False,
1351        "cycle": False,
1352    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class IndexColumnConstraint(ColumnConstraintKind):
1356class IndexColumnConstraint(ColumnConstraintKind):
1357    arg_types = {
1358        "this": False,
1359        "schema": True,
1360        "kind": False,
1361        "index_type": False,
1362        "options": False,
1363    }
arg_types = {'this': False, 'schema': True, 'kind': False, 'index_type': False, 'options': False}
key = 'indexcolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1366class InlineLengthColumnConstraint(ColumnConstraintKind):
1367    pass
key = 'inlinelengthcolumnconstraint'
class NonClusteredColumnConstraint(ColumnConstraintKind):
1370class NonClusteredColumnConstraint(ColumnConstraintKind):
1371    pass
key = 'nonclusteredcolumnconstraint'
class NotForReplicationColumnConstraint(ColumnConstraintKind):
1374class NotForReplicationColumnConstraint(ColumnConstraintKind):
1375    arg_types = {}
arg_types = {}
key = 'notforreplicationcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1378class NotNullColumnConstraint(ColumnConstraintKind):
1379    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1383class OnUpdateColumnConstraint(ColumnConstraintKind):
1384    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1387class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1388    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1391class TitleColumnConstraint(ColumnConstraintKind):
1392    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1395class UniqueColumnConstraint(ColumnConstraintKind):
1396    arg_types = {"this": False, "index_type": False}
arg_types = {'this': False, 'index_type': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1399class UppercaseColumnConstraint(ColumnConstraintKind):
1400    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1403class PathColumnConstraint(ColumnConstraintKind):
1404    pass
key = 'pathcolumnconstraint'
class ComputedColumnConstraint(ColumnConstraintKind):
1409class ComputedColumnConstraint(ColumnConstraintKind):
1410    arg_types = {"this": True, "persisted": False, "not_null": False}
arg_types = {'this': True, 'persisted': False, 'not_null': False}
key = 'computedcolumnconstraint'
class Constraint(Expression):
1413class Constraint(Expression):
1414    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1417class Delete(Expression):
1418    arg_types = {
1419        "with": False,
1420        "this": False,
1421        "using": False,
1422        "where": False,
1423        "returning": False,
1424        "limit": False,
1425        "tables": False,  # Multiple-Table Syntax (MySQL)
1426    }
1427
1428    def delete(
1429        self,
1430        table: ExpOrStr,
1431        dialect: DialectType = None,
1432        copy: bool = True,
1433        **opts,
1434    ) -> Delete:
1435        """
1436        Create a DELETE expression or replace the table on an existing DELETE expression.
1437
1438        Example:
1439            >>> delete("tbl").sql()
1440            'DELETE FROM tbl'
1441
1442        Args:
1443            table: the table from which to delete.
1444            dialect: the dialect used to parse the input expression.
1445            copy: if `False`, modify this expression instance in-place.
1446            opts: other options to use to parse the input expressions.
1447
1448        Returns:
1449            Delete: the modified expression.
1450        """
1451        return _apply_builder(
1452            expression=table,
1453            instance=self,
1454            arg="this",
1455            dialect=dialect,
1456            into=Table,
1457            copy=copy,
1458            **opts,
1459        )
1460
1461    def where(
1462        self,
1463        *expressions: t.Optional[ExpOrStr],
1464        append: bool = True,
1465        dialect: DialectType = None,
1466        copy: bool = True,
1467        **opts,
1468    ) -> Delete:
1469        """
1470        Append to or set the WHERE expressions.
1471
1472        Example:
1473            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1474            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1475
1476        Args:
1477            *expressions: the SQL code strings to parse.
1478                If an `Expression` instance is passed, it will be used as-is.
1479                Multiple expressions are combined with an AND operator.
1480            append: if `True`, AND the new expressions to any existing expression.
1481                Otherwise, this resets the expression.
1482            dialect: the dialect used to parse the input expressions.
1483            copy: if `False`, modify this expression instance in-place.
1484            opts: other options to use to parse the input expressions.
1485
1486        Returns:
1487            Delete: the modified expression.
1488        """
1489        return _apply_conjunction_builder(
1490            *expressions,
1491            instance=self,
1492            arg="where",
1493            append=append,
1494            into=Where,
1495            dialect=dialect,
1496            copy=copy,
1497            **opts,
1498        )
1499
1500    def returning(
1501        self,
1502        expression: ExpOrStr,
1503        dialect: DialectType = None,
1504        copy: bool = True,
1505        **opts,
1506    ) -> Delete:
1507        """
1508        Set the RETURNING expression. Not supported by all dialects.
1509
1510        Example:
1511            >>> delete("tbl").returning("*", dialect="postgres").sql()
1512            'DELETE FROM tbl RETURNING *'
1513
1514        Args:
1515            expression: the SQL code strings to parse.
1516                If an `Expression` instance is passed, it will be used as-is.
1517            dialect: the dialect used to parse the input expressions.
1518            copy: if `False`, modify this expression instance in-place.
1519            opts: other options to use to parse the input expressions.
1520
1521        Returns:
1522            Delete: the modified expression.
1523        """
1524        return _apply_builder(
1525            expression=expression,
1526            instance=self,
1527            arg="returning",
1528            prefix="RETURNING",
1529            dialect=dialect,
1530            copy=copy,
1531            into=Returning,
1532            **opts,
1533        )
arg_types = {'with': False, 'this': False, 'using': False, 'where': False, 'returning': False, 'limit': False, 'tables': False}
def delete( self, table: Union[str, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Delete:
1428    def delete(
1429        self,
1430        table: ExpOrStr,
1431        dialect: DialectType = None,
1432        copy: bool = True,
1433        **opts,
1434    ) -> Delete:
1435        """
1436        Create a DELETE expression or replace the table on an existing DELETE expression.
1437
1438        Example:
1439            >>> delete("tbl").sql()
1440            'DELETE FROM tbl'
1441
1442        Args:
1443            table: the table from which to delete.
1444            dialect: the dialect used to parse the input expression.
1445            copy: if `False`, modify this expression instance in-place.
1446            opts: other options to use to parse the input expressions.
1447
1448        Returns:
1449            Delete: the modified expression.
1450        """
1451        return _apply_builder(
1452            expression=table,
1453            instance=self,
1454            arg="this",
1455            dialect=dialect,
1456            into=Table,
1457            copy=copy,
1458            **opts,
1459        )

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, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Delete:
1461    def where(
1462        self,
1463        *expressions: t.Optional[ExpOrStr],
1464        append: bool = True,
1465        dialect: DialectType = None,
1466        copy: bool = True,
1467        **opts,
1468    ) -> Delete:
1469        """
1470        Append to or set the WHERE expressions.
1471
1472        Example:
1473            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1474            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1475
1476        Args:
1477            *expressions: the SQL code strings to parse.
1478                If an `Expression` instance is passed, it will be used as-is.
1479                Multiple expressions are combined with an AND operator.
1480            append: if `True`, AND the new expressions to any existing expression.
1481                Otherwise, this resets the expression.
1482            dialect: the dialect used to parse the input expressions.
1483            copy: if `False`, modify this expression instance in-place.
1484            opts: other options to use to parse the input expressions.
1485
1486        Returns:
1487            Delete: the modified expression.
1488        """
1489        return _apply_conjunction_builder(
1490            *expressions,
1491            instance=self,
1492            arg="where",
1493            append=append,
1494            into=Where,
1495            dialect=dialect,
1496            copy=copy,
1497            **opts,
1498        )

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, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Delete:
1500    def returning(
1501        self,
1502        expression: ExpOrStr,
1503        dialect: DialectType = None,
1504        copy: bool = True,
1505        **opts,
1506    ) -> Delete:
1507        """
1508        Set the RETURNING expression. Not supported by all dialects.
1509
1510        Example:
1511            >>> delete("tbl").returning("*", dialect="postgres").sql()
1512            'DELETE FROM tbl RETURNING *'
1513
1514        Args:
1515            expression: the SQL code strings to parse.
1516                If an `Expression` instance is passed, it will be used as-is.
1517            dialect: the dialect used to parse the input expressions.
1518            copy: if `False`, modify this expression instance in-place.
1519            opts: other options to use to parse the input expressions.
1520
1521        Returns:
1522            Delete: the modified expression.
1523        """
1524        return _apply_builder(
1525            expression=expression,
1526            instance=self,
1527            arg="returning",
1528            prefix="RETURNING",
1529            dialect=dialect,
1530            copy=copy,
1531            into=Returning,
1532            **opts,
1533        )

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):
1536class Drop(Expression):
1537    arg_types = {
1538        "this": False,
1539        "kind": False,
1540        "exists": False,
1541        "temporary": False,
1542        "materialized": False,
1543        "cascade": False,
1544        "constraints": False,
1545        "purge": False,
1546    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1549class Filter(Expression):
1550    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1553class Check(Expression):
1554    pass
key = 'check'
class Connect(Expression):
1558class Connect(Expression):
1559    arg_types = {"start": False, "connect": True}
arg_types = {'start': False, 'connect': True}
key = 'connect'
class Prior(Expression):
1562class Prior(Expression):
1563    pass
key = 'prior'
class Directory(Expression):
1566class Directory(Expression):
1567    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1568    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1571class ForeignKey(Expression):
1572    arg_types = {
1573        "expressions": True,
1574        "reference": False,
1575        "delete": False,
1576        "update": False,
1577    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class ColumnPrefix(Expression):
1580class ColumnPrefix(Expression):
1581    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'columnprefix'
class PrimaryKey(Expression):
1584class PrimaryKey(Expression):
1585    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1590class Into(Expression):
1591    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1594class From(Expression):
1595    @property
1596    def name(self) -> str:
1597        return self.this.name
1598
1599    @property
1600    def alias_or_name(self) -> str:
1601        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1604class Having(Expression):
1605    pass
key = 'having'
class Hint(Expression):
1608class Hint(Expression):
1609    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1612class JoinHint(Expression):
1613    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1616class Identifier(Expression):
1617    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1618
1619    @property
1620    def quoted(self) -> bool:
1621        return bool(self.args.get("quoted"))
1622
1623    @property
1624    def hashable_args(self) -> t.Any:
1625        return (self.this, self.quoted)
1626
1627    @property
1628    def output_name(self) -> str:
1629        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")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'identifier'
class Opclass(Expression):
1633class Opclass(Expression):
1634    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'opclass'
class Index(Expression):
1637class Index(Expression):
1638    arg_types = {
1639        "this": False,
1640        "table": False,
1641        "using": False,
1642        "where": False,
1643        "columns": False,
1644        "unique": False,
1645        "primary": False,
1646        "amp": False,  # teradata
1647        "partition_by": False,  # teradata
1648        "where": False,  # postgres partial indexes
1649    }
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):
1652class Insert(DDL):
1653    arg_types = {
1654        "with": False,
1655        "this": True,
1656        "expression": False,
1657        "conflict": False,
1658        "returning": False,
1659        "overwrite": False,
1660        "exists": False,
1661        "partition": False,
1662        "alternative": False,
1663        "where": False,
1664        "ignore": False,
1665        "by_name": False,
1666    }
1667
1668    def with_(
1669        self,
1670        alias: ExpOrStr,
1671        as_: ExpOrStr,
1672        recursive: t.Optional[bool] = None,
1673        append: bool = True,
1674        dialect: DialectType = None,
1675        copy: bool = True,
1676        **opts,
1677    ) -> Insert:
1678        """
1679        Append to or set the common table expressions.
1680
1681        Example:
1682            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1683            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1684
1685        Args:
1686            alias: the SQL code string to parse as the table name.
1687                If an `Expression` instance is passed, this is used as-is.
1688            as_: the SQL code string to parse as the table expression.
1689                If an `Expression` instance is passed, it will be used as-is.
1690            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1691            append: if `True`, add to any existing expressions.
1692                Otherwise, this resets the expressions.
1693            dialect: the dialect used to parse the input expression.
1694            copy: if `False`, modify this expression instance in-place.
1695            opts: other options to use to parse the input expressions.
1696
1697        Returns:
1698            The modified expression.
1699        """
1700        return _apply_cte_builder(
1701            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1702        )
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, Expression], as_: Union[str, 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) -> Insert:
1668    def with_(
1669        self,
1670        alias: ExpOrStr,
1671        as_: ExpOrStr,
1672        recursive: t.Optional[bool] = None,
1673        append: bool = True,
1674        dialect: DialectType = None,
1675        copy: bool = True,
1676        **opts,
1677    ) -> Insert:
1678        """
1679        Append to or set the common table expressions.
1680
1681        Example:
1682            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1683            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1684
1685        Args:
1686            alias: the SQL code string to parse as the table name.
1687                If an `Expression` instance is passed, this is used as-is.
1688            as_: the SQL code string to parse as the table expression.
1689                If an `Expression` instance is passed, it will be used as-is.
1690            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1691            append: if `True`, add to any existing expressions.
1692                Otherwise, this resets the expressions.
1693            dialect: the dialect used to parse the input expression.
1694            copy: if `False`, modify this expression instance in-place.
1695            opts: other options to use to parse the input expressions.
1696
1697        Returns:
1698            The modified expression.
1699        """
1700        return _apply_cte_builder(
1701            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1702        )

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):
1705class OnConflict(Expression):
1706    arg_types = {
1707        "duplicate": False,
1708        "expressions": False,
1709        "nothing": False,
1710        "key": False,
1711        "constraint": False,
1712    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1715class Returning(Expression):
1716    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1720class Introducer(Expression):
1721    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1725class National(Expression):
1726    pass
key = 'national'
class LoadData(Expression):
1729class LoadData(Expression):
1730    arg_types = {
1731        "this": True,
1732        "local": False,
1733        "overwrite": False,
1734        "inpath": True,
1735        "partition": False,
1736        "input_format": False,
1737        "serde": False,
1738    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1741class Partition(Expression):
1742    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1745class Fetch(Expression):
1746    arg_types = {
1747        "direction": False,
1748        "count": False,
1749        "percent": False,
1750        "with_ties": False,
1751    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1754class Group(Expression):
1755    arg_types = {
1756        "expressions": False,
1757        "grouping_sets": False,
1758        "cube": False,
1759        "rollup": False,
1760        "totals": False,
1761        "all": False,
1762    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1765class Lambda(Expression):
1766    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1769class Limit(Expression):
1770    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1773class Literal(Condition):
1774    arg_types = {"this": True, "is_string": True}
1775
1776    @property
1777    def hashable_args(self) -> t.Any:
1778        return (self.this, self.args.get("is_string"))
1779
1780    @classmethod
1781    def number(cls, number) -> Literal:
1782        return cls(this=str(number), is_string=False)
1783
1784    @classmethod
1785    def string(cls, string) -> Literal:
1786        return cls(this=str(string), is_string=True)
1787
1788    @property
1789    def output_name(self) -> str:
1790        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> Literal:
1780    @classmethod
1781    def number(cls, number) -> Literal:
1782        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> Literal:
1784    @classmethod
1785    def string(cls, string) -> Literal:
1786        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")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'literal'
class Join(Expression):
1793class Join(Expression):
1794    arg_types = {
1795        "this": True,
1796        "on": False,
1797        "side": False,
1798        "kind": False,
1799        "using": False,
1800        "method": False,
1801        "global": False,
1802        "hint": False,
1803    }
1804
1805    @property
1806    def method(self) -> str:
1807        return self.text("method").upper()
1808
1809    @property
1810    def kind(self) -> str:
1811        return self.text("kind").upper()
1812
1813    @property
1814    def side(self) -> str:
1815        return self.text("side").upper()
1816
1817    @property
1818    def hint(self) -> str:
1819        return self.text("hint").upper()
1820
1821    @property
1822    def alias_or_name(self) -> str:
1823        return self.this.alias_or_name
1824
1825    def on(
1826        self,
1827        *expressions: t.Optional[ExpOrStr],
1828        append: bool = True,
1829        dialect: DialectType = None,
1830        copy: bool = True,
1831        **opts,
1832    ) -> Join:
1833        """
1834        Append to or set the ON expressions.
1835
1836        Example:
1837            >>> import sqlglot
1838            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1839            'JOIN x ON y = 1'
1840
1841        Args:
1842            *expressions: the SQL code strings to parse.
1843                If an `Expression` instance is passed, it will be used as-is.
1844                Multiple expressions are combined with an AND operator.
1845            append: if `True`, AND the new expressions to any existing expression.
1846                Otherwise, this resets the expression.
1847            dialect: the dialect used to parse the input expressions.
1848            copy: if `False`, modify this expression instance in-place.
1849            opts: other options to use to parse the input expressions.
1850
1851        Returns:
1852            The modified Join expression.
1853        """
1854        join = _apply_conjunction_builder(
1855            *expressions,
1856            instance=self,
1857            arg="on",
1858            append=append,
1859            dialect=dialect,
1860            copy=copy,
1861            **opts,
1862        )
1863
1864        if join.kind == "CROSS":
1865            join.set("kind", None)
1866
1867        return join
1868
1869    def using(
1870        self,
1871        *expressions: t.Optional[ExpOrStr],
1872        append: bool = True,
1873        dialect: DialectType = None,
1874        copy: bool = True,
1875        **opts,
1876    ) -> Join:
1877        """
1878        Append to or set the USING expressions.
1879
1880        Example:
1881            >>> import sqlglot
1882            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1883            'JOIN x USING (foo, bla)'
1884
1885        Args:
1886            *expressions: the SQL code strings to parse.
1887                If an `Expression` instance is passed, it will be used as-is.
1888            append: if `True`, concatenate the new expressions to the existing "using" list.
1889                Otherwise, this resets the expression.
1890            dialect: the dialect used to parse the input expressions.
1891            copy: if `False`, modify this expression instance in-place.
1892            opts: other options to use to parse the input expressions.
1893
1894        Returns:
1895            The modified Join expression.
1896        """
1897        join = _apply_list_builder(
1898            *expressions,
1899            instance=self,
1900            arg="using",
1901            append=append,
1902            dialect=dialect,
1903            copy=copy,
1904            **opts,
1905        )
1906
1907        if join.kind == "CROSS":
1908            join.set("kind", None)
1909
1910        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, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Join:
1825    def on(
1826        self,
1827        *expressions: t.Optional[ExpOrStr],
1828        append: bool = True,
1829        dialect: DialectType = None,
1830        copy: bool = True,
1831        **opts,
1832    ) -> Join:
1833        """
1834        Append to or set the ON expressions.
1835
1836        Example:
1837            >>> import sqlglot
1838            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1839            'JOIN x ON y = 1'
1840
1841        Args:
1842            *expressions: the SQL code strings to parse.
1843                If an `Expression` instance is passed, it will be used as-is.
1844                Multiple expressions are combined with an AND operator.
1845            append: if `True`, AND the new expressions to any existing expression.
1846                Otherwise, this resets the expression.
1847            dialect: the dialect used to parse the input expressions.
1848            copy: if `False`, modify this expression instance in-place.
1849            opts: other options to use to parse the input expressions.
1850
1851        Returns:
1852            The modified Join expression.
1853        """
1854        join = _apply_conjunction_builder(
1855            *expressions,
1856            instance=self,
1857            arg="on",
1858            append=append,
1859            dialect=dialect,
1860            copy=copy,
1861            **opts,
1862        )
1863
1864        if join.kind == "CROSS":
1865            join.set("kind", None)
1866
1867        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, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Join:
1869    def using(
1870        self,
1871        *expressions: t.Optional[ExpOrStr],
1872        append: bool = True,
1873        dialect: DialectType = None,
1874        copy: bool = True,
1875        **opts,
1876    ) -> Join:
1877        """
1878        Append to or set the USING expressions.
1879
1880        Example:
1881            >>> import sqlglot
1882            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1883            'JOIN x USING (foo, bla)'
1884
1885        Args:
1886            *expressions: the SQL code strings to parse.
1887                If an `Expression` instance is passed, it will be used as-is.
1888            append: if `True`, concatenate the new expressions to the existing "using" list.
1889                Otherwise, this resets the expression.
1890            dialect: the dialect used to parse the input expressions.
1891            copy: if `False`, modify this expression instance in-place.
1892            opts: other options to use to parse the input expressions.
1893
1894        Returns:
1895            The modified Join expression.
1896        """
1897        join = _apply_list_builder(
1898            *expressions,
1899            instance=self,
1900            arg="using",
1901            append=append,
1902            dialect=dialect,
1903            copy=copy,
1904            **opts,
1905        )
1906
1907        if join.kind == "CROSS":
1908            join.set("kind", None)
1909
1910        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):
1913class Lateral(UDTF):
1914    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):
1917class MatchRecognize(Expression):
1918    arg_types = {
1919        "partition_by": False,
1920        "order": False,
1921        "measures": False,
1922        "rows": False,
1923        "after": False,
1924        "pattern": False,
1925        "define": False,
1926        "alias": False,
1927    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1932class Final(Expression):
1933    pass
key = 'final'
class Offset(Expression):
1936class Offset(Expression):
1937    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1940class Order(Expression):
1941    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1946class Cluster(Order):
1947    pass
key = 'cluster'
class Distribute(Order):
1950class Distribute(Order):
1951    pass
key = 'distribute'
class Sort(Order):
1954class Sort(Order):
1955    pass
key = 'sort'
class Ordered(Expression):
1958class Ordered(Expression):
1959    arg_types = {"this": True, "desc": False, "nulls_first": True}
arg_types = {'this': True, 'desc': False, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1962class Property(Expression):
1963    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1966class AlgorithmProperty(Property):
1967    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1970class AutoIncrementProperty(Property):
1971    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1974class BlockCompressionProperty(Property):
1975    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):
1978class CharacterSetProperty(Property):
1979    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1982class ChecksumProperty(Property):
1983    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1986class CollateProperty(Property):
1987    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1990class CopyGrantsProperty(Property):
1991    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1994class DataBlocksizeProperty(Property):
1995    arg_types = {
1996        "size": False,
1997        "units": False,
1998        "minimum": False,
1999        "maximum": False,
2000        "default": False,
2001    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
2004class DefinerProperty(Property):
2005    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
2008class DistKeyProperty(Property):
2009    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
2012class DistStyleProperty(Property):
2013    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
2016class EngineProperty(Property):
2017    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
2020class HeapProperty(Property):
2021    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
2024class ToTableProperty(Property):
2025    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
2028class ExecuteAsProperty(Property):
2029    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
2032class ExternalProperty(Property):
2033    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
2036class FallbackProperty(Property):
2037    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
2040class FileFormatProperty(Property):
2041    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
2044class FreespaceProperty(Property):
2045    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputModelProperty(Property):
2048class InputModelProperty(Property):
2049    arg_types = {"this": True}
arg_types = {'this': True}
key = 'inputmodelproperty'
class OutputModelProperty(Property):
2052class OutputModelProperty(Property):
2053    arg_types = {"this": True}
arg_types = {'this': True}
key = 'outputmodelproperty'
class IsolatedLoadingProperty(Property):
2056class IsolatedLoadingProperty(Property):
2057    arg_types = {
2058        "no": True,
2059        "concurrent": True,
2060        "for_all": True,
2061        "for_insert": True,
2062        "for_none": True,
2063    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
2066class JournalProperty(Property):
2067    arg_types = {
2068        "no": False,
2069        "dual": False,
2070        "before": False,
2071        "local": False,
2072        "after": False,
2073    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
2076class LanguageProperty(Property):
2077    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
2081class ClusteredByProperty(Property):
2082    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
2085class DictProperty(Property):
2086    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2089class DictSubProperty(Property):
2090    pass
key = 'dictsubproperty'
class DictRange(Property):
2093class DictRange(Property):
2094    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2099class OnCluster(Property):
2100    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2103class LikeProperty(Property):
2104    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2107class LocationProperty(Property):
2108    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2111class LockingProperty(Property):
2112    arg_types = {
2113        "this": False,
2114        "kind": True,
2115        "for_or_in": False,
2116        "lock_type": True,
2117        "override": False,
2118    }
arg_types = {'this': False, 'kind': True, 'for_or_in': False, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2121class LogProperty(Property):
2122    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2125class MaterializedProperty(Property):
2126    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2129class MergeBlockRatioProperty(Property):
2130    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):
2133class NoPrimaryIndexProperty(Property):
2134    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnProperty(Property):
2137class OnProperty(Property):
2138    arg_types = {"this": True}
arg_types = {'this': True}
key = 'onproperty'
class OnCommitProperty(Property):
2141class OnCommitProperty(Property):
2142    arg_types = {"delete": False}
arg_types = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2145class PartitionedByProperty(Property):
2146    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class RemoteWithConnectionModelProperty(Property):
2149class RemoteWithConnectionModelProperty(Property):
2150    arg_types = {"this": True}
arg_types = {'this': True}
key = 'remotewithconnectionmodelproperty'
class ReturnsProperty(Property):
2153class ReturnsProperty(Property):
2154    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2157class RowFormatProperty(Property):
2158    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2161class RowFormatDelimitedProperty(Property):
2162    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2163    arg_types = {
2164        "fields": False,
2165        "escaped": False,
2166        "collection_items": False,
2167        "map_keys": False,
2168        "lines": False,
2169        "null": False,
2170        "serde": False,
2171    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2174class RowFormatSerdeProperty(Property):
2175    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2179class QueryTransform(Expression):
2180    arg_types = {
2181        "expressions": True,
2182        "command_script": True,
2183        "schema": False,
2184        "row_format_before": False,
2185        "record_writer": False,
2186        "row_format_after": False,
2187        "record_reader": False,
2188    }
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 SampleProperty(Property):
2191class SampleProperty(Property):
2192    arg_types = {"this": True}
arg_types = {'this': True}
key = 'sampleproperty'
class SchemaCommentProperty(Property):
2195class SchemaCommentProperty(Property):
2196    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2199class SerdeProperties(Property):
2200    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2203class SetProperty(Property):
2204    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2207class SettingsProperty(Property):
2208    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2211class SortKeyProperty(Property):
2212    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2215class SqlSecurityProperty(Property):
2216    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2219class StabilityProperty(Property):
2220    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2223class TemporaryProperty(Property):
2224    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransformModelProperty(Property):
2227class TransformModelProperty(Property):
2228    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'transformmodelproperty'
class TransientProperty(Property):
2231class TransientProperty(Property):
2232    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2235class VolatileProperty(Property):
2236    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2239class WithDataProperty(Property):
2240    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2243class WithJournalTableProperty(Property):
2244    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2247class Properties(Expression):
2248    arg_types = {"expressions": True}
2249
2250    NAME_TO_PROPERTY = {
2251        "ALGORITHM": AlgorithmProperty,
2252        "AUTO_INCREMENT": AutoIncrementProperty,
2253        "CHARACTER SET": CharacterSetProperty,
2254        "CLUSTERED_BY": ClusteredByProperty,
2255        "COLLATE": CollateProperty,
2256        "COMMENT": SchemaCommentProperty,
2257        "DEFINER": DefinerProperty,
2258        "DISTKEY": DistKeyProperty,
2259        "DISTSTYLE": DistStyleProperty,
2260        "ENGINE": EngineProperty,
2261        "EXECUTE AS": ExecuteAsProperty,
2262        "FORMAT": FileFormatProperty,
2263        "LANGUAGE": LanguageProperty,
2264        "LOCATION": LocationProperty,
2265        "PARTITIONED_BY": PartitionedByProperty,
2266        "RETURNS": ReturnsProperty,
2267        "ROW_FORMAT": RowFormatProperty,
2268        "SORTKEY": SortKeyProperty,
2269    }
2270
2271    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2272
2273    # CREATE property locations
2274    # Form: schema specified
2275    #   create [POST_CREATE]
2276    #     table a [POST_NAME]
2277    #     (b int) [POST_SCHEMA]
2278    #     with ([POST_WITH])
2279    #     index (b) [POST_INDEX]
2280    #
2281    # Form: alias selection
2282    #   create [POST_CREATE]
2283    #     table a [POST_NAME]
2284    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2285    #     index (c) [POST_INDEX]
2286    class Location(AutoName):
2287        POST_CREATE = auto()
2288        POST_NAME = auto()
2289        POST_SCHEMA = auto()
2290        POST_WITH = auto()
2291        POST_ALIAS = auto()
2292        POST_EXPRESSION = auto()
2293        POST_INDEX = auto()
2294        UNSUPPORTED = auto()
2295
2296    @classmethod
2297    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2298        expressions = []
2299        for key, value in properties_dict.items():
2300            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2301            if property_cls:
2302                expressions.append(property_cls(this=convert(value)))
2303            else:
2304                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2305
2306        return cls(expressions=expressions)
arg_types = {'expressions': True}
NAME_TO_PROPERTY = {'ALGORITHM': <class 'AlgorithmProperty'>, 'AUTO_INCREMENT': <class 'AutoIncrementProperty'>, 'CHARACTER SET': <class 'CharacterSetProperty'>, 'CLUSTERED_BY': <class 'ClusteredByProperty'>, 'COLLATE': <class 'CollateProperty'>, 'COMMENT': <class 'SchemaCommentProperty'>, 'DEFINER': <class 'DefinerProperty'>, 'DISTKEY': <class 'DistKeyProperty'>, 'DISTSTYLE': <class 'DistStyleProperty'>, 'ENGINE': <class 'EngineProperty'>, 'EXECUTE AS': <class 'ExecuteAsProperty'>, 'FORMAT': <class 'FileFormatProperty'>, 'LANGUAGE': <class 'LanguageProperty'>, 'LOCATION': <class 'LocationProperty'>, 'PARTITIONED_BY': <class 'PartitionedByProperty'>, 'RETURNS': <class 'ReturnsProperty'>, 'ROW_FORMAT': <class 'RowFormatProperty'>, 'SORTKEY': <class 'SortKeyProperty'>}
PROPERTY_TO_NAME = {<class 'AlgorithmProperty'>: 'ALGORITHM', <class 'AutoIncrementProperty'>: 'AUTO_INCREMENT', <class 'CharacterSetProperty'>: 'CHARACTER SET', <class 'ClusteredByProperty'>: 'CLUSTERED_BY', <class 'CollateProperty'>: 'COLLATE', <class 'SchemaCommentProperty'>: 'COMMENT', <class 'DefinerProperty'>: 'DEFINER', <class 'DistKeyProperty'>: 'DISTKEY', <class 'DistStyleProperty'>: 'DISTSTYLE', <class 'EngineProperty'>: 'ENGINE', <class 'ExecuteAsProperty'>: 'EXECUTE AS', <class 'FileFormatProperty'>: 'FORMAT', <class 'LanguageProperty'>: 'LANGUAGE', <class 'LocationProperty'>: 'LOCATION', <class 'PartitionedByProperty'>: 'PARTITIONED_BY', <class 'ReturnsProperty'>: 'RETURNS', <class 'RowFormatProperty'>: 'ROW_FORMAT', <class 'SortKeyProperty'>: 'SORTKEY'}
@classmethod
def from_dict(cls, properties_dict: Dict) -> Properties:
2296    @classmethod
2297    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2298        expressions = []
2299        for key, value in properties_dict.items():
2300            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2301            if property_cls:
2302                expressions.append(property_cls(this=convert(value)))
2303            else:
2304                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2305
2306        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2286    class Location(AutoName):
2287        POST_CREATE = auto()
2288        POST_NAME = auto()
2289        POST_SCHEMA = auto()
2290        POST_WITH = auto()
2291        POST_ALIAS = auto()
2292        POST_EXPRESSION = auto()
2293        POST_INDEX = auto()
2294        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):
2309class Qualify(Expression):
2310    pass
key = 'qualify'
class InputOutputFormat(Expression):
2313class InputOutputFormat(Expression):
2314    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class Return(Expression):
2318class Return(Expression):
2319    pass
key = 'return'
class Reference(Expression):
2322class Reference(Expression):
2323    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2326class Tuple(Expression):
2327    arg_types = {"expressions": False}
2328
2329    def isin(
2330        self,
2331        *expressions: t.Any,
2332        query: t.Optional[ExpOrStr] = None,
2333        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2334        copy: bool = True,
2335        **opts,
2336    ) -> In:
2337        return In(
2338            this=maybe_copy(self, copy),
2339            expressions=[convert(e, copy=copy) for e in expressions],
2340            query=maybe_parse(query, copy=copy, **opts) if query else None,
2341            unnest=Unnest(
2342                expressions=[
2343                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2344                ]
2345            )
2346            if unnest
2347            else None,
2348        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, Expression, NoneType] = None, unnest: Union[str, Expression, NoneType, Collection[Union[str, Expression]]] = None, copy: bool = True, **opts) -> In:
2329    def isin(
2330        self,
2331        *expressions: t.Any,
2332        query: t.Optional[ExpOrStr] = None,
2333        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2334        copy: bool = True,
2335        **opts,
2336    ) -> In:
2337        return In(
2338            this=maybe_copy(self, copy),
2339            expressions=[convert(e, copy=copy) for e in expressions],
2340            query=maybe_parse(query, copy=copy, **opts) if query else None,
2341            unnest=Unnest(
2342                expressions=[
2343                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2344                ]
2345            )
2346            if unnest
2347            else None,
2348        )
key = 'tuple'
class Subqueryable(Unionable):
2351class Subqueryable(Unionable):
2352    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2353        """
2354        Convert this expression to an aliased expression that can be used as a Subquery.
2355
2356        Example:
2357            >>> subquery = Select().select("x").from_("tbl").subquery()
2358            >>> Select().select("x").from_(subquery).sql()
2359            'SELECT x FROM (SELECT x FROM tbl)'
2360
2361        Args:
2362            alias (str | Identifier): an optional alias for the subquery
2363            copy (bool): if `False`, modify this expression instance in-place.
2364
2365        Returns:
2366            Alias: the subquery
2367        """
2368        instance = maybe_copy(self, copy)
2369        if not isinstance(alias, Expression):
2370            alias = TableAlias(this=to_identifier(alias)) if alias else None
2371
2372        return Subquery(this=instance, alias=alias)
2373
2374    def limit(
2375        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2376    ) -> Select:
2377        raise NotImplementedError
2378
2379    @property
2380    def ctes(self):
2381        with_ = self.args.get("with")
2382        if not with_:
2383            return []
2384        return with_.expressions
2385
2386    @property
2387    def selects(self) -> t.List[Expression]:
2388        raise NotImplementedError("Subqueryable objects must implement `selects`")
2389
2390    @property
2391    def named_selects(self) -> t.List[str]:
2392        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2393
2394    def select(
2395        self,
2396        *expressions: t.Optional[ExpOrStr],
2397        append: bool = True,
2398        dialect: DialectType = None,
2399        copy: bool = True,
2400        **opts,
2401    ) -> Subqueryable:
2402        raise NotImplementedError("Subqueryable objects must implement `select`")
2403
2404    def with_(
2405        self,
2406        alias: ExpOrStr,
2407        as_: ExpOrStr,
2408        recursive: t.Optional[bool] = None,
2409        append: bool = True,
2410        dialect: DialectType = None,
2411        copy: bool = True,
2412        **opts,
2413    ) -> Subqueryable:
2414        """
2415        Append to or set the common table expressions.
2416
2417        Example:
2418            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2419            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2420
2421        Args:
2422            alias: the SQL code string to parse as the table name.
2423                If an `Expression` instance is passed, this is used as-is.
2424            as_: the SQL code string to parse as the table expression.
2425                If an `Expression` instance is passed, it will be used as-is.
2426            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2427            append: if `True`, add to any existing expressions.
2428                Otherwise, this resets the expressions.
2429            dialect: the dialect used to parse the input expression.
2430            copy: if `False`, modify this expression instance in-place.
2431            opts: other options to use to parse the input expressions.
2432
2433        Returns:
2434            The modified expression.
2435        """
2436        return _apply_cte_builder(
2437            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2438        )
def subquery( self, alias: Union[str, Expression, NoneType] = None, copy: bool = True) -> Subquery:
2352    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2353        """
2354        Convert this expression to an aliased expression that can be used as a Subquery.
2355
2356        Example:
2357            >>> subquery = Select().select("x").from_("tbl").subquery()
2358            >>> Select().select("x").from_(subquery).sql()
2359            'SELECT x FROM (SELECT x FROM tbl)'
2360
2361        Args:
2362            alias (str | Identifier): an optional alias for the subquery
2363            copy (bool): if `False`, modify this expression instance in-place.
2364
2365        Returns:
2366            Alias: the subquery
2367        """
2368        instance = maybe_copy(self, copy)
2369        if not isinstance(alias, Expression):
2370            alias = TableAlias(this=to_identifier(alias)) if alias else None
2371
2372        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, Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2374    def limit(
2375        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2376    ) -> Select:
2377        raise NotImplementedError
ctes
selects: List[Expression]
named_selects: List[str]
def select( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Subqueryable:
2394    def select(
2395        self,
2396        *expressions: t.Optional[ExpOrStr],
2397        append: bool = True,
2398        dialect: DialectType = None,
2399        copy: bool = True,
2400        **opts,
2401    ) -> Subqueryable:
2402        raise NotImplementedError("Subqueryable objects must implement `select`")
def with_( self, alias: Union[str, Expression], as_: Union[str, 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) -> Subqueryable:
2404    def with_(
2405        self,
2406        alias: ExpOrStr,
2407        as_: ExpOrStr,
2408        recursive: t.Optional[bool] = None,
2409        append: bool = True,
2410        dialect: DialectType = None,
2411        copy: bool = True,
2412        **opts,
2413    ) -> Subqueryable:
2414        """
2415        Append to or set the common table expressions.
2416
2417        Example:
2418            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2419            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2420
2421        Args:
2422            alias: the SQL code string to parse as the table name.
2423                If an `Expression` instance is passed, this is used as-is.
2424            as_: the SQL code string to parse as the table expression.
2425                If an `Expression` instance is passed, it will be used as-is.
2426            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2427            append: if `True`, add to any existing expressions.
2428                Otherwise, this resets the expressions.
2429            dialect: the dialect used to parse the input expression.
2430            copy: if `False`, modify this expression instance in-place.
2431            opts: other options to use to parse the input expressions.
2432
2433        Returns:
2434            The modified expression.
2435        """
2436        return _apply_cte_builder(
2437            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2438        )

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):
2466class WithTableHint(Expression):
2467    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2471class IndexTableHint(Expression):
2472    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2475class Table(Expression):
2476    arg_types = {
2477        "this": True,
2478        "alias": False,
2479        "db": False,
2480        "catalog": False,
2481        "laterals": False,
2482        "joins": False,
2483        "pivots": False,
2484        "hints": False,
2485        "system_time": False,
2486        "version": False,
2487        "format": False,
2488        "pattern": False,
2489        "index": False,
2490    }
2491
2492    @property
2493    def name(self) -> str:
2494        if isinstance(self.this, Func):
2495            return ""
2496        return self.this.name
2497
2498    @property
2499    def db(self) -> str:
2500        return self.text("db")
2501
2502    @property
2503    def catalog(self) -> str:
2504        return self.text("catalog")
2505
2506    @property
2507    def selects(self) -> t.List[Expression]:
2508        return []
2509
2510    @property
2511    def named_selects(self) -> t.List[str]:
2512        return []
2513
2514    @property
2515    def parts(self) -> t.List[Expression]:
2516        """Return the parts of a table in order catalog, db, table."""
2517        parts: t.List[Expression] = []
2518
2519        for arg in ("catalog", "db", "this"):
2520            part = self.args.get(arg)
2521
2522            if isinstance(part, Dot):
2523                parts.extend(part.flatten())
2524            elif isinstance(part, Expression):
2525                parts.append(part)
2526
2527        return parts
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False, 'version': False, 'format': False, 'pattern': False, 'index': False}
name: str
db: str
catalog: str
selects: List[Expression]
named_selects: List[str]
parts: List[Expression]

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

key = 'table'
class Union(Subqueryable):
2530class Union(Subqueryable):
2531    arg_types = {
2532        "with": False,
2533        "this": True,
2534        "expression": True,
2535        "distinct": False,
2536        "by_name": False,
2537        **QUERY_MODIFIERS,
2538    }
2539
2540    def limit(
2541        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2542    ) -> Select:
2543        """
2544        Set the LIMIT expression.
2545
2546        Example:
2547            >>> select("1").union(select("1")).limit(1).sql()
2548            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2549
2550        Args:
2551            expression: the SQL code string to parse.
2552                This can also be an integer.
2553                If a `Limit` instance is passed, this is used as-is.
2554                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2555            dialect: the dialect used to parse the input expression.
2556            copy: if `False`, modify this expression instance in-place.
2557            opts: other options to use to parse the input expressions.
2558
2559        Returns:
2560            The limited subqueryable.
2561        """
2562        return (
2563            select("*")
2564            .from_(self.subquery(alias="_l_0", copy=copy))
2565            .limit(expression, dialect=dialect, copy=False, **opts)
2566        )
2567
2568    def select(
2569        self,
2570        *expressions: t.Optional[ExpOrStr],
2571        append: bool = True,
2572        dialect: DialectType = None,
2573        copy: bool = True,
2574        **opts,
2575    ) -> Union:
2576        """Append to or set the SELECT of the union recursively.
2577
2578        Example:
2579            >>> from sqlglot import parse_one
2580            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2581            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2582
2583        Args:
2584            *expressions: the SQL code strings to parse.
2585                If an `Expression` instance is passed, it will be used as-is.
2586            append: if `True`, add to any existing expressions.
2587                Otherwise, this resets the expressions.
2588            dialect: the dialect used to parse the input expressions.
2589            copy: if `False`, modify this expression instance in-place.
2590            opts: other options to use to parse the input expressions.
2591
2592        Returns:
2593            Union: the modified expression.
2594        """
2595        this = self.copy() if copy else self
2596        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2597        this.expression.unnest().select(
2598            *expressions, append=append, dialect=dialect, copy=False, **opts
2599        )
2600        return this
2601
2602    @property
2603    def named_selects(self) -> t.List[str]:
2604        return self.this.unnest().named_selects
2605
2606    @property
2607    def is_star(self) -> bool:
2608        return self.this.is_star or self.expression.is_star
2609
2610    @property
2611    def selects(self) -> t.List[Expression]:
2612        return self.this.unnest().selects
2613
2614    @property
2615    def left(self) -> Expression:
2616        return self.this
2617
2618    @property
2619    def right(self) -> Expression:
2620        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, Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2540    def limit(
2541        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2542    ) -> Select:
2543        """
2544        Set the LIMIT expression.
2545
2546        Example:
2547            >>> select("1").union(select("1")).limit(1).sql()
2548            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2549
2550        Args:
2551            expression: the SQL code string to parse.
2552                This can also be an integer.
2553                If a `Limit` instance is passed, this is used as-is.
2554                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2555            dialect: the dialect used to parse the input expression.
2556            copy: if `False`, modify this expression instance in-place.
2557            opts: other options to use to parse the input expressions.
2558
2559        Returns:
2560            The limited subqueryable.
2561        """
2562        return (
2563            select("*")
2564            .from_(self.subquery(alias="_l_0", copy=copy))
2565            .limit(expression, dialect=dialect, copy=False, **opts)
2566        )

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, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Union:
2568    def select(
2569        self,
2570        *expressions: t.Optional[ExpOrStr],
2571        append: bool = True,
2572        dialect: DialectType = None,
2573        copy: bool = True,
2574        **opts,
2575    ) -> Union:
2576        """Append to or set the SELECT of the union recursively.
2577
2578        Example:
2579            >>> from sqlglot import parse_one
2580            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2581            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2582
2583        Args:
2584            *expressions: the SQL code strings to parse.
2585                If an `Expression` instance is passed, it will be used as-is.
2586            append: if `True`, add to any existing expressions.
2587                Otherwise, this resets the expressions.
2588            dialect: the dialect used to parse the input expressions.
2589            copy: if `False`, modify this expression instance in-place.
2590            opts: other options to use to parse the input expressions.
2591
2592        Returns:
2593            Union: the modified expression.
2594        """
2595        this = self.copy() if copy else self
2596        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2597        this.expression.unnest().select(
2598            *expressions, append=append, dialect=dialect, copy=False, **opts
2599        )
2600        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.

selects: List[Expression]
left: Expression
right: Expression
key = 'union'
class Except(Union):
2623class Except(Union):
2624    pass
key = 'except'
class Intersect(Union):
2627class Intersect(Union):
2628    pass
key = 'intersect'
class Unnest(UDTF):
2631class Unnest(UDTF):
2632    arg_types = {
2633        "expressions": True,
2634        "alias": False,
2635        "offset": False,
2636    }
arg_types = {'expressions': True, 'alias': False, 'offset': False}
key = 'unnest'
class Update(Expression):
2639class Update(Expression):
2640    arg_types = {
2641        "with": False,
2642        "this": False,
2643        "expressions": True,
2644        "from": False,
2645        "where": False,
2646        "returning": False,
2647        "order": False,
2648        "limit": False,
2649    }
arg_types = {'with': False, 'this': False, 'expressions': True, 'from': False, 'where': False, 'returning': False, 'order': False, 'limit': False}
key = 'update'
class Values(UDTF):
2652class Values(UDTF):
2653    arg_types = {
2654        "expressions": True,
2655        "ordinality": False,
2656        "alias": False,
2657    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False}
key = 'values'
class Var(Expression):
2660class Var(Expression):
2661    pass
key = 'var'
class Version(Expression):
2664class Version(Expression):
2665    """
2666    Time travel, iceberg, bigquery etc
2667    https://trino.io/docs/current/connector/iceberg.html?highlight=snapshot#using-snapshots
2668    https://www.databricks.com/blog/2019/02/04/introducing-delta-time-travel-for-large-scale-data-lakes.html
2669    https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#for_system_time_as_of
2670    https://learn.microsoft.com/en-us/sql/relational-databases/tables/querying-data-in-a-system-versioned-temporal-table?view=sql-server-ver16
2671    this is either TIMESTAMP or VERSION
2672    kind is ("AS OF", "BETWEEN")
2673    """
2674
2675    arg_types = {"this": True, "kind": True, "expression": False}
arg_types = {'this': True, 'kind': True, 'expression': False}
key = 'version'
class Schema(Expression):
2678class Schema(Expression):
2679    arg_types = {"this": False, "expressions": False}
arg_types = {'this': False, 'expressions': False}
key = 'schema'
class Lock(Expression):
2684class Lock(Expression):
2685    arg_types = {"update": True, "expressions": False, "wait": False}
arg_types = {'update': True, 'expressions': False, 'wait': False}
key = 'lock'
class Select(Subqueryable):
2688class Select(Subqueryable):
2689    arg_types = {
2690        "with": False,
2691        "kind": False,
2692        "expressions": False,
2693        "hint": False,
2694        "distinct": False,
2695        "into": False,
2696        "from": False,
2697        **QUERY_MODIFIERS,
2698    }
2699
2700    def from_(
2701        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2702    ) -> Select:
2703        """
2704        Set the FROM expression.
2705
2706        Example:
2707            >>> Select().from_("tbl").select("x").sql()
2708            'SELECT x FROM tbl'
2709
2710        Args:
2711            expression : the SQL code strings to parse.
2712                If a `From` instance is passed, this is used as-is.
2713                If another `Expression` instance is passed, it will be wrapped in a `From`.
2714            dialect: the dialect used to parse the input expression.
2715            copy: if `False`, modify this expression instance in-place.
2716            opts: other options to use to parse the input expressions.
2717
2718        Returns:
2719            The modified Select expression.
2720        """
2721        return _apply_builder(
2722            expression=expression,
2723            instance=self,
2724            arg="from",
2725            into=From,
2726            prefix="FROM",
2727            dialect=dialect,
2728            copy=copy,
2729            **opts,
2730        )
2731
2732    def group_by(
2733        self,
2734        *expressions: t.Optional[ExpOrStr],
2735        append: bool = True,
2736        dialect: DialectType = None,
2737        copy: bool = True,
2738        **opts,
2739    ) -> Select:
2740        """
2741        Set the GROUP BY expression.
2742
2743        Example:
2744            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2745            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2746
2747        Args:
2748            *expressions: the SQL code strings to parse.
2749                If a `Group` instance is passed, this is used as-is.
2750                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2751                If nothing is passed in then a group by is not applied to the expression
2752            append: if `True`, add to any existing expressions.
2753                Otherwise, this flattens all the `Group` expression into a single expression.
2754            dialect: the dialect used to parse the input expression.
2755            copy: if `False`, modify this expression instance in-place.
2756            opts: other options to use to parse the input expressions.
2757
2758        Returns:
2759            The modified Select expression.
2760        """
2761        if not expressions:
2762            return self if not copy else self.copy()
2763
2764        return _apply_child_list_builder(
2765            *expressions,
2766            instance=self,
2767            arg="group",
2768            append=append,
2769            copy=copy,
2770            prefix="GROUP BY",
2771            into=Group,
2772            dialect=dialect,
2773            **opts,
2774        )
2775
2776    def order_by(
2777        self,
2778        *expressions: t.Optional[ExpOrStr],
2779        append: bool = True,
2780        dialect: DialectType = None,
2781        copy: bool = True,
2782        **opts,
2783    ) -> Select:
2784        """
2785        Set the ORDER BY expression.
2786
2787        Example:
2788            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2789            'SELECT x FROM tbl ORDER BY x DESC'
2790
2791        Args:
2792            *expressions: the SQL code strings to parse.
2793                If a `Group` instance is passed, this is used as-is.
2794                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2795            append: if `True`, add to any existing expressions.
2796                Otherwise, this flattens all the `Order` expression into a single expression.
2797            dialect: the dialect used to parse the input expression.
2798            copy: if `False`, modify this expression instance in-place.
2799            opts: other options to use to parse the input expressions.
2800
2801        Returns:
2802            The modified Select expression.
2803        """
2804        return _apply_child_list_builder(
2805            *expressions,
2806            instance=self,
2807            arg="order",
2808            append=append,
2809            copy=copy,
2810            prefix="ORDER BY",
2811            into=Order,
2812            dialect=dialect,
2813            **opts,
2814        )
2815
2816    def sort_by(
2817        self,
2818        *expressions: t.Optional[ExpOrStr],
2819        append: bool = True,
2820        dialect: DialectType = None,
2821        copy: bool = True,
2822        **opts,
2823    ) -> Select:
2824        """
2825        Set the SORT BY expression.
2826
2827        Example:
2828            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2829            'SELECT x FROM tbl SORT BY x DESC'
2830
2831        Args:
2832            *expressions: the SQL code strings to parse.
2833                If a `Group` instance is passed, this is used as-is.
2834                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2835            append: if `True`, add to any existing expressions.
2836                Otherwise, this flattens all the `Order` expression into a single expression.
2837            dialect: the dialect used to parse the input expression.
2838            copy: if `False`, modify this expression instance in-place.
2839            opts: other options to use to parse the input expressions.
2840
2841        Returns:
2842            The modified Select expression.
2843        """
2844        return _apply_child_list_builder(
2845            *expressions,
2846            instance=self,
2847            arg="sort",
2848            append=append,
2849            copy=copy,
2850            prefix="SORT BY",
2851            into=Sort,
2852            dialect=dialect,
2853            **opts,
2854        )
2855
2856    def cluster_by(
2857        self,
2858        *expressions: t.Optional[ExpOrStr],
2859        append: bool = True,
2860        dialect: DialectType = None,
2861        copy: bool = True,
2862        **opts,
2863    ) -> Select:
2864        """
2865        Set the CLUSTER BY expression.
2866
2867        Example:
2868            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2869            'SELECT x FROM tbl CLUSTER BY x DESC'
2870
2871        Args:
2872            *expressions: the SQL code strings to parse.
2873                If a `Group` instance is passed, this is used as-is.
2874                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2875            append: if `True`, add to any existing expressions.
2876                Otherwise, this flattens all the `Order` expression into a single expression.
2877            dialect: the dialect used to parse the input expression.
2878            copy: if `False`, modify this expression instance in-place.
2879            opts: other options to use to parse the input expressions.
2880
2881        Returns:
2882            The modified Select expression.
2883        """
2884        return _apply_child_list_builder(
2885            *expressions,
2886            instance=self,
2887            arg="cluster",
2888            append=append,
2889            copy=copy,
2890            prefix="CLUSTER BY",
2891            into=Cluster,
2892            dialect=dialect,
2893            **opts,
2894        )
2895
2896    def limit(
2897        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2898    ) -> Select:
2899        """
2900        Set the LIMIT expression.
2901
2902        Example:
2903            >>> Select().from_("tbl").select("x").limit(10).sql()
2904            'SELECT x FROM tbl LIMIT 10'
2905
2906        Args:
2907            expression: the SQL code string to parse.
2908                This can also be an integer.
2909                If a `Limit` instance is passed, this is used as-is.
2910                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2911            dialect: the dialect used to parse the input expression.
2912            copy: if `False`, modify this expression instance in-place.
2913            opts: other options to use to parse the input expressions.
2914
2915        Returns:
2916            Select: the modified expression.
2917        """
2918        return _apply_builder(
2919            expression=expression,
2920            instance=self,
2921            arg="limit",
2922            into=Limit,
2923            prefix="LIMIT",
2924            dialect=dialect,
2925            copy=copy,
2926            into_arg="expression",
2927            **opts,
2928        )
2929
2930    def offset(
2931        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2932    ) -> Select:
2933        """
2934        Set the OFFSET expression.
2935
2936        Example:
2937            >>> Select().from_("tbl").select("x").offset(10).sql()
2938            'SELECT x FROM tbl OFFSET 10'
2939
2940        Args:
2941            expression: the SQL code string to parse.
2942                This can also be an integer.
2943                If a `Offset` instance is passed, this is used as-is.
2944                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2945            dialect: the dialect used to parse the input expression.
2946            copy: if `False`, modify this expression instance in-place.
2947            opts: other options to use to parse the input expressions.
2948
2949        Returns:
2950            The modified Select expression.
2951        """
2952        return _apply_builder(
2953            expression=expression,
2954            instance=self,
2955            arg="offset",
2956            into=Offset,
2957            prefix="OFFSET",
2958            dialect=dialect,
2959            copy=copy,
2960            into_arg="expression",
2961            **opts,
2962        )
2963
2964    def select(
2965        self,
2966        *expressions: t.Optional[ExpOrStr],
2967        append: bool = True,
2968        dialect: DialectType = None,
2969        copy: bool = True,
2970        **opts,
2971    ) -> Select:
2972        """
2973        Append to or set the SELECT expressions.
2974
2975        Example:
2976            >>> Select().select("x", "y").sql()
2977            'SELECT x, y'
2978
2979        Args:
2980            *expressions: the SQL code strings to parse.
2981                If an `Expression` instance is passed, it will be used as-is.
2982            append: if `True`, add to any existing expressions.
2983                Otherwise, this resets the expressions.
2984            dialect: the dialect used to parse the input expressions.
2985            copy: if `False`, modify this expression instance in-place.
2986            opts: other options to use to parse the input expressions.
2987
2988        Returns:
2989            The modified Select expression.
2990        """
2991        return _apply_list_builder(
2992            *expressions,
2993            instance=self,
2994            arg="expressions",
2995            append=append,
2996            dialect=dialect,
2997            copy=copy,
2998            **opts,
2999        )
3000
3001    def lateral(
3002        self,
3003        *expressions: t.Optional[ExpOrStr],
3004        append: bool = True,
3005        dialect: DialectType = None,
3006        copy: bool = True,
3007        **opts,
3008    ) -> Select:
3009        """
3010        Append to or set the LATERAL expressions.
3011
3012        Example:
3013            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
3014            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
3015
3016        Args:
3017            *expressions: the SQL code strings to parse.
3018                If an `Expression` instance is passed, it will be used as-is.
3019            append: if `True`, add to any existing expressions.
3020                Otherwise, this resets the expressions.
3021            dialect: the dialect used to parse the input expressions.
3022            copy: if `False`, modify this expression instance in-place.
3023            opts: other options to use to parse the input expressions.
3024
3025        Returns:
3026            The modified Select expression.
3027        """
3028        return _apply_list_builder(
3029            *expressions,
3030            instance=self,
3031            arg="laterals",
3032            append=append,
3033            into=Lateral,
3034            prefix="LATERAL VIEW",
3035            dialect=dialect,
3036            copy=copy,
3037            **opts,
3038        )
3039
3040    def join(
3041        self,
3042        expression: ExpOrStr,
3043        on: t.Optional[ExpOrStr] = None,
3044        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
3045        append: bool = True,
3046        join_type: t.Optional[str] = None,
3047        join_alias: t.Optional[Identifier | str] = None,
3048        dialect: DialectType = None,
3049        copy: bool = True,
3050        **opts,
3051    ) -> Select:
3052        """
3053        Append to or set the JOIN expressions.
3054
3055        Example:
3056            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
3057            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
3058
3059            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
3060            'SELECT 1 FROM a JOIN b USING (x, y, z)'
3061
3062            Use `join_type` to change the type of join:
3063
3064            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
3065            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
3066
3067        Args:
3068            expression: the SQL code string to parse.
3069                If an `Expression` instance is passed, it will be used as-is.
3070            on: optionally specify the join "on" criteria as a SQL string.
3071                If an `Expression` instance is passed, it will be used as-is.
3072            using: optionally specify the join "using" criteria as a SQL string.
3073                If an `Expression` instance is passed, it will be used as-is.
3074            append: if `True`, add to any existing expressions.
3075                Otherwise, this resets the expressions.
3076            join_type: if set, alter the parsed join type.
3077            join_alias: an optional alias for the joined source.
3078            dialect: the dialect used to parse the input expressions.
3079            copy: if `False`, modify this expression instance in-place.
3080            opts: other options to use to parse the input expressions.
3081
3082        Returns:
3083            Select: the modified expression.
3084        """
3085        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
3086
3087        try:
3088            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
3089        except ParseError:
3090            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
3091
3092        join = expression if isinstance(expression, Join) else Join(this=expression)
3093
3094        if isinstance(join.this, Select):
3095            join.this.replace(join.this.subquery())
3096
3097        if join_type:
3098            method: t.Optional[Token]
3099            side: t.Optional[Token]
3100            kind: t.Optional[Token]
3101
3102            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
3103
3104            if method:
3105                join.set("method", method.text)
3106            if side:
3107                join.set("side", side.text)
3108            if kind:
3109                join.set("kind", kind.text)
3110
3111        if on:
3112            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
3113            join.set("on", on)
3114
3115        if using:
3116            join = _apply_list_builder(
3117                *ensure_list(using),
3118                instance=join,
3119                arg="using",
3120                append=append,
3121                copy=copy,
3122                into=Identifier,
3123                **opts,
3124            )
3125
3126        if join_alias:
3127            join.set("this", alias_(join.this, join_alias, table=True))
3128
3129        return _apply_list_builder(
3130            join,
3131            instance=self,
3132            arg="joins",
3133            append=append,
3134            copy=copy,
3135            **opts,
3136        )
3137
3138    def where(
3139        self,
3140        *expressions: t.Optional[ExpOrStr],
3141        append: bool = True,
3142        dialect: DialectType = None,
3143        copy: bool = True,
3144        **opts,
3145    ) -> Select:
3146        """
3147        Append to or set the WHERE expressions.
3148
3149        Example:
3150            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3151            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3152
3153        Args:
3154            *expressions: the SQL code strings to parse.
3155                If an `Expression` instance is passed, it will be used as-is.
3156                Multiple expressions are combined with an AND operator.
3157            append: if `True`, AND the new expressions to any existing expression.
3158                Otherwise, this resets the expression.
3159            dialect: the dialect used to parse the input expressions.
3160            copy: if `False`, modify this expression instance in-place.
3161            opts: other options to use to parse the input expressions.
3162
3163        Returns:
3164            Select: the modified expression.
3165        """
3166        return _apply_conjunction_builder(
3167            *expressions,
3168            instance=self,
3169            arg="where",
3170            append=append,
3171            into=Where,
3172            dialect=dialect,
3173            copy=copy,
3174            **opts,
3175        )
3176
3177    def having(
3178        self,
3179        *expressions: t.Optional[ExpOrStr],
3180        append: bool = True,
3181        dialect: DialectType = None,
3182        copy: bool = True,
3183        **opts,
3184    ) -> Select:
3185        """
3186        Append to or set the HAVING expressions.
3187
3188        Example:
3189            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3190            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3191
3192        Args:
3193            *expressions: the SQL code strings to parse.
3194                If an `Expression` instance is passed, it will be used as-is.
3195                Multiple expressions are combined with an AND operator.
3196            append: if `True`, AND the new expressions to any existing expression.
3197                Otherwise, this resets the expression.
3198            dialect: the dialect used to parse the input expressions.
3199            copy: if `False`, modify this expression instance in-place.
3200            opts: other options to use to parse the input expressions.
3201
3202        Returns:
3203            The modified Select expression.
3204        """
3205        return _apply_conjunction_builder(
3206            *expressions,
3207            instance=self,
3208            arg="having",
3209            append=append,
3210            into=Having,
3211            dialect=dialect,
3212            copy=copy,
3213            **opts,
3214        )
3215
3216    def window(
3217        self,
3218        *expressions: t.Optional[ExpOrStr],
3219        append: bool = True,
3220        dialect: DialectType = None,
3221        copy: bool = True,
3222        **opts,
3223    ) -> Select:
3224        return _apply_list_builder(
3225            *expressions,
3226            instance=self,
3227            arg="windows",
3228            append=append,
3229            into=Window,
3230            dialect=dialect,
3231            copy=copy,
3232            **opts,
3233        )
3234
3235    def qualify(
3236        self,
3237        *expressions: t.Optional[ExpOrStr],
3238        append: bool = True,
3239        dialect: DialectType = None,
3240        copy: bool = True,
3241        **opts,
3242    ) -> Select:
3243        return _apply_conjunction_builder(
3244            *expressions,
3245            instance=self,
3246            arg="qualify",
3247            append=append,
3248            into=Qualify,
3249            dialect=dialect,
3250            copy=copy,
3251            **opts,
3252        )
3253
3254    def distinct(
3255        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3256    ) -> Select:
3257        """
3258        Set the OFFSET expression.
3259
3260        Example:
3261            >>> Select().from_("tbl").select("x").distinct().sql()
3262            'SELECT DISTINCT x FROM tbl'
3263
3264        Args:
3265            ons: the expressions to distinct on
3266            distinct: whether the Select should be distinct
3267            copy: if `False`, modify this expression instance in-place.
3268
3269        Returns:
3270            Select: the modified expression.
3271        """
3272        instance = maybe_copy(self, copy)
3273        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3274        instance.set("distinct", Distinct(on=on) if distinct else None)
3275        return instance
3276
3277    def ctas(
3278        self,
3279        table: ExpOrStr,
3280        properties: t.Optional[t.Dict] = None,
3281        dialect: DialectType = None,
3282        copy: bool = True,
3283        **opts,
3284    ) -> Create:
3285        """
3286        Convert this expression to a CREATE TABLE AS statement.
3287
3288        Example:
3289            >>> Select().select("*").from_("tbl").ctas("x").sql()
3290            'CREATE TABLE x AS SELECT * FROM tbl'
3291
3292        Args:
3293            table: the SQL code string to parse as the table name.
3294                If another `Expression` instance is passed, it will be used as-is.
3295            properties: an optional mapping of table properties
3296            dialect: the dialect used to parse the input table.
3297            copy: if `False`, modify this expression instance in-place.
3298            opts: other options to use to parse the input table.
3299
3300        Returns:
3301            The new Create expression.
3302        """
3303        instance = maybe_copy(self, copy)
3304        table_expression = maybe_parse(
3305            table,
3306            into=Table,
3307            dialect=dialect,
3308            **opts,
3309        )
3310        properties_expression = None
3311        if properties:
3312            properties_expression = Properties.from_dict(properties)
3313
3314        return Create(
3315            this=table_expression,
3316            kind="table",
3317            expression=instance,
3318            properties=properties_expression,
3319        )
3320
3321    def lock(self, update: bool = True, copy: bool = True) -> Select:
3322        """
3323        Set the locking read mode for this expression.
3324
3325        Examples:
3326            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3327            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3328
3329            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3330            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3331
3332        Args:
3333            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3334            copy: if `False`, modify this expression instance in-place.
3335
3336        Returns:
3337            The modified expression.
3338        """
3339        inst = maybe_copy(self, copy)
3340        inst.set("locks", [Lock(update=update)])
3341
3342        return inst
3343
3344    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3345        """
3346        Set hints for this expression.
3347
3348        Examples:
3349            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3350            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3351
3352        Args:
3353            hints: The SQL code strings to parse as the hints.
3354                If an `Expression` instance is passed, it will be used as-is.
3355            dialect: The dialect used to parse the hints.
3356            copy: If `False`, modify this expression instance in-place.
3357
3358        Returns:
3359            The modified expression.
3360        """
3361        inst = maybe_copy(self, copy)
3362        inst.set(
3363            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3364        )
3365
3366        return inst
3367
3368    @property
3369    def named_selects(self) -> t.List[str]:
3370        return [e.output_name for e in self.expressions if e.alias_or_name]
3371
3372    @property
3373    def is_star(self) -> bool:
3374        return any(expression.is_star for expression in self.expressions)
3375
3376    @property
3377    def selects(self) -> t.List[Expression]:
3378        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, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2700    def from_(
2701        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2702    ) -> Select:
2703        """
2704        Set the FROM expression.
2705
2706        Example:
2707            >>> Select().from_("tbl").select("x").sql()
2708            'SELECT x FROM tbl'
2709
2710        Args:
2711            expression : the SQL code strings to parse.
2712                If a `From` instance is passed, this is used as-is.
2713                If another `Expression` instance is passed, it will be wrapped in a `From`.
2714            dialect: the dialect used to parse the input expression.
2715            copy: if `False`, modify this expression instance in-place.
2716            opts: other options to use to parse the input expressions.
2717
2718        Returns:
2719            The modified Select expression.
2720        """
2721        return _apply_builder(
2722            expression=expression,
2723            instance=self,
2724            arg="from",
2725            into=From,
2726            prefix="FROM",
2727            dialect=dialect,
2728            copy=copy,
2729            **opts,
2730        )

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

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

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, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2816    def sort_by(
2817        self,
2818        *expressions: t.Optional[ExpOrStr],
2819        append: bool = True,
2820        dialect: DialectType = None,
2821        copy: bool = True,
2822        **opts,
2823    ) -> Select:
2824        """
2825        Set the SORT BY expression.
2826
2827        Example:
2828            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2829            'SELECT x FROM tbl SORT BY x DESC'
2830
2831        Args:
2832            *expressions: the SQL code strings to parse.
2833                If a `Group` instance is passed, this is used as-is.
2834                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2835            append: if `True`, add to any existing expressions.
2836                Otherwise, this flattens all the `Order` expression into a single expression.
2837            dialect: the dialect used to parse the input expression.
2838            copy: if `False`, modify this expression instance in-place.
2839            opts: other options to use to parse the input expressions.
2840
2841        Returns:
2842            The modified Select expression.
2843        """
2844        return _apply_child_list_builder(
2845            *expressions,
2846            instance=self,
2847            arg="sort",
2848            append=append,
2849            copy=copy,
2850            prefix="SORT BY",
2851            into=Sort,
2852            dialect=dialect,
2853            **opts,
2854        )

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, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2856    def cluster_by(
2857        self,
2858        *expressions: t.Optional[ExpOrStr],
2859        append: bool = True,
2860        dialect: DialectType = None,
2861        copy: bool = True,
2862        **opts,
2863    ) -> Select:
2864        """
2865        Set the CLUSTER BY expression.
2866
2867        Example:
2868            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2869            'SELECT x FROM tbl CLUSTER BY x DESC'
2870
2871        Args:
2872            *expressions: the SQL code strings to parse.
2873                If a `Group` instance is passed, this is used as-is.
2874                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2875            append: if `True`, add to any existing expressions.
2876                Otherwise, this flattens all the `Order` expression into a single expression.
2877            dialect: the dialect used to parse the input expression.
2878            copy: if `False`, modify this expression instance in-place.
2879            opts: other options to use to parse the input expressions.
2880
2881        Returns:
2882            The modified Select expression.
2883        """
2884        return _apply_child_list_builder(
2885            *expressions,
2886            instance=self,
2887            arg="cluster",
2888            append=append,
2889            copy=copy,
2890            prefix="CLUSTER BY",
2891            into=Cluster,
2892            dialect=dialect,
2893            **opts,
2894        )

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, Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2896    def limit(
2897        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2898    ) -> Select:
2899        """
2900        Set the LIMIT expression.
2901
2902        Example:
2903            >>> Select().from_("tbl").select("x").limit(10).sql()
2904            'SELECT x FROM tbl LIMIT 10'
2905
2906        Args:
2907            expression: the SQL code string to parse.
2908                This can also be an integer.
2909                If a `Limit` instance is passed, this is used as-is.
2910                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2911            dialect: the dialect used to parse the input expression.
2912            copy: if `False`, modify this expression instance in-place.
2913            opts: other options to use to parse the input expressions.
2914
2915        Returns:
2916            Select: the modified expression.
2917        """
2918        return _apply_builder(
2919            expression=expression,
2920            instance=self,
2921            arg="limit",
2922            into=Limit,
2923            prefix="LIMIT",
2924            dialect=dialect,
2925            copy=copy,
2926            into_arg="expression",
2927            **opts,
2928        )

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, Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2930    def offset(
2931        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2932    ) -> Select:
2933        """
2934        Set the OFFSET expression.
2935
2936        Example:
2937            >>> Select().from_("tbl").select("x").offset(10).sql()
2938            'SELECT x FROM tbl OFFSET 10'
2939
2940        Args:
2941            expression: the SQL code string to parse.
2942                This can also be an integer.
2943                If a `Offset` instance is passed, this is used as-is.
2944                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2945            dialect: the dialect used to parse the input expression.
2946            copy: if `False`, modify this expression instance in-place.
2947            opts: other options to use to parse the input expressions.
2948
2949        Returns:
2950            The modified Select expression.
2951        """
2952        return _apply_builder(
2953            expression=expression,
2954            instance=self,
2955            arg="offset",
2956            into=Offset,
2957            prefix="OFFSET",
2958            dialect=dialect,
2959            copy=copy,
2960            into_arg="expression",
2961            **opts,
2962        )

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, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
2964    def select(
2965        self,
2966        *expressions: t.Optional[ExpOrStr],
2967        append: bool = True,
2968        dialect: DialectType = None,
2969        copy: bool = True,
2970        **opts,
2971    ) -> Select:
2972        """
2973        Append to or set the SELECT expressions.
2974
2975        Example:
2976            >>> Select().select("x", "y").sql()
2977            'SELECT x, y'
2978
2979        Args:
2980            *expressions: the SQL code strings to parse.
2981                If an `Expression` instance is passed, it will be used as-is.
2982            append: if `True`, add to any existing expressions.
2983                Otherwise, this resets the expressions.
2984            dialect: the dialect used to parse the input expressions.
2985            copy: if `False`, modify this expression instance in-place.
2986            opts: other options to use to parse the input expressions.
2987
2988        Returns:
2989            The modified Select expression.
2990        """
2991        return _apply_list_builder(
2992            *expressions,
2993            instance=self,
2994            arg="expressions",
2995            append=append,
2996            dialect=dialect,
2997            copy=copy,
2998            **opts,
2999        )

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, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3001    def lateral(
3002        self,
3003        *expressions: t.Optional[ExpOrStr],
3004        append: bool = True,
3005        dialect: DialectType = None,
3006        copy: bool = True,
3007        **opts,
3008    ) -> Select:
3009        """
3010        Append to or set the LATERAL expressions.
3011
3012        Example:
3013            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
3014            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
3015
3016        Args:
3017            *expressions: the SQL code strings to parse.
3018                If an `Expression` instance is passed, it will be used as-is.
3019            append: if `True`, add to any existing expressions.
3020                Otherwise, this resets the expressions.
3021            dialect: the dialect used to parse the input expressions.
3022            copy: if `False`, modify this expression instance in-place.
3023            opts: other options to use to parse the input expressions.
3024
3025        Returns:
3026            The modified Select expression.
3027        """
3028        return _apply_list_builder(
3029            *expressions,
3030            instance=self,
3031            arg="laterals",
3032            append=append,
3033            into=Lateral,
3034            prefix="LATERAL VIEW",
3035            dialect=dialect,
3036            copy=copy,
3037            **opts,
3038        )

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, Expression], on: Union[str, Expression, NoneType] = None, using: Union[str, Expression, Collection[Union[str, Expression]], NoneType] = None, append: bool = True, join_type: Optional[str] = None, join_alias: Union[Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3040    def join(
3041        self,
3042        expression: ExpOrStr,
3043        on: t.Optional[ExpOrStr] = None,
3044        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
3045        append: bool = True,
3046        join_type: t.Optional[str] = None,
3047        join_alias: t.Optional[Identifier | str] = None,
3048        dialect: DialectType = None,
3049        copy: bool = True,
3050        **opts,
3051    ) -> Select:
3052        """
3053        Append to or set the JOIN expressions.
3054
3055        Example:
3056            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
3057            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
3058
3059            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
3060            'SELECT 1 FROM a JOIN b USING (x, y, z)'
3061
3062            Use `join_type` to change the type of join:
3063
3064            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
3065            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
3066
3067        Args:
3068            expression: the SQL code string to parse.
3069                If an `Expression` instance is passed, it will be used as-is.
3070            on: optionally specify the join "on" criteria as a SQL string.
3071                If an `Expression` instance is passed, it will be used as-is.
3072            using: optionally specify the join "using" criteria as a SQL string.
3073                If an `Expression` instance is passed, it will be used as-is.
3074            append: if `True`, add to any existing expressions.
3075                Otherwise, this resets the expressions.
3076            join_type: if set, alter the parsed join type.
3077            join_alias: an optional alias for the joined source.
3078            dialect: the dialect used to parse the input expressions.
3079            copy: if `False`, modify this expression instance in-place.
3080            opts: other options to use to parse the input expressions.
3081
3082        Returns:
3083            Select: the modified expression.
3084        """
3085        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
3086
3087        try:
3088            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
3089        except ParseError:
3090            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
3091
3092        join = expression if isinstance(expression, Join) else Join(this=expression)
3093
3094        if isinstance(join.this, Select):
3095            join.this.replace(join.this.subquery())
3096
3097        if join_type:
3098            method: t.Optional[Token]
3099            side: t.Optional[Token]
3100            kind: t.Optional[Token]
3101
3102            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
3103
3104            if method:
3105                join.set("method", method.text)
3106            if side:
3107                join.set("side", side.text)
3108            if kind:
3109                join.set("kind", kind.text)
3110
3111        if on:
3112            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
3113            join.set("on", on)
3114
3115        if using:
3116            join = _apply_list_builder(
3117                *ensure_list(using),
3118                instance=join,
3119                arg="using",
3120                append=append,
3121                copy=copy,
3122                into=Identifier,
3123                **opts,
3124            )
3125
3126        if join_alias:
3127            join.set("this", alias_(join.this, join_alias, table=True))
3128
3129        return _apply_list_builder(
3130            join,
3131            instance=self,
3132            arg="joins",
3133            append=append,
3134            copy=copy,
3135            **opts,
3136        )

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, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3138    def where(
3139        self,
3140        *expressions: t.Optional[ExpOrStr],
3141        append: bool = True,
3142        dialect: DialectType = None,
3143        copy: bool = True,
3144        **opts,
3145    ) -> Select:
3146        """
3147        Append to or set the WHERE expressions.
3148
3149        Example:
3150            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3151            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3152
3153        Args:
3154            *expressions: the SQL code strings to parse.
3155                If an `Expression` instance is passed, it will be used as-is.
3156                Multiple expressions are combined with an AND operator.
3157            append: if `True`, AND the new expressions to any existing expression.
3158                Otherwise, this resets the expression.
3159            dialect: the dialect used to parse the input expressions.
3160            copy: if `False`, modify this expression instance in-place.
3161            opts: other options to use to parse the input expressions.
3162
3163        Returns:
3164            Select: the modified expression.
3165        """
3166        return _apply_conjunction_builder(
3167            *expressions,
3168            instance=self,
3169            arg="where",
3170            append=append,
3171            into=Where,
3172            dialect=dialect,
3173            copy=copy,
3174            **opts,
3175        )

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, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3177    def having(
3178        self,
3179        *expressions: t.Optional[ExpOrStr],
3180        append: bool = True,
3181        dialect: DialectType = None,
3182        copy: bool = True,
3183        **opts,
3184    ) -> Select:
3185        """
3186        Append to or set the HAVING expressions.
3187
3188        Example:
3189            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3190            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3191
3192        Args:
3193            *expressions: the SQL code strings to parse.
3194                If an `Expression` instance is passed, it will be used as-is.
3195                Multiple expressions are combined with an AND operator.
3196            append: if `True`, AND the new expressions to any existing expression.
3197                Otherwise, this resets the expression.
3198            dialect: the dialect used to parse the input expressions.
3199            copy: if `False`, modify this expression instance in-place.
3200            opts: other options to use to parse the input expressions.
3201
3202        Returns:
3203            The modified Select expression.
3204        """
3205        return _apply_conjunction_builder(
3206            *expressions,
3207            instance=self,
3208            arg="having",
3209            append=append,
3210            into=Having,
3211            dialect=dialect,
3212            copy=copy,
3213            **opts,
3214        )

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, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3216    def window(
3217        self,
3218        *expressions: t.Optional[ExpOrStr],
3219        append: bool = True,
3220        dialect: DialectType = None,
3221        copy: bool = True,
3222        **opts,
3223    ) -> Select:
3224        return _apply_list_builder(
3225            *expressions,
3226            instance=self,
3227            arg="windows",
3228            append=append,
3229            into=Window,
3230            dialect=dialect,
3231            copy=copy,
3232            **opts,
3233        )
def qualify( self, *expressions: Union[str, Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Select:
3235    def qualify(
3236        self,
3237        *expressions: t.Optional[ExpOrStr],
3238        append: bool = True,
3239        dialect: DialectType = None,
3240        copy: bool = True,
3241        **opts,
3242    ) -> Select:
3243        return _apply_conjunction_builder(
3244            *expressions,
3245            instance=self,
3246            arg="qualify",
3247            append=append,
3248            into=Qualify,
3249            dialect=dialect,
3250            copy=copy,
3251            **opts,
3252        )
def distinct( self, *ons: Union[str, Expression, NoneType], distinct: bool = True, copy: bool = True) -> Select:
3254    def distinct(
3255        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3256    ) -> Select:
3257        """
3258        Set the OFFSET expression.
3259
3260        Example:
3261            >>> Select().from_("tbl").select("x").distinct().sql()
3262            'SELECT DISTINCT x FROM tbl'
3263
3264        Args:
3265            ons: the expressions to distinct on
3266            distinct: whether the Select should be distinct
3267            copy: if `False`, modify this expression instance in-place.
3268
3269        Returns:
3270            Select: the modified expression.
3271        """
3272        instance = maybe_copy(self, copy)
3273        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3274        instance.set("distinct", Distinct(on=on) if distinct else None)
3275        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, Expression], properties: Optional[Dict] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Create:
3277    def ctas(
3278        self,
3279        table: ExpOrStr,
3280        properties: t.Optional[t.Dict] = None,
3281        dialect: DialectType = None,
3282        copy: bool = True,
3283        **opts,
3284    ) -> Create:
3285        """
3286        Convert this expression to a CREATE TABLE AS statement.
3287
3288        Example:
3289            >>> Select().select("*").from_("tbl").ctas("x").sql()
3290            'CREATE TABLE x AS SELECT * FROM tbl'
3291
3292        Args:
3293            table: the SQL code string to parse as the table name.
3294                If another `Expression` instance is passed, it will be used as-is.
3295            properties: an optional mapping of table properties
3296            dialect: the dialect used to parse the input table.
3297            copy: if `False`, modify this expression instance in-place.
3298            opts: other options to use to parse the input table.
3299
3300        Returns:
3301            The new Create expression.
3302        """
3303        instance = maybe_copy(self, copy)
3304        table_expression = maybe_parse(
3305            table,
3306            into=Table,
3307            dialect=dialect,
3308            **opts,
3309        )
3310        properties_expression = None
3311        if properties:
3312            properties_expression = Properties.from_dict(properties)
3313
3314        return Create(
3315            this=table_expression,
3316            kind="table",
3317            expression=instance,
3318            properties=properties_expression,
3319        )

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) -> Select:
3321    def lock(self, update: bool = True, copy: bool = True) -> Select:
3322        """
3323        Set the locking read mode for this expression.
3324
3325        Examples:
3326            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3327            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3328
3329            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3330            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3331
3332        Args:
3333            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3334            copy: if `False`, modify this expression instance in-place.
3335
3336        Returns:
3337            The modified expression.
3338        """
3339        inst = maybe_copy(self, copy)
3340        inst.set("locks", [Lock(update=update)])
3341
3342        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, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True) -> Select:
3344    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3345        """
3346        Set hints for this expression.
3347
3348        Examples:
3349            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3350            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3351
3352        Args:
3353            hints: The SQL code strings to parse as the hints.
3354                If an `Expression` instance is passed, it will be used as-is.
3355            dialect: The dialect used to parse the hints.
3356            copy: If `False`, modify this expression instance in-place.
3357
3358        Returns:
3359            The modified expression.
3360        """
3361        inst = maybe_copy(self, copy)
3362        inst.set(
3363            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3364        )
3365
3366        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.

selects: List[Expression]
key = 'select'
class Subquery(DerivedTable, Unionable):
3381class Subquery(DerivedTable, Unionable):
3382    arg_types = {
3383        "this": True,
3384        "alias": False,
3385        "with": False,
3386        **QUERY_MODIFIERS,
3387    }
3388
3389    def unnest(self):
3390        """
3391        Returns the first non subquery.
3392        """
3393        expression = self
3394        while isinstance(expression, Subquery):
3395            expression = expression.this
3396        return expression
3397
3398    def unwrap(self) -> Subquery:
3399        expression = self
3400        while expression.same_parent and expression.is_wrapper:
3401            expression = t.cast(Subquery, expression.parent)
3402        return expression
3403
3404    @property
3405    def is_wrapper(self) -> bool:
3406        """
3407        Whether this Subquery acts as a simple wrapper around another expression.
3408
3409        SELECT * FROM (((SELECT * FROM t)))
3410                      ^
3411                      This corresponds to a "wrapper" Subquery node
3412        """
3413        return all(v is None for k, v in self.args.items() if k != "this")
3414
3415    @property
3416    def is_star(self) -> bool:
3417        return self.this.is_star
3418
3419    @property
3420    def output_name(self) -> str:
3421        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):
3389    def unnest(self):
3390        """
3391        Returns the first non subquery.
3392        """
3393        expression = self
3394        while isinstance(expression, Subquery):
3395            expression = expression.this
3396        return expression

Returns the first non subquery.

def unwrap(self) -> Subquery:
3398    def unwrap(self) -> Subquery:
3399        expression = self
3400        while expression.same_parent and expression.is_wrapper:
3401            expression = t.cast(Subquery, expression.parent)
3402        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")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'subquery'
class TableSample(Expression):
3424class TableSample(Expression):
3425    arg_types = {
3426        "this": False,
3427        "expressions": False,
3428        "method": False,
3429        "bucket_numerator": False,
3430        "bucket_denominator": False,
3431        "bucket_field": False,
3432        "percent": False,
3433        "rows": False,
3434        "size": False,
3435        "seed": False,
3436        "kind": False,
3437    }
arg_types = {'this': False, 'expressions': 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):
3440class Tag(Expression):
3441    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3442
3443    arg_types = {
3444        "this": False,
3445        "prefix": False,
3446        "postfix": False,
3447    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3452class Pivot(Expression):
3453    arg_types = {
3454        "this": False,
3455        "alias": False,
3456        "expressions": False,
3457        "field": False,
3458        "unpivot": False,
3459        "using": False,
3460        "group": False,
3461        "columns": False,
3462        "include_nulls": False,
3463    }
arg_types = {'this': False, 'alias': False, 'expressions': False, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False, 'include_nulls': False}
key = 'pivot'
class Window(Condition):
3466class Window(Condition):
3467    arg_types = {
3468        "this": True,
3469        "partition_by": False,
3470        "order": False,
3471        "spec": False,
3472        "alias": False,
3473        "over": False,
3474        "first": False,
3475    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3478class WindowSpec(Expression):
3479    arg_types = {
3480        "kind": False,
3481        "start": False,
3482        "start_side": False,
3483        "end": False,
3484        "end_side": False,
3485    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3488class Where(Expression):
3489    pass
key = 'where'
class Star(Expression):
3492class Star(Expression):
3493    arg_types = {"except": False, "replace": False}
3494
3495    @property
3496    def name(self) -> str:
3497        return "*"
3498
3499    @property
3500    def output_name(self) -> str:
3501        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")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'star'
class Parameter(Condition):
3504class Parameter(Condition):
3505    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3508class SessionParameter(Condition):
3509    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3512class Placeholder(Condition):
3513    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3516class Null(Condition):
3517    arg_types: t.Dict[str, t.Any] = {}
3518
3519    @property
3520    def name(self) -> str:
3521        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3524class Boolean(Condition):
3525    pass
key = 'boolean'
class DataTypeParam(Expression):
3528class DataTypeParam(Expression):
3529    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypeparam'
class DataType(Expression):
3532class DataType(Expression):
3533    arg_types = {
3534        "this": True,
3535        "expressions": False,
3536        "nested": False,
3537        "values": False,
3538        "prefix": False,
3539        "kind": False,
3540    }
3541
3542    class Type(AutoName):
3543        ARRAY = auto()
3544        BIGDECIMAL = auto()
3545        BIGINT = auto()
3546        BIGSERIAL = auto()
3547        BINARY = auto()
3548        BIT = auto()
3549        BOOLEAN = auto()
3550        CHAR = auto()
3551        DATE = auto()
3552        DATEMULTIRANGE = auto()
3553        DATERANGE = auto()
3554        DATETIME = auto()
3555        DATETIME64 = auto()
3556        DECIMAL = auto()
3557        DOUBLE = auto()
3558        ENUM = auto()
3559        ENUM8 = auto()
3560        ENUM16 = auto()
3561        FIXEDSTRING = auto()
3562        FLOAT = auto()
3563        GEOGRAPHY = auto()
3564        GEOMETRY = auto()
3565        HLLSKETCH = auto()
3566        HSTORE = auto()
3567        IMAGE = auto()
3568        INET = auto()
3569        INT = auto()
3570        INT128 = auto()
3571        INT256 = auto()
3572        INT4MULTIRANGE = auto()
3573        INT4RANGE = auto()
3574        INT8MULTIRANGE = auto()
3575        INT8RANGE = auto()
3576        INTERVAL = auto()
3577        IPADDRESS = auto()
3578        IPPREFIX = auto()
3579        JSON = auto()
3580        JSONB = auto()
3581        LONGBLOB = auto()
3582        LONGTEXT = auto()
3583        LOWCARDINALITY = auto()
3584        MAP = auto()
3585        MEDIUMBLOB = auto()
3586        MEDIUMINT = auto()
3587        MEDIUMTEXT = auto()
3588        MONEY = auto()
3589        NCHAR = auto()
3590        NESTED = auto()
3591        NULL = auto()
3592        NULLABLE = auto()
3593        NUMMULTIRANGE = auto()
3594        NUMRANGE = auto()
3595        NVARCHAR = auto()
3596        OBJECT = auto()
3597        ROWVERSION = auto()
3598        SERIAL = auto()
3599        SET = auto()
3600        SMALLINT = auto()
3601        SMALLMONEY = auto()
3602        SMALLSERIAL = auto()
3603        STRUCT = auto()
3604        SUPER = auto()
3605        TEXT = auto()
3606        TINYBLOB = auto()
3607        TINYTEXT = auto()
3608        TIME = auto()
3609        TIMETZ = auto()
3610        TIMESTAMP = auto()
3611        TIMESTAMPLTZ = auto()
3612        TIMESTAMPTZ = auto()
3613        TIMESTAMP_S = auto()
3614        TIMESTAMP_MS = auto()
3615        TIMESTAMP_NS = auto()
3616        TINYINT = auto()
3617        TSMULTIRANGE = auto()
3618        TSRANGE = auto()
3619        TSTZMULTIRANGE = auto()
3620        TSTZRANGE = auto()
3621        UBIGINT = auto()
3622        UINT = auto()
3623        UINT128 = auto()
3624        UINT256 = auto()
3625        UMEDIUMINT = auto()
3626        UDECIMAL = auto()
3627        UNIQUEIDENTIFIER = auto()
3628        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3629        USERDEFINED = "USER-DEFINED"
3630        USMALLINT = auto()
3631        UTINYINT = auto()
3632        UUID = auto()
3633        VARBINARY = auto()
3634        VARCHAR = auto()
3635        VARIANT = auto()
3636        XML = auto()
3637        YEAR = auto()
3638
3639    TEXT_TYPES = {
3640        Type.CHAR,
3641        Type.NCHAR,
3642        Type.VARCHAR,
3643        Type.NVARCHAR,
3644        Type.TEXT,
3645    }
3646
3647    INTEGER_TYPES = {
3648        Type.INT,
3649        Type.TINYINT,
3650        Type.SMALLINT,
3651        Type.BIGINT,
3652        Type.INT128,
3653        Type.INT256,
3654    }
3655
3656    FLOAT_TYPES = {
3657        Type.FLOAT,
3658        Type.DOUBLE,
3659    }
3660
3661    NUMERIC_TYPES = {
3662        *INTEGER_TYPES,
3663        *FLOAT_TYPES,
3664    }
3665
3666    TEMPORAL_TYPES = {
3667        Type.TIME,
3668        Type.TIMETZ,
3669        Type.TIMESTAMP,
3670        Type.TIMESTAMPTZ,
3671        Type.TIMESTAMPLTZ,
3672        Type.TIMESTAMP_S,
3673        Type.TIMESTAMP_MS,
3674        Type.TIMESTAMP_NS,
3675        Type.DATE,
3676        Type.DATETIME,
3677        Type.DATETIME64,
3678    }
3679
3680    @classmethod
3681    def build(
3682        cls,
3683        dtype: str | DataType | DataType.Type,
3684        dialect: DialectType = None,
3685        udt: bool = False,
3686        **kwargs,
3687    ) -> DataType:
3688        """
3689        Constructs a DataType object.
3690
3691        Args:
3692            dtype: the data type of interest.
3693            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3694            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3695                DataType, thus creating a user-defined type.
3696            kawrgs: additional arguments to pass in the constructor of DataType.
3697
3698        Returns:
3699            The constructed DataType object.
3700        """
3701        from sqlglot import parse_one
3702
3703        if isinstance(dtype, str):
3704            if dtype.upper() == "UNKNOWN":
3705                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3706
3707            try:
3708                data_type_exp = parse_one(
3709                    dtype, read=dialect, into=DataType, error_level=ErrorLevel.IGNORE
3710                )
3711            except ParseError:
3712                if udt:
3713                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3714                raise
3715        elif isinstance(dtype, DataType.Type):
3716            data_type_exp = DataType(this=dtype)
3717        elif isinstance(dtype, DataType):
3718            return dtype
3719        else:
3720            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3721
3722        return DataType(**{**data_type_exp.args, **kwargs})
3723
3724    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3725        """
3726        Checks whether this DataType matches one of the provided data types. Nested types or precision
3727        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3728
3729        Args:
3730            dtypes: the data types to compare this DataType to.
3731
3732        Returns:
3733            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3734        """
3735        for dtype in dtypes:
3736            other = DataType.build(dtype, udt=True)
3737
3738            if (
3739                other.expressions
3740                or self.this == DataType.Type.USERDEFINED
3741                or other.this == DataType.Type.USERDEFINED
3742            ):
3743                matches = self == other
3744            else:
3745                matches = self.this == other.this
3746
3747            if matches:
3748                return True
3749        return False
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False, 'kind': False}
TEXT_TYPES = {<Type.CHAR: 'CHAR'>, <Type.TEXT: 'TEXT'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>}
INTEGER_TYPES = {<Type.SMALLINT: 'SMALLINT'>, <Type.INT: 'INT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT256: 'INT256'>, <Type.BIGINT: 'BIGINT'>, <Type.INT128: 'INT128'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.BIGINT: 'BIGINT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.INT: 'INT'>, <Type.INT128: 'INT128'>, <Type.TINYINT: 'TINYINT'>, <Type.INT256: 'INT256'>}
TEMPORAL_TYPES = {<Type.TIMETZ: 'TIMETZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATETIME: 'DATETIME'>, <Type.TIME: 'TIME'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.TIMESTAMP_S: 'TIMESTAMP_S'>, <Type.DATETIME64: 'DATETIME64'>, <Type.TIMESTAMP_NS: 'TIMESTAMP_NS'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMP_MS: 'TIMESTAMP_MS'>, <Type.DATE: 'DATE'>}
@classmethod
def build( cls, dtype: str | DataType | DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, udt: bool = False, **kwargs) -> DataType:
3680    @classmethod
3681    def build(
3682        cls,
3683        dtype: str | DataType | DataType.Type,
3684        dialect: DialectType = None,
3685        udt: bool = False,
3686        **kwargs,
3687    ) -> DataType:
3688        """
3689        Constructs a DataType object.
3690
3691        Args:
3692            dtype: the data type of interest.
3693            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3694            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3695                DataType, thus creating a user-defined type.
3696            kawrgs: additional arguments to pass in the constructor of DataType.
3697
3698        Returns:
3699            The constructed DataType object.
3700        """
3701        from sqlglot import parse_one
3702
3703        if isinstance(dtype, str):
3704            if dtype.upper() == "UNKNOWN":
3705                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3706
3707            try:
3708                data_type_exp = parse_one(
3709                    dtype, read=dialect, into=DataType, error_level=ErrorLevel.IGNORE
3710                )
3711            except ParseError:
3712                if udt:
3713                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3714                raise
3715        elif isinstance(dtype, DataType.Type):
3716            data_type_exp = DataType(this=dtype)
3717        elif isinstance(dtype, DataType):
3718            return dtype
3719        else:
3720            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3721
3722        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 | DataType | DataType.Type) -> bool:
3724    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3725        """
3726        Checks whether this DataType matches one of the provided data types. Nested types or precision
3727        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3728
3729        Args:
3730            dtypes: the data types to compare this DataType to.
3731
3732        Returns:
3733            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3734        """
3735        for dtype in dtypes:
3736            other = DataType.build(dtype, udt=True)
3737
3738            if (
3739                other.expressions
3740                or self.this == DataType.Type.USERDEFINED
3741                or other.this == DataType.Type.USERDEFINED
3742            ):
3743                matches = self == other
3744            else:
3745                matches = self.this == other.this
3746
3747            if matches:
3748                return True
3749        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):
3542    class Type(AutoName):
3543        ARRAY = auto()
3544        BIGDECIMAL = auto()
3545        BIGINT = auto()
3546        BIGSERIAL = auto()
3547        BINARY = auto()
3548        BIT = auto()
3549        BOOLEAN = auto()
3550        CHAR = auto()
3551        DATE = auto()
3552        DATEMULTIRANGE = auto()
3553        DATERANGE = auto()
3554        DATETIME = auto()
3555        DATETIME64 = auto()
3556        DECIMAL = auto()
3557        DOUBLE = auto()
3558        ENUM = auto()
3559        ENUM8 = auto()
3560        ENUM16 = auto()
3561        FIXEDSTRING = auto()
3562        FLOAT = auto()
3563        GEOGRAPHY = auto()
3564        GEOMETRY = auto()
3565        HLLSKETCH = auto()
3566        HSTORE = auto()
3567        IMAGE = auto()
3568        INET = auto()
3569        INT = auto()
3570        INT128 = auto()
3571        INT256 = auto()
3572        INT4MULTIRANGE = auto()
3573        INT4RANGE = auto()
3574        INT8MULTIRANGE = auto()
3575        INT8RANGE = auto()
3576        INTERVAL = auto()
3577        IPADDRESS = auto()
3578        IPPREFIX = auto()
3579        JSON = auto()
3580        JSONB = auto()
3581        LONGBLOB = auto()
3582        LONGTEXT = auto()
3583        LOWCARDINALITY = auto()
3584        MAP = auto()
3585        MEDIUMBLOB = auto()
3586        MEDIUMINT = auto()
3587        MEDIUMTEXT = auto()
3588        MONEY = auto()
3589        NCHAR = auto()
3590        NESTED = auto()
3591        NULL = auto()
3592        NULLABLE = auto()
3593        NUMMULTIRANGE = auto()
3594        NUMRANGE = auto()
3595        NVARCHAR = auto()
3596        OBJECT = auto()
3597        ROWVERSION = auto()
3598        SERIAL = auto()
3599        SET = auto()
3600        SMALLINT = auto()
3601        SMALLMONEY = auto()
3602        SMALLSERIAL = auto()
3603        STRUCT = auto()
3604        SUPER = auto()
3605        TEXT = auto()
3606        TINYBLOB = auto()
3607        TINYTEXT = auto()
3608        TIME = auto()
3609        TIMETZ = auto()
3610        TIMESTAMP = auto()
3611        TIMESTAMPLTZ = auto()
3612        TIMESTAMPTZ = auto()
3613        TIMESTAMP_S = auto()
3614        TIMESTAMP_MS = auto()
3615        TIMESTAMP_NS = auto()
3616        TINYINT = auto()
3617        TSMULTIRANGE = auto()
3618        TSRANGE = auto()
3619        TSTZMULTIRANGE = auto()
3620        TSTZRANGE = auto()
3621        UBIGINT = auto()
3622        UINT = auto()
3623        UINT128 = auto()
3624        UINT256 = auto()
3625        UMEDIUMINT = auto()
3626        UDECIMAL = auto()
3627        UNIQUEIDENTIFIER = auto()
3628        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3629        USERDEFINED = "USER-DEFINED"
3630        USMALLINT = auto()
3631        UTINYINT = auto()
3632        UUID = auto()
3633        VARBINARY = auto()
3634        VARCHAR = auto()
3635        VARIANT = auto()
3636        XML = auto()
3637        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'>
TINYBLOB = <Type.TINYBLOB: 'TINYBLOB'>
TINYTEXT = <Type.TINYTEXT: 'TINYTEXT'>
TIME = <Type.TIME: 'TIME'>
TIMETZ = <Type.TIMETZ: 'TIMETZ'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMP_S = <Type.TIMESTAMP_S: 'TIMESTAMP_S'>
TIMESTAMP_MS = <Type.TIMESTAMP_MS: 'TIMESTAMP_MS'>
TIMESTAMP_NS = <Type.TIMESTAMP_NS: 'TIMESTAMP_NS'>
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'>
UMEDIUMINT = <Type.UMEDIUMINT: 'UMEDIUMINT'>
UDECIMAL = <Type.UDECIMAL: 'UDECIMAL'>
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(DataType):
3753class PseudoType(DataType):
3754    arg_types = {"this": True}
arg_types = {'this': True}
key = 'pseudotype'
class ObjectIdentifier(DataType):
3758class ObjectIdentifier(DataType):
3759    arg_types = {"this": True}
arg_types = {'this': True}
key = 'objectidentifier'
class SubqueryPredicate(Predicate):
3763class SubqueryPredicate(Predicate):
3764    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3767class All(SubqueryPredicate):
3768    pass
key = 'all'
class Any(SubqueryPredicate):
3771class Any(SubqueryPredicate):
3772    pass
key = 'any'
class Exists(SubqueryPredicate):
3775class Exists(SubqueryPredicate):
3776    pass
key = 'exists'
class Command(Expression):
3781class Command(Expression):
3782    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3785class Transaction(Expression):
3786    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3789class Commit(Expression):
3790    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3793class Rollback(Expression):
3794    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3797class AlterTable(Expression):
3798    arg_types = {"this": True, "actions": True, "exists": False, "only": False}
arg_types = {'this': True, 'actions': True, 'exists': False, 'only': False}
key = 'altertable'
class AddConstraint(Expression):
3801class AddConstraint(Expression):
3802    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3805class DropPartition(Expression):
3806    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3810class Binary(Condition):
3811    arg_types = {"this": True, "expression": True}
3812
3813    @property
3814    def left(self) -> Expression:
3815        return self.this
3816
3817    @property
3818    def right(self) -> Expression:
3819        return self.expression
arg_types = {'this': True, 'expression': True}
left: Expression
right: Expression
key = 'binary'
class Add(Binary):
3822class Add(Binary):
3823    pass
key = 'add'
class Connector(Binary):
3826class Connector(Binary):
3827    pass
key = 'connector'
class And(Connector):
3830class And(Connector):
3831    pass
key = 'and'
class Or(Connector):
3834class Or(Connector):
3835    pass
key = 'or'
class BitwiseAnd(Binary):
3838class BitwiseAnd(Binary):
3839    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3842class BitwiseLeftShift(Binary):
3843    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3846class BitwiseOr(Binary):
3847    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3850class BitwiseRightShift(Binary):
3851    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3854class BitwiseXor(Binary):
3855    pass
key = 'bitwisexor'
class Div(Binary):
3858class Div(Binary):
3859    pass
key = 'div'
class Overlaps(Binary):
3862class Overlaps(Binary):
3863    pass
key = 'overlaps'
class Dot(Binary):
3866class Dot(Binary):
3867    @property
3868    def name(self) -> str:
3869        return self.expression.name
3870
3871    @property
3872    def output_name(self) -> str:
3873        return self.name
3874
3875    @classmethod
3876    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3877        """Build a Dot object with a sequence of expressions."""
3878        if len(expressions) < 2:
3879            raise ValueError(f"Dot requires >= 2 expressions.")
3880
3881        return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))
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")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
@classmethod
def build( self, expressions: Sequence[Expression]) -> Dot:
3875    @classmethod
3876    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3877        """Build a Dot object with a sequence of expressions."""
3878        if len(expressions) < 2:
3879            raise ValueError(f"Dot requires >= 2 expressions.")
3880
3881        return t.cast(Dot, reduce(lambda x, y: Dot(this=x, expression=y), expressions))

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3884class DPipe(Binary):
3885    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3888class SafeDPipe(DPipe):
3889    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3892class EQ(Binary, Predicate):
3893    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3896class NullSafeEQ(Binary, Predicate):
3897    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3900class NullSafeNEQ(Binary, Predicate):
3901    pass
key = 'nullsafeneq'
class Distance(Binary):
3904class Distance(Binary):
3905    pass
key = 'distance'
class Escape(Binary):
3908class Escape(Binary):
3909    pass
key = 'escape'
class Glob(Binary, Predicate):
3912class Glob(Binary, Predicate):
3913    pass
key = 'glob'
class GT(Binary, Predicate):
3916class GT(Binary, Predicate):
3917    pass
key = 'gt'
class GTE(Binary, Predicate):
3920class GTE(Binary, Predicate):
3921    pass
key = 'gte'
class ILike(Binary, Predicate):
3924class ILike(Binary, Predicate):
3925    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3928class ILikeAny(Binary, Predicate):
3929    pass
key = 'ilikeany'
class IntDiv(Binary):
3932class IntDiv(Binary):
3933    pass
key = 'intdiv'
class Is(Binary, Predicate):
3936class Is(Binary, Predicate):
3937    pass
key = 'is'
class Kwarg(Binary):
3940class Kwarg(Binary):
3941    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3944class Like(Binary, Predicate):
3945    pass
key = 'like'
class LikeAny(Binary, Predicate):
3948class LikeAny(Binary, Predicate):
3949    pass
key = 'likeany'
class LT(Binary, Predicate):
3952class LT(Binary, Predicate):
3953    pass
key = 'lt'
class LTE(Binary, Predicate):
3956class LTE(Binary, Predicate):
3957    pass
key = 'lte'
class Mod(Binary):
3960class Mod(Binary):
3961    pass
key = 'mod'
class Mul(Binary):
3964class Mul(Binary):
3965    pass
key = 'mul'
class NEQ(Binary, Predicate):
3968class NEQ(Binary, Predicate):
3969    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3972class SimilarTo(Binary, Predicate):
3973    pass
key = 'similarto'
class Slice(Binary):
3976class Slice(Binary):
3977    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3980class Sub(Binary):
3981    pass
key = 'sub'
class ArrayOverlaps(Binary):
3984class ArrayOverlaps(Binary):
3985    pass
key = 'arrayoverlaps'
class Unary(Condition):
3990class Unary(Condition):
3991    pass
key = 'unary'
class BitwiseNot(Unary):
3994class BitwiseNot(Unary):
3995    pass
key = 'bitwisenot'
class Not(Unary):
3998class Not(Unary):
3999    pass
key = 'not'
class Paren(Unary):
4002class Paren(Unary):
4003    arg_types = {"this": True, "with": False}
4004
4005    @property
4006    def output_name(self) -> str:
4007        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")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'paren'
class Neg(Unary):
4010class Neg(Unary):
4011    pass
key = 'neg'
class Alias(Expression):
4014class Alias(Expression):
4015    arg_types = {"this": True, "alias": False}
4016
4017    @property
4018    def output_name(self) -> str:
4019        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")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'alias'
class Aliases(Expression):
4022class Aliases(Expression):
4023    arg_types = {"this": True, "expressions": True}
4024
4025    @property
4026    def aliases(self):
4027        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
4030class AtTimeZone(Expression):
4031    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
4034class Between(Predicate):
4035    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
4038class Bracket(Condition):
4039    arg_types = {"this": True, "expressions": True}
4040
4041    @property
4042    def output_name(self) -> str:
4043        if len(self.expressions) == 1:
4044            return self.expressions[0].output_name
4045
4046        return super().output_name
arg_types = {'this': True, 'expressions': 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")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
key = 'bracket'
class SafeBracket(Bracket):
4049class SafeBracket(Bracket):
4050    """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):
4053class Distinct(Expression):
4054    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
4057class In(Predicate):
4058    arg_types = {
4059        "this": True,
4060        "expressions": False,
4061        "query": False,
4062        "unnest": False,
4063        "field": False,
4064        "is_global": False,
4065    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
4068class TimeUnit(Expression):
4069    """Automatically converts unit arg into a var."""
4070
4071    arg_types = {"unit": False}
4072
4073    def __init__(self, **args):
4074        unit = args.get("unit")
4075        if isinstance(unit, (Column, Literal)):
4076            args["unit"] = Var(this=unit.name)
4077        elif isinstance(unit, Week):
4078            unit.set("this", Var(this=unit.this.name))
4079
4080        super().__init__(**args)
4081
4082    @property
4083    def unit(self) -> t.Optional[Var]:
4084        return self.args.get("unit")

Automatically converts unit arg into a var.

TimeUnit(**args)
4073    def __init__(self, **args):
4074        unit = args.get("unit")
4075        if isinstance(unit, (Column, Literal)):
4076            args["unit"] = Var(this=unit.name)
4077        elif isinstance(unit, Week):
4078            unit.set("this", Var(this=unit.this.name))
4079
4080        super().__init__(**args)
arg_types = {'unit': False}
unit: Optional[Var]
key = 'timeunit'
class IntervalOp(TimeUnit):
4087class IntervalOp(TimeUnit):
4088    arg_types = {"unit": True, "expression": True}
4089
4090    def interval(self):
4091        return Interval(
4092            this=self.expression.copy(),
4093            unit=self.unit.copy(),
4094        )
arg_types = {'unit': True, 'expression': True}
def interval(self):
4090    def interval(self):
4091        return Interval(
4092            this=self.expression.copy(),
4093            unit=self.unit.copy(),
4094        )
key = 'intervalop'
class IntervalSpan(DataType):
4100class IntervalSpan(DataType):
4101    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'intervalspan'
class Interval(TimeUnit):
4104class Interval(TimeUnit):
4105    arg_types = {"this": False, "unit": False}
arg_types = {'this': False, 'unit': False}
key = 'interval'
class IgnoreNulls(Expression):
4108class IgnoreNulls(Expression):
4109    pass
key = 'ignorenulls'
class RespectNulls(Expression):
4112class RespectNulls(Expression):
4113    pass
key = 'respectnulls'
class Func(Condition):
4117class Func(Condition):
4118    """
4119    The base class for all function expressions.
4120
4121    Attributes:
4122        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
4123            treated as a variable length argument and the argument's value will be stored as a list.
4124        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
4125            for this function expression. These values are used to map this node to a name during parsing
4126            as well as to provide the function's name during SQL string generation. By default the SQL
4127            name is set to the expression's class name transformed to snake case.
4128    """
4129
4130    is_var_len_args = False
4131
4132    @classmethod
4133    def from_arg_list(cls, args):
4134        if cls.is_var_len_args:
4135            all_arg_keys = list(cls.arg_types)
4136            # If this function supports variable length argument treat the last argument as such.
4137            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4138            num_non_var = len(non_var_len_arg_keys)
4139
4140            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4141            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4142        else:
4143            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4144
4145        return cls(**args_dict)
4146
4147    @classmethod
4148    def sql_names(cls):
4149        if cls is Func:
4150            raise NotImplementedError(
4151                "SQL name is only supported by concrete function implementations"
4152            )
4153        if "_sql_names" not in cls.__dict__:
4154            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4155        return cls._sql_names
4156
4157    @classmethod
4158    def sql_name(cls):
4159        return cls.sql_names()[0]
4160
4161    @classmethod
4162    def default_parser_mappings(cls):
4163        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):
4132    @classmethod
4133    def from_arg_list(cls, args):
4134        if cls.is_var_len_args:
4135            all_arg_keys = list(cls.arg_types)
4136            # If this function supports variable length argument treat the last argument as such.
4137            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
4138            num_non_var = len(non_var_len_arg_keys)
4139
4140            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
4141            args_dict[all_arg_keys[-1]] = args[num_non_var:]
4142        else:
4143            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
4144
4145        return cls(**args_dict)
@classmethod
def sql_names(cls):
4147    @classmethod
4148    def sql_names(cls):
4149        if cls is Func:
4150            raise NotImplementedError(
4151                "SQL name is only supported by concrete function implementations"
4152            )
4153        if "_sql_names" not in cls.__dict__:
4154            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4155        return cls._sql_names
@classmethod
def sql_name(cls):
4157    @classmethod
4158    def sql_name(cls):
4159        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
4161    @classmethod
4162    def default_parser_mappings(cls):
4163        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
4166class AggFunc(Func):
4167    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
4170class ParameterizedAgg(AggFunc):
4171    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
4174class Abs(Func):
4175    pass
key = 'abs'
class Flatten(Func):
4178class Flatten(Func):
4179    pass
key = 'flatten'
class Transform(Func):
4183class Transform(Func):
4184    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
4187class Anonymous(Func):
4188    arg_types = {"this": True, "expressions": False}
4189    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
4194class Hll(AggFunc):
4195    arg_types = {"this": True, "expressions": False}
4196    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
4199class ApproxDistinct(AggFunc):
4200    arg_types = {"this": True, "accuracy": False}
4201    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
4204class Array(Func):
4205    arg_types = {"expressions": False}
4206    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
4210class ToChar(Func):
4211    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
4214class GenerateSeries(Func):
4215    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
4218class ArrayAgg(AggFunc):
4219    pass
key = 'arrayagg'
class ArrayAll(Func):
4222class ArrayAll(Func):
4223    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4226class ArrayAny(Func):
4227    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4230class ArrayConcat(Func):
4231    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4232    arg_types = {"this": True, "expressions": False}
4233    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4236class ArrayContains(Binary, Func):
4237    pass
key = 'arraycontains'
class ArrayContained(Binary):
4240class ArrayContained(Binary):
4241    pass
key = 'arraycontained'
class ArrayFilter(Func):
4244class ArrayFilter(Func):
4245    arg_types = {"this": True, "expression": True}
4246    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4249class ArrayJoin(Func):
4250    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4253class ArraySize(Func):
4254    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4257class ArraySort(Func):
4258    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4261class ArraySum(Func):
4262    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4265class ArrayUnionAgg(AggFunc):
4266    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4269class Avg(AggFunc):
4270    pass
key = 'avg'
class AnyValue(AggFunc):
4273class AnyValue(AggFunc):
4274    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):
4277class First(Func):
4278    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4281class Last(Func):
4282    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4285class Case(Func):
4286    arg_types = {"this": False, "ifs": True, "default": False}
4287
4288    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4289        instance = maybe_copy(self, copy)
4290        instance.append(
4291            "ifs",
4292            If(
4293                this=maybe_parse(condition, copy=copy, **opts),
4294                true=maybe_parse(then, copy=copy, **opts),
4295            ),
4296        )
4297        return instance
4298
4299    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4300        instance = maybe_copy(self, copy)
4301        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4302        return instance
arg_types = {'this': False, 'ifs': True, 'default': False}
def when( self, condition: Union[str, Expression], then: Union[str, Expression], copy: bool = True, **opts) -> Case:
4288    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4289        instance = maybe_copy(self, copy)
4290        instance.append(
4291            "ifs",
4292            If(
4293                this=maybe_parse(condition, copy=copy, **opts),
4294                true=maybe_parse(then, copy=copy, **opts),
4295            ),
4296        )
4297        return instance
def else_( self, condition: Union[str, Expression], copy: bool = True, **opts) -> Case:
4299    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4300        instance = maybe_copy(self, copy)
4301        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4302        return instance
key = 'case'
class Cast(Func):
4305class Cast(Func):
4306    arg_types = {"this": True, "to": True, "format": False, "safe": False}
4307
4308    @property
4309    def name(self) -> str:
4310        return self.this.name
4311
4312    @property
4313    def to(self) -> DataType:
4314        return self.args["to"]
4315
4316    @property
4317    def output_name(self) -> str:
4318        return self.name
4319
4320    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4321        """
4322        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4323        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4324        array<int> != array<float>.
4325
4326        Args:
4327            dtypes: the data types to compare this Cast's DataType to.
4328
4329        Returns:
4330            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4331        """
4332        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True, 'format': False, 'safe': False}
name: str
to: DataType
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")sqlglot.expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c")sqlglot.expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2")sqlglot.expressions[0].output_name
''
def is_type( self, *dtypes: str | DataType | DataType.Type) -> bool:
4320    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4321        """
4322        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4323        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4324        array<int> != array<float>.
4325
4326        Args:
4327            dtypes: the data types to compare this Cast's DataType to.
4328
4329        Returns:
4330            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4331        """
4332        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):
4335class TryCast(Cast):
4336    pass
key = 'trycast'
class CastToStrType(Func):
4339class CastToStrType(Func):
4340    arg_types = {"this": True, "to": True}
arg_types = {'this': True, 'to': True}
key = 'casttostrtype'
class Collate(Binary, Func):
4343class Collate(Binary, Func):
4344    pass
key = 'collate'
class Ceil(Func):
4347class Ceil(Func):
4348    arg_types = {"this": True, "decimals": False}
4349    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4352class Coalesce(Func):
4353    arg_types = {"this": True, "expressions": False}
4354    is_var_len_args = True
4355    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Chr(Func):
4358class Chr(Func):
4359    arg_types = {"this": True, "charset": False, "expressions": False}
4360    is_var_len_args = True
4361    _sql_names = ["CHR", "CHAR"]
arg_types = {'this': True, 'charset': False, 'expressions': False}
is_var_len_args = True
key = 'chr'
class Concat(Func):
4364class Concat(Func):
4365    arg_types = {"expressions": True}
4366    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4369class SafeConcat(Concat):
4370    pass
key = 'safeconcat'
class ConcatWs(Concat):
4373class ConcatWs(Concat):
4374    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4377class Count(AggFunc):
4378    arg_types = {"this": False, "expressions": False}
4379    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4382class CountIf(AggFunc):
4383    pass
key = 'countif'
class CurrentDate(Func):
4386class CurrentDate(Func):
4387    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4390class CurrentDatetime(Func):
4391    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4394class CurrentTime(Func):
4395    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4398class CurrentTimestamp(Func):
4399    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4402class CurrentUser(Func):
4403    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, IntervalOp):
4406class DateAdd(Func, IntervalOp):
4407    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, IntervalOp):
4410class DateSub(Func, IntervalOp):
4411    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4414class DateDiff(Func, TimeUnit):
4415    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4416    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4419class DateTrunc(Func):
4420    arg_types = {"unit": True, "this": True, "zone": False}
4421
4422    @property
4423    def unit(self) -> Expression:
4424        return self.args["unit"]
arg_types = {'unit': True, 'this': True, 'zone': False}
unit: Expression
key = 'datetrunc'
class DatetimeAdd(Func, IntervalOp):
4427class DatetimeAdd(Func, IntervalOp):
4428    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, IntervalOp):
4431class DatetimeSub(Func, IntervalOp):
4432    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4435class DatetimeDiff(Func, TimeUnit):
4436    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4439class DatetimeTrunc(Func, TimeUnit):
4440    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4443class DayOfWeek(Func):
4444    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4447class DayOfMonth(Func):
4448    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4451class DayOfYear(Func):
4452    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class ToDays(Func):
4455class ToDays(Func):
4456    pass
key = 'todays'
class WeekOfYear(Func):
4459class WeekOfYear(Func):
4460    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4463class MonthsBetween(Func):
4464    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4467class LastDateOfMonth(Func):
4468    pass
key = 'lastdateofmonth'
class Extract(Func):
4471class Extract(Func):
4472    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class Timestamp(Func):
4475class Timestamp(Func):
4476    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'timestamp'
class TimestampAdd(Func, TimeUnit):
4479class TimestampAdd(Func, TimeUnit):
4480    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4483class TimestampSub(Func, TimeUnit):
4484    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4487class TimestampDiff(Func, TimeUnit):
4488    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4491class TimestampTrunc(Func, TimeUnit):
4492    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4495class TimeAdd(Func, TimeUnit):
4496    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4499class TimeSub(Func, TimeUnit):
4500    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4503class TimeDiff(Func, TimeUnit):
4504    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4507class TimeTrunc(Func, TimeUnit):
4508    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4511class DateFromParts(Func):
4512    _sql_names = ["DATEFROMPARTS"]
4513    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4516class DateStrToDate(Func):
4517    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4520class DateToDateStr(Func):
4521    pass
key = 'datetodatestr'
class DateToDi(Func):
4524class DateToDi(Func):
4525    pass
key = 'datetodi'
class Date(Func):
4529class Date(Func):
4530    arg_types = {"this": False, "zone": False, "expressions": False}
4531    is_var_len_args = True
arg_types = {'this': False, 'zone': False, 'expressions': False}
is_var_len_args = True
key = 'date'
class Day(Func):
4534class Day(Func):
4535    pass
key = 'day'
class Decode(Func):
4538class Decode(Func):
4539    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4542class DiToDate(Func):
4543    pass
key = 'ditodate'
class Encode(Func):
4546class Encode(Func):
4547    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4550class Exp(Func):
4551    pass
key = 'exp'
class Explode(Func):
4555class Explode(Func):
4556    arg_types = {"this": True, "expressions": False}
4557    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'explode'
class ExplodeOuter(Explode):
4560class ExplodeOuter(Explode):
4561    pass
key = 'explodeouter'
class Posexplode(Explode):
4564class Posexplode(Explode):
4565    pass
key = 'posexplode'
class PosexplodeOuter(Posexplode):
4568class PosexplodeOuter(Posexplode):
4569    pass
key = 'posexplodeouter'
class Floor(Func):
4572class Floor(Func):
4573    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4576class FromBase64(Func):
4577    pass
key = 'frombase64'
class ToBase64(Func):
4580class ToBase64(Func):
4581    pass
key = 'tobase64'
class Greatest(Func):
4584class Greatest(Func):
4585    arg_types = {"this": True, "expressions": False}
4586    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(AggFunc):
4589class GroupConcat(AggFunc):
4590    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4593class Hex(Func):
4594    pass
key = 'hex'
class Xor(Connector, Func):
4597class Xor(Connector, Func):
4598    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4601class If(Func):
4602    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4605class Initcap(Func):
4606    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4609class IsNan(Func):
4610    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class FormatJson(Expression):
4613class FormatJson(Expression):
4614    pass
key = 'formatjson'
class JSONKeyValue(Expression):
4617class JSONKeyValue(Expression):
4618    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4621class JSONObject(Func):
4622    arg_types = {
4623        "expressions": False,
4624        "null_handling": False,
4625        "unique_keys": False,
4626        "return_type": False,
4627        "encoding": False,
4628    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'encoding': False}
key = 'jsonobject'
class JSONArray(Func):
4632class JSONArray(Func):
4633    arg_types = {
4634        "expressions": True,
4635        "null_handling": False,
4636        "return_type": False,
4637        "strict": False,
4638    }
arg_types = {'expressions': True, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarray'
class JSONArrayAgg(Func):
4642class JSONArrayAgg(Func):
4643    arg_types = {
4644        "this": True,
4645        "order": False,
4646        "null_handling": False,
4647        "return_type": False,
4648        "strict": False,
4649    }
arg_types = {'this': True, 'order': False, 'null_handling': False, 'return_type': False, 'strict': False}
key = 'jsonarrayagg'
class JSONColumnDef(Expression):
4654class JSONColumnDef(Expression):
4655    arg_types = {"this": False, "kind": False, "path": False, "nested_schema": False}
arg_types = {'this': False, 'kind': False, 'path': False, 'nested_schema': False}
key = 'jsoncolumndef'
class JSONSchema(Expression):
4658class JSONSchema(Expression):
4659    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'jsonschema'
class JSONTable(Func):
4663class JSONTable(Func):
4664    arg_types = {
4665        "this": True,
4666        "schema": True,
4667        "path": False,
4668        "error_handling": False,
4669        "empty_handling": False,
4670    }
arg_types = {'this': True, 'schema': True, 'path': False, 'error_handling': False, 'empty_handling': False}
key = 'jsontable'
class OpenJSONColumnDef(Expression):
4673class OpenJSONColumnDef(Expression):
4674    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):
4677class OpenJSON(Func):
4678    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4681class JSONBContains(Binary):
4682    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4685class JSONExtract(Binary, Func):
4686    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4689class JSONExtractScalar(JSONExtract):
4690    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4693class JSONBExtract(JSONExtract):
4694    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4697class JSONBExtractScalar(JSONExtract):
4698    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4701class JSONFormat(Func):
4702    arg_types = {"this": False, "options": False}
4703    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4707class JSONArrayContains(Binary, Predicate, Func):
4708    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class ParseJSON(Func):
4711class ParseJSON(Func):
4712    # BigQuery, Snowflake have PARSE_JSON, Presto has JSON_PARSE
4713    _sql_names = ["PARSE_JSON", "JSON_PARSE"]
4714    arg_types = {"this": True, "expressions": False}
4715    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'parsejson'
class Least(Func):
4718class Least(Func):
4719    arg_types = {"this": True, "expressions": False}
4720    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4723class Left(Func):
4724    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4731class Length(Func):
4732    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4735class Levenshtein(Func):
4736    arg_types = {
4737        "this": True,
4738        "expression": False,
4739        "ins_cost": False,
4740        "del_cost": False,
4741        "sub_cost": False,
4742    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4745class Ln(Func):
4746    pass
key = 'ln'
class Log(Func):
4749class Log(Func):
4750    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4753class Log2(Func):
4754    pass
key = 'log2'
class Log10(Func):
4757class Log10(Func):
4758    pass
key = 'log10'
class LogicalOr(AggFunc):
4761class LogicalOr(AggFunc):
4762    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4765class LogicalAnd(AggFunc):
4766    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4769class Lower(Func):
4770    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4773class Map(Func):
4774    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4777class MapFromEntries(Func):
4778    pass
key = 'mapfromentries'
class StarMap(Func):
4781class StarMap(Func):
4782    pass
key = 'starmap'
class VarMap(Func):
4785class VarMap(Func):
4786    arg_types = {"keys": True, "values": True}
4787    is_var_len_args = True
4788
4789    @property
4790    def keys(self) -> t.List[Expression]:
4791        return self.args["keys"].expressions
4792
4793    @property
4794    def values(self) -> t.List[Expression]:
4795        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
keys: List[Expression]
values: List[Expression]
key = 'varmap'
class MatchAgainst(Func):
4799class MatchAgainst(Func):
4800    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4803class Max(AggFunc):
4804    arg_types = {"this": True, "expressions": False}
4805    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4808class MD5(Func):
4809    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4813class MD5Digest(Func):
4814    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4817class Min(AggFunc):
4818    arg_types = {"this": True, "expressions": False}
4819    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4822class Month(Func):
4823    pass
key = 'month'
class Nvl2(Func):
4826class Nvl2(Func):
4827    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Predict(Func):
4831class Predict(Func):
4832    arg_types = {"this": True, "expression": True, "params_struct": False}
arg_types = {'this': True, 'expression': True, 'params_struct': False}
key = 'predict'
class Pow(Binary, Func):
4835class Pow(Binary, Func):
4836    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4839class PercentileCont(AggFunc):
4840    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4843class PercentileDisc(AggFunc):
4844    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4847class Quantile(AggFunc):
4848    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4851class ApproxQuantile(Quantile):
4852    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):
4855class RangeN(Func):
4856    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4859class ReadCSV(Func):
4860    _sql_names = ["READ_CSV"]
4861    is_var_len_args = True
4862    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4865class Reduce(Func):
4866    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):
4869class RegexpExtract(Func):
4870    arg_types = {
4871        "this": True,
4872        "expression": True,
4873        "position": False,
4874        "occurrence": False,
4875        "parameters": False,
4876        "group": False,
4877    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4880class RegexpReplace(Func):
4881    arg_types = {
4882        "this": True,
4883        "expression": True,
4884        "replacement": True,
4885        "position": False,
4886        "occurrence": False,
4887        "parameters": False,
4888        "modifiers": False,
4889    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False, 'modifiers': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4892class RegexpLike(Binary, Func):
4893    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Binary, Func):
4896class RegexpILike(Binary, Func):
4897    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4902class RegexpSplit(Func):
4903    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4906class Repeat(Func):
4907    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4910class Round(Func):
4911    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4914class RowNumber(Func):
4915    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4918class SafeDivide(Func):
4919    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4922class SetAgg(AggFunc):
4923    pass
key = 'setagg'
class SHA(Func):
4926class SHA(Func):
4927    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4930class SHA2(Func):
4931    _sql_names = ["SHA2"]
4932    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4935class SortArray(Func):
4936    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4939class Split(Func):
4940    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4945class Substring(Func):
4946    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4949class StandardHash(Func):
4950    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4953class StartsWith(Func):
4954    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4955    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4958class StrPosition(Func):
4959    arg_types = {
4960        "this": True,
4961        "substr": True,
4962        "position": False,
4963        "instance": False,
4964    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4967class StrToDate(Func):
4968    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4971class StrToTime(Func):
4972    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4977class StrToUnix(Func):
4978    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
4983class StrToMap(Func):
4984    arg_types = {
4985        "this": True,
4986        "pair_delim": False,
4987        "key_value_delim": False,
4988        "duplicate_resolution_callback": False,
4989    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
4992class NumberToStr(Func):
4993    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
4996class FromBase(Func):
4997    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
5000class Struct(Func):
5001    arg_types = {"expressions": True}
5002    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
5005class StructExtract(Func):
5006    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Stuff(Func):
5011class Stuff(Func):
5012    _sql_names = ["STUFF", "INSERT"]
5013    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):
5016class Sum(AggFunc):
5017    pass
key = 'sum'
class Sqrt(Func):
5020class Sqrt(Func):
5021    pass
key = 'sqrt'
class Stddev(AggFunc):
5024class Stddev(AggFunc):
5025    pass
key = 'stddev'
class StddevPop(AggFunc):
5028class StddevPop(AggFunc):
5029    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
5032class StddevSamp(AggFunc):
5033    pass
key = 'stddevsamp'
class TimeToStr(Func):
5036class TimeToStr(Func):
5037    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
5040class TimeToTimeStr(Func):
5041    pass
key = 'timetotimestr'
class TimeToUnix(Func):
5044class TimeToUnix(Func):
5045    pass
key = 'timetounix'
class TimeStrToDate(Func):
5048class TimeStrToDate(Func):
5049    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
5052class TimeStrToTime(Func):
5053    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
5056class TimeStrToUnix(Func):
5057    pass
key = 'timestrtounix'
class Trim(Func):
5060class Trim(Func):
5061    arg_types = {
5062        "this": True,
5063        "expression": False,
5064        "position": False,
5065        "collation": False,
5066    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
5069class TsOrDsAdd(Func, TimeUnit):
5070    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
5073class TsOrDsToDateStr(Func):
5074    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
5077class TsOrDsToDate(Func):
5078    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
5081class TsOrDiToDi(Func):
5082    pass
key = 'tsorditodi'
class Unhex(Func):
5085class Unhex(Func):
5086    pass
key = 'unhex'
class UnixToStr(Func):
5089class UnixToStr(Func):
5090    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
5095class UnixToTime(Func):
5096    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
5097
5098    SECONDS = Literal.string("seconds")
5099    MILLIS = Literal.string("millis")
5100    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):
5103class UnixToTimeStr(Func):
5104    pass
key = 'unixtotimestr'
class Upper(Func):
5107class Upper(Func):
5108    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
5111class Variance(AggFunc):
5112    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
5115class VariancePop(AggFunc):
5116    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
5119class Week(Func):
5120    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
5123class XMLTable(Func):
5124    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):
5127class Year(Func):
5128    pass
key = 'year'
class Use(Expression):
5131class Use(Expression):
5132    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
5135class Merge(Expression):
5136    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):
5139class When(Func):
5140    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):
5145class NextValueFor(Func):
5146    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'Abs'>, <class 'AnyValue'>, <class 'ApproxDistinct'>, <class 'ApproxQuantile'>, <class 'Array'>, <class 'ArrayAgg'>, <class 'ArrayAll'>, <class 'ArrayAny'>, <class 'ArrayConcat'>, <class 'ArrayContains'>, <class 'ArrayFilter'>, <class 'ArrayJoin'>, <class 'ArraySize'>, <class 'ArraySort'>, <class 'ArraySum'>, <class 'ArrayUnionAgg'>, <class 'Avg'>, <class 'Case'>, <class 'Cast'>, <class 'CastToStrType'>, <class 'Ceil'>, <class 'Chr'>, <class 'Coalesce'>, <class 'Collate'>, <class 'Concat'>, <class 'ConcatWs'>, <class 'Count'>, <class 'CountIf'>, <class 'CurrentDate'>, <class 'CurrentDatetime'>, <class 'CurrentTime'>, <class 'CurrentTimestamp'>, <class 'CurrentUser'>, <class 'Date'>, <class 'DateAdd'>, <class 'DateDiff'>, <class 'DateFromParts'>, <class 'DateStrToDate'>, <class 'DateSub'>, <class 'DateToDateStr'>, <class 'DateToDi'>, <class 'DateTrunc'>, <class 'DatetimeAdd'>, <class 'DatetimeDiff'>, <class 'DatetimeSub'>, <class 'DatetimeTrunc'>, <class 'Day'>, <class 'DayOfMonth'>, <class 'DayOfWeek'>, <class 'DayOfYear'>, <class 'Decode'>, <class 'DiToDate'>, <class 'Encode'>, <class 'Exp'>, <class 'Explode'>, <class 'ExplodeOuter'>, <class 'Extract'>, <class 'First'>, <class 'Flatten'>, <class 'Floor'>, <class 'FromBase'>, <class 'FromBase64'>, <class 'GenerateSeries'>, <class 'Greatest'>, <class 'GroupConcat'>, <class 'Hex'>, <class 'Hll'>, <class 'If'>, <class 'Initcap'>, <class 'IsNan'>, <class 'JSONArray'>, <class 'JSONArrayAgg'>, <class 'JSONArrayContains'>, <class 'JSONBExtract'>, <class 'JSONBExtractScalar'>, <class 'JSONExtract'>, <class 'JSONExtractScalar'>, <class 'JSONFormat'>, <class 'JSONObject'>, <class 'JSONTable'>, <class 'Last'>, <class 'LastDateOfMonth'>, <class 'Least'>, <class 'Left'>, <class 'Length'>, <class 'Levenshtein'>, <class 'Ln'>, <class 'Log'>, <class 'Log10'>, <class 'Log2'>, <class 'LogicalAnd'>, <class 'LogicalOr'>, <class 'Lower'>, <class 'MD5'>, <class 'MD5Digest'>, <class 'Map'>, <class 'MapFromEntries'>, <class 'MatchAgainst'>, <class 'Max'>, <class 'Min'>, <class 'Month'>, <class 'MonthsBetween'>, <class 'NextValueFor'>, <class 'NumberToStr'>, <class 'Nvl2'>, <class 'OpenJSON'>, <class 'ParameterizedAgg'>, <class 'ParseJSON'>, <class 'PercentileCont'>, <class 'PercentileDisc'>, <class 'Posexplode'>, <class 'PosexplodeOuter'>, <class 'Pow'>, <class 'Predict'>, <class 'Quantile'>, <class 'RangeN'>, <class 'ReadCSV'>, <class 'Reduce'>, <class 'RegexpExtract'>, <class 'RegexpILike'>, <class 'RegexpLike'>, <class 'RegexpReplace'>, <class 'RegexpSplit'>, <class 'Repeat'>, <class 'Right'>, <class 'Round'>, <class 'RowNumber'>, <class 'SHA'>, <class 'SHA2'>, <class 'SafeConcat'>, <class 'SafeDivide'>, <class 'SetAgg'>, <class 'SortArray'>, <class 'Split'>, <class 'Sqrt'>, <class 'StandardHash'>, <class 'StarMap'>, <class 'StartsWith'>, <class 'Stddev'>, <class 'StddevPop'>, <class 'StddevSamp'>, <class 'StrPosition'>, <class 'StrToDate'>, <class 'StrToMap'>, <class 'StrToTime'>, <class 'StrToUnix'>, <class 'Struct'>, <class 'StructExtract'>, <class 'Stuff'>, <class 'Substring'>, <class 'Sum'>, <class 'TimeAdd'>, <class 'TimeDiff'>, <class 'TimeStrToDate'>, <class 'TimeStrToTime'>, <class 'TimeStrToUnix'>, <class 'TimeSub'>, <class 'TimeToStr'>, <class 'TimeToTimeStr'>, <class 'TimeToUnix'>, <class 'TimeTrunc'>, <class 'Timestamp'>, <class 'TimestampAdd'>, <class 'TimestampDiff'>, <class 'TimestampSub'>, <class 'TimestampTrunc'>, <class 'ToBase64'>, <class 'ToChar'>, <class 'ToDays'>, <class 'Transform'>, <class 'Trim'>, <class 'TryCast'>, <class 'TsOrDiToDi'>, <class 'TsOrDsAdd'>, <class 'TsOrDsToDate'>, <class 'TsOrDsToDateStr'>, <class 'Unhex'>, <class 'UnixToStr'>, <class 'UnixToTime'>, <class 'UnixToTimeStr'>, <class 'Upper'>, <class 'VarMap'>, <class 'Variance'>, <class 'VariancePop'>, <class 'Week'>, <class 'WeekOfYear'>, <class 'When'>, <class 'XMLTable'>, <class 'Xor'>, <class 'Year'>]
def maybe_parse( sql_or_expression: Union[str, Expression], *, into: Union[str, Type[Expression], Collection[Union[str, Type[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) -> Expression:
5183def maybe_parse(
5184    sql_or_expression: ExpOrStr,
5185    *,
5186    into: t.Optional[IntoType] = None,
5187    dialect: DialectType = None,
5188    prefix: t.Optional[str] = None,
5189    copy: bool = False,
5190    **opts,
5191) -> Expression:
5192    """Gracefully handle a possible string or expression.
5193
5194    Example:
5195        >>> maybe_parse("1")
5196        (LITERAL this: 1, is_string: False)
5197        >>> maybe_parse(to_identifier("x"))
5198        (IDENTIFIER this: x, quoted: False)
5199
5200    Args:
5201        sql_or_expression: the SQL code string or an expression
5202        into: the SQLGlot Expression to parse into
5203        dialect: the dialect used to parse the input expressions (in the case that an
5204            input expression is a SQL string).
5205        prefix: a string to prefix the sql with before it gets parsed
5206            (automatically includes a space)
5207        copy: whether or not to copy the expression.
5208        **opts: other options to use to parse the input expressions (again, in the case
5209            that an input expression is a SQL string).
5210
5211    Returns:
5212        Expression: the parsed or given expression.
5213    """
5214    if isinstance(sql_or_expression, Expression):
5215        if copy:
5216            return sql_or_expression.copy()
5217        return sql_or_expression
5218
5219    if sql_or_expression is None:
5220        raise ParseError(f"SQL cannot be None")
5221
5222    import sqlglot
5223
5224    sql = str(sql_or_expression)
5225    if prefix:
5226        sql = f"{prefix} {sql}"
5227
5228    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):
5241def maybe_copy(instance, copy=True):
5242    return instance.copy() if copy and instance else instance
def union( left: Union[str, Expression], right: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Union:
5423def union(
5424    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5425) -> Union:
5426    """
5427    Initializes a syntax tree from one UNION expression.
5428
5429    Example:
5430        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5431        'SELECT * FROM foo UNION SELECT * FROM bla'
5432
5433    Args:
5434        left: the SQL code string corresponding to the left-hand side.
5435            If an `Expression` instance is passed, it will be used as-is.
5436        right: the SQL code string corresponding to the right-hand side.
5437            If an `Expression` instance is passed, it will be used as-is.
5438        distinct: set the DISTINCT flag if and only if this is true.
5439        dialect: the dialect used to parse the input expression.
5440        opts: other options to use to parse the input expressions.
5441
5442    Returns:
5443        The new Union instance.
5444    """
5445    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5446    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5447
5448    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, Expression], right: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Intersect:
5451def intersect(
5452    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5453) -> Intersect:
5454    """
5455    Initializes a syntax tree from one INTERSECT expression.
5456
5457    Example:
5458        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5459        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5460
5461    Args:
5462        left: the SQL code string corresponding to the left-hand side.
5463            If an `Expression` instance is passed, it will be used as-is.
5464        right: the SQL code string corresponding to the right-hand side.
5465            If an `Expression` instance is passed, it will be used as-is.
5466        distinct: set the DISTINCT flag if and only if this is true.
5467        dialect: the dialect used to parse the input expression.
5468        opts: other options to use to parse the input expressions.
5469
5470    Returns:
5471        The new Intersect instance.
5472    """
5473    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5474    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5475
5476    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, Expression], right: Union[str, Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Except:
5479def except_(
5480    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5481) -> Except:
5482    """
5483    Initializes a syntax tree from one EXCEPT expression.
5484
5485    Example:
5486        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5487        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5488
5489    Args:
5490        left: the SQL code string corresponding to the left-hand side.
5491            If an `Expression` instance is passed, it will be used as-is.
5492        right: the SQL code string corresponding to the right-hand side.
5493            If an `Expression` instance is passed, it will be used as-is.
5494        distinct: set the DISTINCT flag if and only if this is true.
5495        dialect: the dialect used to parse the input expression.
5496        opts: other options to use to parse the input expressions.
5497
5498    Returns:
5499        The new Except instance.
5500    """
5501    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5502    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5503
5504    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, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Select:
5507def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5508    """
5509    Initializes a syntax tree from one or multiple SELECT expressions.
5510
5511    Example:
5512        >>> select("col1", "col2").from_("tbl").sql()
5513        'SELECT col1, col2 FROM tbl'
5514
5515    Args:
5516        *expressions: the SQL code string to parse as the expressions of a
5517            SELECT statement. If an Expression instance is passed, this is used as-is.
5518        dialect: the dialect used to parse the input expressions (in the case that an
5519            input expression is a SQL string).
5520        **opts: other options to use to parse the input expressions (again, in the case
5521            that an input expression is a SQL string).
5522
5523    Returns:
5524        Select: the syntax tree for the SELECT statement.
5525    """
5526    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, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Select:
5529def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5530    """
5531    Initializes a syntax tree from a FROM expression.
5532
5533    Example:
5534        >>> from_("tbl").select("col1", "col2").sql()
5535        'SELECT col1, col2 FROM tbl'
5536
5537    Args:
5538        *expression: the SQL code string to parse as the FROM expressions of a
5539            SELECT statement. If an Expression instance is passed, this is used as-is.
5540        dialect: the dialect used to parse the input expression (in the case that the
5541            input expression is a SQL string).
5542        **opts: other options to use to parse the input expressions (again, in the case
5543            that the input expression is a SQL string).
5544
5545    Returns:
5546        Select: the syntax tree for the SELECT statement.
5547    """
5548    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 | Table, properties: dict, where: Union[str, Expression, NoneType] = None, from_: Union[str, Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Update:
5551def update(
5552    table: str | Table,
5553    properties: dict,
5554    where: t.Optional[ExpOrStr] = None,
5555    from_: t.Optional[ExpOrStr] = None,
5556    dialect: DialectType = None,
5557    **opts,
5558) -> Update:
5559    """
5560    Creates an update statement.
5561
5562    Example:
5563        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5564        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5565
5566    Args:
5567        *properties: dictionary of properties to set which are
5568            auto converted to sql objects eg None -> NULL
5569        where: sql conditional parsed into a WHERE statement
5570        from_: sql statement parsed into a FROM statement
5571        dialect: the dialect used to parse the input expressions.
5572        **opts: other options to use to parse the input expressions.
5573
5574    Returns:
5575        Update: the syntax tree for the UPDATE statement.
5576    """
5577    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5578    update_expr.set(
5579        "expressions",
5580        [
5581            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5582            for k, v in properties.items()
5583        ],
5584    )
5585    if from_:
5586        update_expr.set(
5587            "from",
5588            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5589        )
5590    if isinstance(where, Condition):
5591        where = Where(this=where)
5592    if where:
5593        update_expr.set(
5594            "where",
5595            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5596        )
5597    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, Expression], where: Union[str, Expression, NoneType] = None, returning: Union[str, Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Delete:
5600def delete(
5601    table: ExpOrStr,
5602    where: t.Optional[ExpOrStr] = None,
5603    returning: t.Optional[ExpOrStr] = None,
5604    dialect: DialectType = None,
5605    **opts,
5606) -> Delete:
5607    """
5608    Builds a delete statement.
5609
5610    Example:
5611        >>> delete("my_table", where="id > 1").sql()
5612        'DELETE FROM my_table WHERE id > 1'
5613
5614    Args:
5615        where: sql conditional parsed into a WHERE statement
5616        returning: sql conditional parsed into a RETURNING statement
5617        dialect: the dialect used to parse the input expressions.
5618        **opts: other options to use to parse the input expressions.
5619
5620    Returns:
5621        Delete: the syntax tree for the DELETE statement.
5622    """
5623    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5624    if where:
5625        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5626    if returning:
5627        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5628    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, Expression], into: Union[str, Expression], columns: Optional[Sequence[Union[str, Expression]]] = None, overwrite: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Insert:
5631def insert(
5632    expression: ExpOrStr,
5633    into: ExpOrStr,
5634    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5635    overwrite: t.Optional[bool] = None,
5636    dialect: DialectType = None,
5637    copy: bool = True,
5638    **opts,
5639) -> Insert:
5640    """
5641    Builds an INSERT statement.
5642
5643    Example:
5644        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5645        'INSERT INTO tbl VALUES (1, 2, 3)'
5646
5647    Args:
5648        expression: the sql string or expression of the INSERT statement
5649        into: the tbl to insert data to.
5650        columns: optionally the table's column names.
5651        overwrite: whether to INSERT OVERWRITE or not.
5652        dialect: the dialect used to parse the input expressions.
5653        copy: whether or not to copy the expression.
5654        **opts: other options to use to parse the input expressions.
5655
5656    Returns:
5657        Insert: the syntax tree for the INSERT statement.
5658    """
5659    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5660    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5661
5662    if columns:
5663        this = _apply_list_builder(
5664            *columns,
5665            instance=Schema(this=this),
5666            arg="expressions",
5667            into=Identifier,
5668            copy=False,
5669            dialect=dialect,
5670            **opts,
5671        )
5672
5673    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, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
5676def condition(
5677    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5678) -> Condition:
5679    """
5680    Initialize a logical condition expression.
5681
5682    Example:
5683        >>> condition("x=1").sql()
5684        'x = 1'
5685
5686        This is helpful for composing larger logical syntax trees:
5687        >>> where = condition("x=1")
5688        >>> where = where.and_("y=1")
5689        >>> Select().from_("tbl").select("*").where(where).sql()
5690        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5691
5692    Args:
5693        *expression: the SQL code string to parse.
5694            If an Expression instance is passed, this is used as-is.
5695        dialect: the dialect used to parse the input expression (in the case that the
5696            input expression is a SQL string).
5697        copy: Whether or not to copy `expression` (only applies to expressions).
5698        **opts: other options to use to parse the input expressions (again, in the case
5699            that the input expression is a SQL string).
5700
5701    Returns:
5702        The new Condition instance
5703    """
5704    return maybe_parse(
5705        expression,
5706        into=Condition,
5707        dialect=dialect,
5708        copy=copy,
5709        **opts,
5710    )

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, Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
5713def and_(
5714    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5715) -> Condition:
5716    """
5717    Combine multiple conditions with an AND logical operator.
5718
5719    Example:
5720        >>> and_("x=1", and_("y=1", "z=1")).sql()
5721        'x = 1 AND (y = 1 AND z = 1)'
5722
5723    Args:
5724        *expressions: the SQL code strings to parse.
5725            If an Expression instance is passed, this is used as-is.
5726        dialect: the dialect used to parse the input expression.
5727        copy: whether or not to copy `expressions` (only applies to Expressions).
5728        **opts: other options to use to parse the input expressions.
5729
5730    Returns:
5731        And: the new condition
5732    """
5733    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, Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Condition:
5736def or_(
5737    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5738) -> Condition:
5739    """
5740    Combine multiple conditions with an OR logical operator.
5741
5742    Example:
5743        >>> or_("x=1", or_("y=1", "z=1")).sql()
5744        'x = 1 OR (y = 1 OR z = 1)'
5745
5746    Args:
5747        *expressions: the SQL code strings to parse.
5748            If an Expression instance is passed, this is used as-is.
5749        dialect: the dialect used to parse the input expression.
5750        copy: whether or not to copy `expressions` (only applies to Expressions).
5751        **opts: other options to use to parse the input expressions.
5752
5753    Returns:
5754        Or: the new condition
5755    """
5756    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, Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> Not:
5759def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5760    """
5761    Wrap a condition with a NOT operator.
5762
5763    Example:
5764        >>> not_("this_suit='black'").sql()
5765        "NOT this_suit = 'black'"
5766
5767    Args:
5768        expression: the SQL code string to parse.
5769            If an Expression instance is passed, this is used as-is.
5770        dialect: the dialect used to parse the input expression.
5771        copy: whether to copy the expression or not.
5772        **opts: other options to use to parse the input expressions.
5773
5774    Returns:
5775        The new condition.
5776    """
5777    this = condition(
5778        expression,
5779        dialect=dialect,
5780        copy=copy,
5781        **opts,
5782    )
5783    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, Expression], copy: bool = True) -> Paren:
5786def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5787    """
5788    Wrap an expression in parentheses.
5789
5790    Example:
5791        >>> paren("5 + 3").sql()
5792        '(5 + 3)'
5793
5794    Args:
5795        expression: the SQL code string to parse.
5796            If an Expression instance is passed, this is used as-is.
5797        copy: whether to copy the expression or not.
5798
5799    Returns:
5800        The wrapped expression.
5801    """
5802    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):
5820def to_identifier(name, quoted=None, copy=True):
5821    """Builds an identifier.
5822
5823    Args:
5824        name: The name to turn into an identifier.
5825        quoted: Whether or not force quote the identifier.
5826        copy: Whether or not to copy a passed in Identefier node.
5827
5828    Returns:
5829        The identifier ast node.
5830    """
5831
5832    if name is None:
5833        return None
5834
5835    if isinstance(name, Identifier):
5836        identifier = maybe_copy(name, copy)
5837    elif isinstance(name, str):
5838        identifier = Identifier(
5839            this=name,
5840            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5841        )
5842    else:
5843        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5844    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 | Literal) -> Interval:
5850def to_interval(interval: str | Literal) -> Interval:
5851    """Builds an interval expression from a string like '1 day' or '5 months'."""
5852    if isinstance(interval, Literal):
5853        if not interval.is_string:
5854            raise ValueError("Invalid interval string.")
5855
5856        interval = interval.this
5857
5858    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5859
5860    if not interval_parts:
5861        raise ValueError("Invalid interval string.")
5862
5863    return Interval(
5864        this=Literal.string(interval_parts.group(1)),
5865        unit=Var(this=interval_parts.group(2)),
5866    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, Table, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Optional[Table]:
5879def to_table(
5880    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5881) -> t.Optional[Table]:
5882    """
5883    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5884    If a table is passed in then that table is returned.
5885
5886    Args:
5887        sql_path: a `[catalog].[schema].[table]` string.
5888        dialect: the source dialect according to which the table name will be parsed.
5889        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5890
5891    Returns:
5892        A table expression.
5893    """
5894    if sql_path is None or isinstance(sql_path, Table):
5895        return sql_path
5896    if not isinstance(sql_path, str):
5897        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5898
5899    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5900    if table:
5901        for k, v in kwargs.items():
5902            table.set(k, v)
5903
5904    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 | Column, **kwargs) -> Column:
5907def to_column(sql_path: str | Column, **kwargs) -> Column:
5908    """
5909    Create a column from a `[table].[column]` sql path. Schema is optional.
5910
5911    If a column is passed in then that column is returned.
5912
5913    Args:
5914        sql_path: `[table].[column]` string
5915    Returns:
5916        Table: A column expression
5917    """
5918    if sql_path is None or isinstance(sql_path, Column):
5919        return sql_path
5920    if not isinstance(sql_path, str):
5921        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5922    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, Expression], alias: str | Identifier, table: Union[bool, Sequence[str | Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts):
5925def alias_(
5926    expression: ExpOrStr,
5927    alias: str | Identifier,
5928    table: bool | t.Sequence[str | Identifier] = False,
5929    quoted: t.Optional[bool] = None,
5930    dialect: DialectType = None,
5931    copy: bool = True,
5932    **opts,
5933):
5934    """Create an Alias expression.
5935
5936    Example:
5937        >>> alias_('foo', 'bar').sql()
5938        'foo AS bar'
5939
5940        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5941        '(SELECT 1, 2) AS bar(a, b)'
5942
5943    Args:
5944        expression: the SQL code strings to parse.
5945            If an Expression instance is passed, this is used as-is.
5946        alias: the alias name to use. If the name has
5947            special characters it is quoted.
5948        table: Whether or not to create a table alias, can also be a list of columns.
5949        quoted: whether or not to quote the alias
5950        dialect: the dialect used to parse the input expression.
5951        copy: Whether or not to copy the expression.
5952        **opts: other options to use to parse the input expressions.
5953
5954    Returns:
5955        Alias: the aliased expression
5956    """
5957    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5958    alias = to_identifier(alias, quoted=quoted)
5959
5960    if table:
5961        table_alias = TableAlias(this=alias)
5962        exp.set("alias", table_alias)
5963
5964        if not isinstance(table, bool):
5965            for column in table:
5966                table_alias.append("columns", to_identifier(column, quoted=quoted))
5967
5968        return exp
5969
5970    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5971    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5972    # for the complete Window expression.
5973    #
5974    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5975
5976    if "alias" in exp.arg_types and not isinstance(exp, Window):
5977        exp.set("alias", alias)
5978        return exp
5979    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, Expression], alias: Union[Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> Select:
5982def subquery(
5983    expression: ExpOrStr,
5984    alias: t.Optional[Identifier | str] = None,
5985    dialect: DialectType = None,
5986    **opts,
5987) -> Select:
5988    """
5989    Build a subquery expression.
5990
5991    Example:
5992        >>> subquery('select x from tbl', 'bar').select('x').sql()
5993        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5994
5995    Args:
5996        expression: the SQL code strings to parse.
5997            If an Expression instance is passed, this is used as-is.
5998        alias: the alias name to use.
5999        dialect: the dialect used to parse the input expression.
6000        **opts: other options to use to parse the input expressions.
6001
6002    Returns:
6003        A new Select instance with the subquery expression included.
6004    """
6005
6006    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
6007    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 | Identifier, table: Union[Identifier, str, NoneType] = None, db: Union[Identifier, str, NoneType] = None, catalog: Union[Identifier, str, NoneType] = None, quoted: Optional[bool] = None) -> Column:
6010def column(
6011    col: str | Identifier,
6012    table: t.Optional[str | Identifier] = None,
6013    db: t.Optional[str | Identifier] = None,
6014    catalog: t.Optional[str | Identifier] = None,
6015    quoted: t.Optional[bool] = None,
6016) -> Column:
6017    """
6018    Build a Column.
6019
6020    Args:
6021        col: Column name.
6022        table: Table name.
6023        db: Database name.
6024        catalog: Catalog name.
6025        quoted: Whether to force quotes on the column's identifiers.
6026
6027    Returns:
6028        The new Column instance.
6029    """
6030    return Column(
6031        this=to_identifier(col, quoted=quoted),
6032        table=to_identifier(table, quoted=quoted),
6033        db=to_identifier(db, quoted=quoted),
6034        catalog=to_identifier(catalog, quoted=quoted),
6035    )

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, Expression], to: str | DataType | DataType.Type, **opts) -> Cast:
6038def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
6039    """Cast an expression to a data type.
6040
6041    Example:
6042        >>> cast('x + 1', 'int').sql()
6043        'CAST(x + 1 AS INT)'
6044
6045    Args:
6046        expression: The expression to cast.
6047        to: The datatype to cast to.
6048
6049    Returns:
6050        The new Cast instance.
6051    """
6052    expression = maybe_parse(expression, **opts)
6053    data_type = DataType.build(to, **opts)
6054    expression = Cast(this=expression, to=data_type)
6055    expression.type = data_type
6056    return expression

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: Identifier | str, db: Union[Identifier, str, NoneType] = None, catalog: Union[Identifier, str, NoneType] = None, quoted: Optional[bool] = None, alias: Union[Identifier, str, NoneType] = None) -> Table:
6059def table_(
6060    table: Identifier | str,
6061    db: t.Optional[Identifier | str] = None,
6062    catalog: t.Optional[Identifier | str] = None,
6063    quoted: t.Optional[bool] = None,
6064    alias: t.Optional[Identifier | str] = None,
6065) -> Table:
6066    """Build a Table.
6067
6068    Args:
6069        table: Table name.
6070        db: Database name.
6071        catalog: Catalog name.
6072        quote: Whether to force quotes on the table's identifiers.
6073        alias: Table's alias.
6074
6075    Returns:
6076        The new Table instance.
6077    """
6078    return Table(
6079        this=to_identifier(table, quoted=quoted) if table else None,
6080        db=to_identifier(db, quoted=quoted) if db else None,
6081        catalog=to_identifier(catalog, quoted=quoted) if catalog else None,
6082        alias=TableAlias(this=to_identifier(alias)) if alias else None,
6083    )

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, DataType], NoneType] = None) -> Values:
6086def values(
6087    values: t.Iterable[t.Tuple[t.Any, ...]],
6088    alias: t.Optional[str] = None,
6089    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
6090) -> Values:
6091    """Build VALUES statement.
6092
6093    Example:
6094        >>> values([(1, '2')]).sql()
6095        "VALUES (1, '2')"
6096
6097    Args:
6098        values: values statements that will be converted to SQL
6099        alias: optional alias
6100        columns: Optional list of ordered column names or ordered dictionary of column names to types.
6101         If either are provided then an alias is also required.
6102
6103    Returns:
6104        Values: the Values expression object
6105    """
6106    if columns and not alias:
6107        raise ValueError("Alias is required when providing columns")
6108
6109    return Values(
6110        expressions=[convert(tup) for tup in values],
6111        alias=(
6112            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
6113            if columns
6114            else (TableAlias(this=to_identifier(alias)) if alias else None)
6115        ),
6116    )

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, Expression, NoneType]) -> Var:
6119def var(name: t.Optional[ExpOrStr]) -> Var:
6120    """Build a SQL variable.
6121
6122    Example:
6123        >>> repr(var('x'))
6124        '(VAR this: x)'
6125
6126        >>> repr(var(column('x', table='y')))
6127        '(VAR this: x)'
6128
6129    Args:
6130        name: The name of the var or an expression who's name will become the var.
6131
6132    Returns:
6133        The new variable node.
6134    """
6135    if not name:
6136        raise ValueError("Cannot convert empty name into var.")
6137
6138    if isinstance(name, Expression):
6139        name = name.name
6140    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 | Table, new_name: str | Table) -> AlterTable:
6143def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
6144    """Build ALTER TABLE... RENAME... expression
6145
6146    Args:
6147        old_name: The old name of the table
6148        new_name: The new name of the table
6149
6150    Returns:
6151        Alter table expression
6152    """
6153    old_table = to_table(old_name)
6154    new_table = to_table(new_name)
6155    return AlterTable(
6156        this=old_table,
6157        actions=[
6158            RenameTable(this=new_table),
6159        ],
6160    )

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) -> Expression:
6163def convert(value: t.Any, copy: bool = False) -> Expression:
6164    """Convert a python value into an expression object.
6165
6166    Raises an error if a conversion is not possible.
6167
6168    Args:
6169        value: A python object.
6170        copy: Whether or not to copy `value` (only applies to Expressions and collections).
6171
6172    Returns:
6173        Expression: the equivalent expression object.
6174    """
6175    if isinstance(value, Expression):
6176        return maybe_copy(value, copy)
6177    if isinstance(value, str):
6178        return Literal.string(value)
6179    if isinstance(value, bool):
6180        return Boolean(this=value)
6181    if value is None or (isinstance(value, float) and math.isnan(value)):
6182        return NULL
6183    if isinstance(value, numbers.Number):
6184        return Literal.number(value)
6185    if isinstance(value, datetime.datetime):
6186        datetime_literal = Literal.string(
6187            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
6188        )
6189        return TimeStrToTime(this=datetime_literal)
6190    if isinstance(value, datetime.date):
6191        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
6192        return DateStrToDate(this=date_literal)
6193    if isinstance(value, tuple):
6194        return Tuple(expressions=[convert(v, copy=copy) for v in value])
6195    if isinstance(value, list):
6196        return Array(expressions=[convert(v, copy=copy) for v in value])
6197    if isinstance(value, dict):
6198        return Map(
6199            keys=Array(expressions=[convert(k, copy=copy) for k in value]),
6200            values=Array(expressions=[convert(v, copy=copy) for v in value.values()]),
6201        )
6202    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: Expression, fun: Callable, *args, **kwargs) -> None:
6205def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
6206    """
6207    Replace children of an expression with the result of a lambda fun(child) -> exp.
6208    """
6209    for k, v in expression.args.items():
6210        is_list_arg = type(v) is list
6211
6212        child_nodes = v if is_list_arg else [v]
6213        new_child_nodes = []
6214
6215        for cn in child_nodes:
6216            if isinstance(cn, Expression):
6217                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
6218                    new_child_nodes.append(child_node)
6219                    child_node.parent = expression
6220                    child_node.arg_key = k
6221            else:
6222                new_child_nodes.append(cn)
6223
6224        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: Expression, exclude: str = '') -> Set[str]:
6227def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
6228    """
6229    Return all table names referenced through columns in an expression.
6230
6231    Example:
6232        >>> import sqlglot
6233        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
6234        ['a', 'c']
6235
6236    Args:
6237        expression: expression to find table names.
6238        exclude: a table name to exclude
6239
6240    Returns:
6241        A list of unique names.
6242    """
6243    return {
6244        table
6245        for table in (column.table for column in expression.find_all(Column))
6246        if table and table != exclude
6247    }

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: Table | str, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) -> str:
6250def table_name(table: Table | str, dialect: DialectType = None) -> str:
6251    """Get the full name of a table as a string.
6252
6253    Args:
6254        table: Table expression node or string.
6255        dialect: The dialect to generate the table name for.
6256
6257    Examples:
6258        >>> from sqlglot import exp, parse_one
6259        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
6260        'a.b.c'
6261
6262    Returns:
6263        The table name.
6264    """
6265
6266    table = maybe_parse(table, into=Table, dialect=dialect)
6267
6268    if not table:
6269        raise ValueError(f"Cannot parse {table}")
6270
6271    return ".".join(
6272        part.sql(dialect=dialect, identify=True)
6273        if not SAFE_IDENTIFIER_RE.match(part.name)
6274        else part.name
6275        for part in table.parts
6276    )

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:
6279def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
6280    """Replace all tables in expression according to the mapping.
6281
6282    Args:
6283        expression: expression node to be transformed and replaced.
6284        mapping: mapping of table names.
6285        copy: whether or not to copy the expression.
6286
6287    Examples:
6288        >>> from sqlglot import exp, parse_one
6289        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
6290        'SELECT * FROM c'
6291
6292    Returns:
6293        The mapped expression.
6294    """
6295
6296    def _replace_tables(node: Expression) -> Expression:
6297        if isinstance(node, Table):
6298            new_name = mapping.get(table_name(node))
6299            if new_name:
6300                return to_table(
6301                    new_name,
6302                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
6303                )
6304        return node
6305
6306    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: Expression, *args, **kwargs) -> Expression:
6309def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
6310    """Replace placeholders in an expression.
6311
6312    Args:
6313        expression: expression node to be transformed and replaced.
6314        args: positional names that will substitute unnamed placeholders in the given order.
6315        kwargs: keyword arguments that will substitute named placeholders.
6316
6317    Examples:
6318        >>> from sqlglot import exp, parse_one
6319        >>> replace_placeholders(
6320        ...     parse_one("select * from :tbl where ? = ?"),
6321        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
6322        ... ).sql()
6323        "SELECT * FROM foo WHERE str_col = 'b'"
6324
6325    Returns:
6326        The mapped expression.
6327    """
6328
6329    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
6330        if isinstance(node, Placeholder):
6331            if node.name:
6332                new_name = kwargs.get(node.name)
6333                if new_name:
6334                    return convert(new_name)
6335            else:
6336                try:
6337                    return convert(next(args))
6338                except StopIteration:
6339                    pass
6340        return node
6341
6342    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: Expression, sources: Dict[str, Subqueryable], copy: bool = True) -> Expression:
6345def expand(
6346    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
6347) -> Expression:
6348    """Transforms an expression by expanding all referenced sources into subqueries.
6349
6350    Examples:
6351        >>> from sqlglot import parse_one
6352        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
6353        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
6354
6355        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
6356        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
6357
6358    Args:
6359        expression: The expression to expand.
6360        sources: A dictionary of name to Subqueryables.
6361        copy: Whether or not to copy the expression during transformation. Defaults to True.
6362
6363    Returns:
6364        The transformed expression.
6365    """
6366
6367    def _expand(node: Expression):
6368        if isinstance(node, Table):
6369            name = table_name(node)
6370            source = sources.get(name)
6371            if source:
6372                subquery = source.subquery(node.alias or name)
6373                subquery.comments = [f"source: {name}"]
6374                return subquery.transform(_expand, copy=False)
6375        return node
6376
6377    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) -> Func:
6380def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6381    """
6382    Returns a Func expression.
6383
6384    Examples:
6385        >>> func("abs", 5).sql()
6386        'ABS(5)'
6387
6388        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6389        'CAST(5 AS DOUBLE)'
6390
6391    Args:
6392        name: the name of the function to build.
6393        args: the args used to instantiate the function of interest.
6394        dialect: the source dialect.
6395        kwargs: the kwargs used to instantiate the function of interest.
6396
6397    Note:
6398        The arguments `args` and `kwargs` are mutually exclusive.
6399
6400    Returns:
6401        An instance of the function of interest, or an anonymous function, if `name` doesn't
6402        correspond to an existing `sqlglot.expressions.Func` class.
6403    """
6404    if args and kwargs:
6405        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6406
6407    from sqlglot.dialects.dialect import Dialect
6408
6409    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6410    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6411
6412    parser = Dialect.get_or_raise(dialect)().parser()
6413    from_args_list = parser.FUNCTIONS.get(name.upper())
6414
6415    if from_args_list:
6416        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6417    else:
6418        kwargs = kwargs or {"expressions": converted}
6419        function = Anonymous(this=name, **kwargs)
6420
6421    for error_message in function.error_messages(converted):
6422        raise ValueError(error_message)
6423
6424    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 Func class.

def true() -> Boolean:
6427def true() -> Boolean:
6428    """
6429    Returns a true Boolean expression.
6430    """
6431    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> Boolean:
6434def false() -> Boolean:
6435    """
6436    Returns a false Boolean expression.
6437    """
6438    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> Null:
6441def null() -> Null:
6442    """
6443    Returns a Null expression.
6444    """
6445    return Null()

Returns a Null expression.

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