Edit on GitHub

Expressions

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

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


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

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

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

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

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

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

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

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

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

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

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

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

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

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

Returns a deep copy of the expression.

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

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

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

Sets arg_key to value.

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

Returns the depth of this tree.

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

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

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

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

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

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

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

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

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

The generator object.

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

Returns a nearest parent matching expression_types.

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

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

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

Returns the root expression of this tree.

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

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

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

the generator object.

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

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

Returns:

The generator object.

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

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

Returns:

The generator object.

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

Returns the first non parenthesis child or self.

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

Returns the inner expression if this is an Alias.

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

Returns unnested operands as a tuple.

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

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

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

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

Returns SQL string representation of this tree.

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

The SQL string.

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

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

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

The transformed tree.

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

Swap out this expression with a new expression.

For example::

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

The new expression or expressions.

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

Remove this expression from its AST.

Returns:

The popped expression.

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

Assert that this Expression is an instance of type_.

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

Examples:

This is useful for type security in chained expressions:

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

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

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

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

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

Dump this Expression to a JSON-serializable dict.

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

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

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

AND this condition with one or multiple expressions.

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

The new And condition.

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

OR this condition with one or multiple expressions.

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

The new Or condition.

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

Wrap this condition with NOT.

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

The new Not instance.

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

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

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

Builds a UNION expression.

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

The new Union expression.

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

Builds an INTERSECT expression.

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

The new Intersect expression.

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

Builds an EXCEPT expression.

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

The new Except expression.

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

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

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

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

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

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

Converts the column into a dot expression.

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

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

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

Delete: the modified expression.

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

Append to or set the WHERE expressions.

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

Delete: the modified expression.

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

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):
1478class Drop(Expression):
1479    arg_types = {
1480        "this": False,
1481        "kind": False,
1482        "exists": False,
1483        "temporary": False,
1484        "materialized": False,
1485        "cascade": False,
1486        "constraints": False,
1487        "purge": False,
1488    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1491class Filter(Expression):
1492    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1495class Check(Expression):
1496    pass
key = 'check'
class Directory(Expression):
1499class Directory(Expression):
1500    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1501    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1504class ForeignKey(Expression):
1505    arg_types = {
1506        "expressions": True,
1507        "reference": False,
1508        "delete": False,
1509        "update": False,
1510    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1513class PrimaryKey(Expression):
1514    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1519class Into(Expression):
1520    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1523class From(Expression):
1524    @property
1525    def name(self) -> str:
1526        return self.this.name
1527
1528    @property
1529    def alias_or_name(self) -> str:
1530        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1533class Having(Expression):
1534    pass
key = 'having'
class Hint(Expression):
1537class Hint(Expression):
1538    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1541class JoinHint(Expression):
1542    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1545class Identifier(Expression):
1546    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1547
1548    @property
1549    def quoted(self) -> bool:
1550        return bool(self.args.get("quoted"))
1551
1552    @property
1553    def hashable_args(self) -> t.Any:
1554        return (self.this, self.quoted)
1555
1556    @property
1557    def output_name(self) -> str:
1558        return self.name
arg_types = {'this': True, 'quoted': False, 'global': False, 'temporary': False}
quoted: bool
hashable_args: Any
output_name: str

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

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

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

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):
1627class OnConflict(Expression):
1628    arg_types = {
1629        "duplicate": False,
1630        "expressions": False,
1631        "nothing": False,
1632        "key": False,
1633        "constraint": False,
1634    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1637class Returning(Expression):
1638    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1642class Introducer(Expression):
1643    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1647class National(Expression):
1648    pass
key = 'national'
class LoadData(Expression):
1651class LoadData(Expression):
1652    arg_types = {
1653        "this": True,
1654        "local": False,
1655        "overwrite": False,
1656        "inpath": True,
1657        "partition": False,
1658        "input_format": False,
1659        "serde": False,
1660    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1663class Partition(Expression):
1664    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1667class Fetch(Expression):
1668    arg_types = {
1669        "direction": False,
1670        "count": False,
1671        "percent": False,
1672        "with_ties": False,
1673    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1676class Group(Expression):
1677    arg_types = {
1678        "expressions": False,
1679        "grouping_sets": False,
1680        "cube": False,
1681        "rollup": False,
1682        "totals": False,
1683        "all": False,
1684    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1687class Lambda(Expression):
1688    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1691class Limit(Expression):
1692    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1695class Literal(Condition):
1696    arg_types = {"this": True, "is_string": True}
1697
1698    @property
1699    def hashable_args(self) -> t.Any:
1700        return (self.this, self.args.get("is_string"))
1701
1702    @classmethod
1703    def number(cls, number) -> Literal:
1704        return cls(this=str(number), is_string=False)
1705
1706    @classmethod
1707    def string(cls, string) -> Literal:
1708        return cls(this=str(string), is_string=True)
1709
1710    @property
1711    def output_name(self) -> str:
1712        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1702    @classmethod
1703    def number(cls, number) -> Literal:
1704        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1706    @classmethod
1707    def string(cls, string) -> Literal:
1708        return cls(this=str(string), is_string=True)
output_name: str

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

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

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

Append to or set the ON expressions.

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

The modified Join expression.

def using( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1791    def using(
1792        self,
1793        *expressions: t.Optional[ExpOrStr],
1794        append: bool = True,
1795        dialect: DialectType = None,
1796        copy: bool = True,
1797        **opts,
1798    ) -> Join:
1799        """
1800        Append to or set the USING expressions.
1801
1802        Example:
1803            >>> import sqlglot
1804            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1805            'JOIN x USING (foo, bla)'
1806
1807        Args:
1808            *expressions: the SQL code strings to parse.
1809                If an `Expression` instance is passed, it will be used as-is.
1810            append: if `True`, concatenate the new expressions to the existing "using" list.
1811                Otherwise, this resets the expression.
1812            dialect: the dialect used to parse the input expressions.
1813            copy: if `False`, modify this expression instance in-place.
1814            opts: other options to use to parse the input expressions.
1815
1816        Returns:
1817            The modified Join expression.
1818        """
1819        join = _apply_list_builder(
1820            *expressions,
1821            instance=self,
1822            arg="using",
1823            append=append,
1824            dialect=dialect,
1825            copy=copy,
1826            **opts,
1827        )
1828
1829        if join.kind == "CROSS":
1830            join.set("kind", None)
1831
1832        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):
1835class Lateral(UDTF):
1836    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):
1839class MatchRecognize(Expression):
1840    arg_types = {
1841        "partition_by": False,
1842        "order": False,
1843        "measures": False,
1844        "rows": False,
1845        "after": False,
1846        "pattern": False,
1847        "define": False,
1848        "alias": False,
1849    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1854class Final(Expression):
1855    pass
key = 'final'
class Offset(Expression):
1858class Offset(Expression):
1859    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1862class Order(Expression):
1863    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1868class Cluster(Order):
1869    pass
key = 'cluster'
class Distribute(Order):
1872class Distribute(Order):
1873    pass
key = 'distribute'
class Sort(Order):
1876class Sort(Order):
1877    pass
key = 'sort'
class Ordered(Expression):
1880class Ordered(Expression):
1881    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1884class Property(Expression):
1885    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1888class AlgorithmProperty(Property):
1889    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1892class AutoIncrementProperty(Property):
1893    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1896class BlockCompressionProperty(Property):
1897    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):
1900class CharacterSetProperty(Property):
1901    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1904class ChecksumProperty(Property):
1905    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1908class CollateProperty(Property):
1909    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1912class CopyGrantsProperty(Property):
1913    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1916class DataBlocksizeProperty(Property):
1917    arg_types = {
1918        "size": False,
1919        "units": False,
1920        "minimum": False,
1921        "maximum": False,
1922        "default": False,
1923    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1926class DefinerProperty(Property):
1927    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1930class DistKeyProperty(Property):
1931    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1934class DistStyleProperty(Property):
1935    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1938class EngineProperty(Property):
1939    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
1942class HeapProperty(Property):
1943    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
1946class ToTableProperty(Property):
1947    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1950class ExecuteAsProperty(Property):
1951    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1954class ExternalProperty(Property):
1955    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1958class FallbackProperty(Property):
1959    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1962class FileFormatProperty(Property):
1963    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1966class FreespaceProperty(Property):
1967    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1970class InputOutputFormat(Expression):
1971    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1974class IsolatedLoadingProperty(Property):
1975    arg_types = {
1976        "no": True,
1977        "concurrent": True,
1978        "for_all": True,
1979        "for_insert": True,
1980        "for_none": True,
1981    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1984class JournalProperty(Property):
1985    arg_types = {
1986        "no": False,
1987        "dual": False,
1988        "before": False,
1989        "local": False,
1990        "after": False,
1991    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1994class LanguageProperty(Property):
1995    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1999class ClusteredByProperty(Property):
2000    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
2003class DictProperty(Property):
2004    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2007class DictSubProperty(Property):
2008    pass
key = 'dictsubproperty'
class DictRange(Property):
2011class DictRange(Property):
2012    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2017class OnCluster(Property):
2018    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2021class LikeProperty(Property):
2022    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2025class LocationProperty(Property):
2026    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2029class LockingProperty(Property):
2030    arg_types = {
2031        "this": False,
2032        "kind": True,
2033        "for_or_in": True,
2034        "lock_type": True,
2035        "override": False,
2036    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2039class LogProperty(Property):
2040    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2043class MaterializedProperty(Property):
2044    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2047class MergeBlockRatioProperty(Property):
2048    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):
2051class NoPrimaryIndexProperty(Property):
2052    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
2055class OnCommitProperty(Property):
2056    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2059class PartitionedByProperty(Property):
2060    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2063class ReturnsProperty(Property):
2064    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2067class RowFormatProperty(Property):
2068    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2071class RowFormatDelimitedProperty(Property):
2072    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2073    arg_types = {
2074        "fields": False,
2075        "escaped": False,
2076        "collection_items": False,
2077        "map_keys": False,
2078        "lines": False,
2079        "null": False,
2080        "serde": False,
2081    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2084class RowFormatSerdeProperty(Property):
2085    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2089class QueryTransform(Expression):
2090    arg_types = {
2091        "expressions": True,
2092        "command_script": True,
2093        "schema": False,
2094        "row_format_before": False,
2095        "record_writer": False,
2096        "row_format_after": False,
2097        "record_reader": False,
2098    }
arg_types = {'expressions': True, 'command_script': True, 'schema': False, 'row_format_before': False, 'record_writer': False, 'row_format_after': False, 'record_reader': False}
key = 'querytransform'
class SchemaCommentProperty(Property):
2101class SchemaCommentProperty(Property):
2102    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2105class SerdeProperties(Property):
2106    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2109class SetProperty(Property):
2110    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2113class SettingsProperty(Property):
2114    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2117class SortKeyProperty(Property):
2118    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2121class SqlSecurityProperty(Property):
2122    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2125class StabilityProperty(Property):
2126    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2129class TemporaryProperty(Property):
2130    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2133class TransientProperty(Property):
2134    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2137class VolatileProperty(Property):
2138    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2141class WithDataProperty(Property):
2142    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2145class WithJournalTableProperty(Property):
2146    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2149class Properties(Expression):
2150    arg_types = {"expressions": True}
2151
2152    NAME_TO_PROPERTY = {
2153        "ALGORITHM": AlgorithmProperty,
2154        "AUTO_INCREMENT": AutoIncrementProperty,
2155        "CHARACTER SET": CharacterSetProperty,
2156        "CLUSTERED_BY": ClusteredByProperty,
2157        "COLLATE": CollateProperty,
2158        "COMMENT": SchemaCommentProperty,
2159        "DEFINER": DefinerProperty,
2160        "DISTKEY": DistKeyProperty,
2161        "DISTSTYLE": DistStyleProperty,
2162        "ENGINE": EngineProperty,
2163        "EXECUTE AS": ExecuteAsProperty,
2164        "FORMAT": FileFormatProperty,
2165        "LANGUAGE": LanguageProperty,
2166        "LOCATION": LocationProperty,
2167        "PARTITIONED_BY": PartitionedByProperty,
2168        "RETURNS": ReturnsProperty,
2169        "ROW_FORMAT": RowFormatProperty,
2170        "SORTKEY": SortKeyProperty,
2171    }
2172
2173    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2174
2175    # CREATE property locations
2176    # Form: schema specified
2177    #   create [POST_CREATE]
2178    #     table a [POST_NAME]
2179    #     (b int) [POST_SCHEMA]
2180    #     with ([POST_WITH])
2181    #     index (b) [POST_INDEX]
2182    #
2183    # Form: alias selection
2184    #   create [POST_CREATE]
2185    #     table a [POST_NAME]
2186    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2187    #     index (c) [POST_INDEX]
2188    class Location(AutoName):
2189        POST_CREATE = auto()
2190        POST_NAME = auto()
2191        POST_SCHEMA = auto()
2192        POST_WITH = auto()
2193        POST_ALIAS = auto()
2194        POST_EXPRESSION = auto()
2195        POST_INDEX = auto()
2196        UNSUPPORTED = auto()
2197
2198    @classmethod
2199    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2200        expressions = []
2201        for key, value in properties_dict.items():
2202            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2203            if property_cls:
2204                expressions.append(property_cls(this=convert(value)))
2205            else:
2206                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2207
2208        return cls(expressions=expressions)
arg_types = {'expressions': True}
NAME_TO_PROPERTY = {'ALGORITHM': <class 'sqlglot.expressions.AlgorithmProperty'>, 'AUTO_INCREMENT': <class 'sqlglot.expressions.AutoIncrementProperty'>, 'CHARACTER SET': <class 'sqlglot.expressions.CharacterSetProperty'>, 'CLUSTERED_BY': <class 'sqlglot.expressions.ClusteredByProperty'>, 'COLLATE': <class 'sqlglot.expressions.CollateProperty'>, 'COMMENT': <class 'sqlglot.expressions.SchemaCommentProperty'>, 'DEFINER': <class 'sqlglot.expressions.DefinerProperty'>, 'DISTKEY': <class 'sqlglot.expressions.DistKeyProperty'>, 'DISTSTYLE': <class 'sqlglot.expressions.DistStyleProperty'>, 'ENGINE': <class 'sqlglot.expressions.EngineProperty'>, 'EXECUTE AS': <class 'sqlglot.expressions.ExecuteAsProperty'>, 'FORMAT': <class 'sqlglot.expressions.FileFormatProperty'>, 'LANGUAGE': <class 'sqlglot.expressions.LanguageProperty'>, 'LOCATION': <class 'sqlglot.expressions.LocationProperty'>, 'PARTITIONED_BY': <class 'sqlglot.expressions.PartitionedByProperty'>, 'RETURNS': <class 'sqlglot.expressions.ReturnsProperty'>, 'ROW_FORMAT': <class 'sqlglot.expressions.RowFormatProperty'>, 'SORTKEY': <class 'sqlglot.expressions.SortKeyProperty'>}
PROPERTY_TO_NAME = {<class 'sqlglot.expressions.AlgorithmProperty'>: 'ALGORITHM', <class 'sqlglot.expressions.AutoIncrementProperty'>: 'AUTO_INCREMENT', <class 'sqlglot.expressions.CharacterSetProperty'>: 'CHARACTER SET', <class 'sqlglot.expressions.ClusteredByProperty'>: 'CLUSTERED_BY', <class 'sqlglot.expressions.CollateProperty'>: 'COLLATE', <class 'sqlglot.expressions.SchemaCommentProperty'>: 'COMMENT', <class 'sqlglot.expressions.DefinerProperty'>: 'DEFINER', <class 'sqlglot.expressions.DistKeyProperty'>: 'DISTKEY', <class 'sqlglot.expressions.DistStyleProperty'>: 'DISTSTYLE', <class 'sqlglot.expressions.EngineProperty'>: 'ENGINE', <class 'sqlglot.expressions.ExecuteAsProperty'>: 'EXECUTE AS', <class 'sqlglot.expressions.FileFormatProperty'>: 'FORMAT', <class 'sqlglot.expressions.LanguageProperty'>: 'LANGUAGE', <class 'sqlglot.expressions.LocationProperty'>: 'LOCATION', <class 'sqlglot.expressions.PartitionedByProperty'>: 'PARTITIONED_BY', <class 'sqlglot.expressions.ReturnsProperty'>: 'RETURNS', <class 'sqlglot.expressions.RowFormatProperty'>: 'ROW_FORMAT', <class 'sqlglot.expressions.SortKeyProperty'>: 'SORTKEY'}
@classmethod
def from_dict(cls, properties_dict: Dict) -> sqlglot.expressions.Properties:
2198    @classmethod
2199    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2200        expressions = []
2201        for key, value in properties_dict.items():
2202            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2203            if property_cls:
2204                expressions.append(property_cls(this=convert(value)))
2205            else:
2206                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2207
2208        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2188    class Location(AutoName):
2189        POST_CREATE = auto()
2190        POST_NAME = auto()
2191        POST_SCHEMA = auto()
2192        POST_WITH = auto()
2193        POST_ALIAS = auto()
2194        POST_EXPRESSION = auto()
2195        POST_INDEX = auto()
2196        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):
2211class Qualify(Expression):
2212    pass
key = 'qualify'
class Return(Expression):
2216class Return(Expression):
2217    pass
key = 'return'
class Reference(Expression):
2220class Reference(Expression):
2221    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2224class Tuple(Expression):
2225    arg_types = {"expressions": False}
2226
2227    def isin(
2228        self,
2229        *expressions: t.Any,
2230        query: t.Optional[ExpOrStr] = None,
2231        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2232        copy: bool = True,
2233        **opts,
2234    ) -> In:
2235        return In(
2236            this=maybe_copy(self, copy),
2237            expressions=[convert(e, copy=copy) for e in expressions],
2238            query=maybe_parse(query, copy=copy, **opts) if query else None,
2239            unnest=Unnest(
2240                expressions=[
2241                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2242                ]
2243            )
2244            if unnest
2245            else None,
2246        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, unnest: Union[str, sqlglot.expressions.Expression, NoneType, Collection[Union[str, sqlglot.expressions.Expression]]] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2227    def isin(
2228        self,
2229        *expressions: t.Any,
2230        query: t.Optional[ExpOrStr] = None,
2231        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2232        copy: bool = True,
2233        **opts,
2234    ) -> In:
2235        return In(
2236            this=maybe_copy(self, copy),
2237            expressions=[convert(e, copy=copy) for e in expressions],
2238            query=maybe_parse(query, copy=copy, **opts) if query else None,
2239            unnest=Unnest(
2240                expressions=[
2241                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2242                ]
2243            )
2244            if unnest
2245            else None,
2246        )
key = 'tuple'
class Subqueryable(Unionable):
2249class Subqueryable(Unionable):
2250    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2251        """
2252        Convert this expression to an aliased expression that can be used as a Subquery.
2253
2254        Example:
2255            >>> subquery = Select().select("x").from_("tbl").subquery()
2256            >>> Select().select("x").from_(subquery).sql()
2257            'SELECT x FROM (SELECT x FROM tbl)'
2258
2259        Args:
2260            alias (str | Identifier): an optional alias for the subquery
2261            copy (bool): if `False`, modify this expression instance in-place.
2262
2263        Returns:
2264            Alias: the subquery
2265        """
2266        instance = maybe_copy(self, copy)
2267        if not isinstance(alias, Expression):
2268            alias = TableAlias(this=to_identifier(alias)) if alias else None
2269
2270        return Subquery(this=instance, alias=alias)
2271
2272    def limit(
2273        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2274    ) -> Select:
2275        raise NotImplementedError
2276
2277    @property
2278    def ctes(self):
2279        with_ = self.args.get("with")
2280        if not with_:
2281            return []
2282        return with_.expressions
2283
2284    @property
2285    def selects(self) -> t.List[Expression]:
2286        raise NotImplementedError("Subqueryable objects must implement `selects`")
2287
2288    @property
2289    def named_selects(self) -> t.List[str]:
2290        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2291
2292    def with_(
2293        self,
2294        alias: ExpOrStr,
2295        as_: ExpOrStr,
2296        recursive: t.Optional[bool] = None,
2297        append: bool = True,
2298        dialect: DialectType = None,
2299        copy: bool = True,
2300        **opts,
2301    ) -> Subqueryable:
2302        """
2303        Append to or set the common table expressions.
2304
2305        Example:
2306            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2307            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2308
2309        Args:
2310            alias: the SQL code string to parse as the table name.
2311                If an `Expression` instance is passed, this is used as-is.
2312            as_: the SQL code string to parse as the table expression.
2313                If an `Expression` instance is passed, it will be used as-is.
2314            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2315            append: if `True`, add to any existing expressions.
2316                Otherwise, this resets the expressions.
2317            dialect: the dialect used to parse the input expression.
2318            copy: if `False`, modify this expression instance in-place.
2319            opts: other options to use to parse the input expressions.
2320
2321        Returns:
2322            The modified expression.
2323        """
2324        return _apply_cte_builder(
2325            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2326        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2250    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2251        """
2252        Convert this expression to an aliased expression that can be used as a Subquery.
2253
2254        Example:
2255            >>> subquery = Select().select("x").from_("tbl").subquery()
2256            >>> Select().select("x").from_(subquery).sql()
2257            'SELECT x FROM (SELECT x FROM tbl)'
2258
2259        Args:
2260            alias (str | Identifier): an optional alias for the subquery
2261            copy (bool): if `False`, modify this expression instance in-place.
2262
2263        Returns:
2264            Alias: the subquery
2265        """
2266        instance = maybe_copy(self, copy)
2267        if not isinstance(alias, Expression):
2268            alias = TableAlias(this=to_identifier(alias)) if alias else None
2269
2270        return Subquery(this=instance, alias=alias)

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

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

Alias: the subquery

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

Append to or set the common table expressions.

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

The modified expression.

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

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

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

Set the LIMIT expression.

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

The limited subqueryable.

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

Append to or set the SELECT of the union recursively.

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

Union: the modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

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

Set the FROM expression.

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

The modified Select expression.

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

Set the GROUP BY expression.

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

The modified Select expression.

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

Set the ORDER BY expression.

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

The modified Select expression.

def sort_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2693    def sort_by(
2694        self,
2695        *expressions: t.Optional[ExpOrStr],
2696        append: bool = True,
2697        dialect: DialectType = None,
2698        copy: bool = True,
2699        **opts,
2700    ) -> Select:
2701        """
2702        Set the SORT BY expression.
2703
2704        Example:
2705            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2706            'SELECT x FROM tbl SORT BY x DESC'
2707
2708        Args:
2709            *expressions: the SQL code strings to parse.
2710                If a `Group` instance is passed, this is used as-is.
2711                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2712            append: if `True`, add to any existing expressions.
2713                Otherwise, this flattens all the `Order` expression into a single expression.
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_child_list_builder(
2722            *expressions,
2723            instance=self,
2724            arg="sort",
2725            append=append,
2726            copy=copy,
2727            prefix="SORT BY",
2728            into=Sort,
2729            dialect=dialect,
2730            **opts,
2731        )

Set the SORT BY expression.

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

The modified Select expression.

def cluster_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2733    def cluster_by(
2734        self,
2735        *expressions: t.Optional[ExpOrStr],
2736        append: bool = True,
2737        dialect: DialectType = None,
2738        copy: bool = True,
2739        **opts,
2740    ) -> Select:
2741        """
2742        Set the CLUSTER BY expression.
2743
2744        Example:
2745            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2746            'SELECT x FROM tbl CLUSTER BY x DESC'
2747
2748        Args:
2749            *expressions: the SQL code strings to parse.
2750                If a `Group` instance is passed, this is used as-is.
2751                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2752            append: if `True`, add to any existing expressions.
2753                Otherwise, this flattens all the `Order` 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        return _apply_child_list_builder(
2762            *expressions,
2763            instance=self,
2764            arg="cluster",
2765            append=append,
2766            copy=copy,
2767            prefix="CLUSTER BY",
2768            into=Cluster,
2769            dialect=dialect,
2770            **opts,
2771        )

Set the CLUSTER BY expression.

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

The modified Select expression.

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

Set the LIMIT expression.

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

Select: the modified expression.

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

Set the OFFSET expression.

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

The modified Select expression.

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

Append to or set the SELECT expressions.

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

The modified Select expression.

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

Append to or set the LATERAL expressions.

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

The modified Select expression.

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

Append to or set the JOIN expressions.

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

Use join_type to change the type of join:

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

Select: the modified expression.

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

Append to or set the WHERE expressions.

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

Select: the modified expression.

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

Append to or set the HAVING expressions.

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

The modified Select expression.

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

Set the OFFSET expression.

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

Select: the modified expression.

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

Convert this expression to a CREATE TABLE AS statement.

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

The new Create expression.

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

Set the locking read mode for this expression.

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

The modified expression.

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

Set hints for this expression.

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

The modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

key = 'select'
class Subquery(DerivedTable, Unionable):
3256class Subquery(DerivedTable, Unionable):
3257    arg_types = {
3258        "this": True,
3259        "alias": False,
3260        "with": False,
3261        **QUERY_MODIFIERS,
3262    }
3263
3264    def unnest(self):
3265        """
3266        Returns the first non subquery.
3267        """
3268        expression = self
3269        while isinstance(expression, Subquery):
3270            expression = expression.this
3271        return expression
3272
3273    def unwrap(self) -> Subquery:
3274        expression = self
3275        while expression.same_parent and expression.is_wrapper:
3276            expression = t.cast(Subquery, expression.parent)
3277        return expression
3278
3279    @property
3280    def is_wrapper(self) -> bool:
3281        """
3282        Whether this Subquery acts as a simple wrapper around another expression.
3283
3284        SELECT * FROM (((SELECT * FROM t)))
3285                      ^
3286                      This corresponds to a "wrapper" Subquery node
3287        """
3288        return all(v is None for k, v in self.args.items() if k != "this")
3289
3290    @property
3291    def is_star(self) -> bool:
3292        return self.this.is_star
3293
3294    @property
3295    def output_name(self) -> str:
3296        return self.alias
arg_types = {'this': True, 'alias': False, 'with': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def unnest(self):
3264    def unnest(self):
3265        """
3266        Returns the first non subquery.
3267        """
3268        expression = self
3269        while isinstance(expression, Subquery):
3270            expression = expression.this
3271        return expression

Returns the first non subquery.

def unwrap(self) -> sqlglot.expressions.Subquery:
3273    def unwrap(self) -> Subquery:
3274        expression = self
3275        while expression.same_parent and expression.is_wrapper:
3276            expression = t.cast(Subquery, expression.parent)
3277        return expression
is_wrapper: bool

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

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

is_star: bool

Checks whether an expression is a star.

output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'subquery'
class TableSample(Expression):
3299class TableSample(Expression):
3300    arg_types = {
3301        "this": False,
3302        "method": False,
3303        "bucket_numerator": False,
3304        "bucket_denominator": False,
3305        "bucket_field": False,
3306        "percent": False,
3307        "rows": False,
3308        "size": False,
3309        "seed": False,
3310        "kind": False,
3311    }
arg_types = {'this': False, 'method': False, 'bucket_numerator': False, 'bucket_denominator': False, 'bucket_field': False, 'percent': False, 'rows': False, 'size': False, 'seed': False, 'kind': False}
key = 'tablesample'
class Tag(Expression):
3314class Tag(Expression):
3315    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3316
3317    arg_types = {
3318        "this": False,
3319        "prefix": False,
3320        "postfix": False,
3321    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3326class Pivot(Expression):
3327    arg_types = {
3328        "this": False,
3329        "alias": False,
3330        "expressions": True,
3331        "field": False,
3332        "unpivot": False,
3333        "using": False,
3334        "group": False,
3335        "columns": False,
3336        "include_nulls": False,
3337    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False, 'include_nulls': False}
key = 'pivot'
class Window(Condition):
3340class Window(Condition):
3341    arg_types = {
3342        "this": True,
3343        "partition_by": False,
3344        "order": False,
3345        "spec": False,
3346        "alias": False,
3347        "over": False,
3348        "first": False,
3349    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3352class WindowSpec(Expression):
3353    arg_types = {
3354        "kind": False,
3355        "start": False,
3356        "start_side": False,
3357        "end": False,
3358        "end_side": False,
3359    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3362class Where(Expression):
3363    pass
key = 'where'
class Star(Expression):
3366class Star(Expression):
3367    arg_types = {"except": False, "replace": False}
3368
3369    @property
3370    def name(self) -> str:
3371        return "*"
3372
3373    @property
3374    def output_name(self) -> str:
3375        return self.name
arg_types = {'except': False, 'replace': False}
name: str
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'star'
class Parameter(Condition):
3378class Parameter(Condition):
3379    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3382class SessionParameter(Condition):
3383    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3386class Placeholder(Condition):
3387    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3390class Null(Condition):
3391    arg_types: t.Dict[str, t.Any] = {}
3392
3393    @property
3394    def name(self) -> str:
3395        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3398class Boolean(Condition):
3399    pass
key = 'boolean'
class DataTypeParam(Expression):
3402class DataTypeParam(Expression):
3403    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypeparam'
class DataType(Expression):
3406class DataType(Expression):
3407    arg_types = {
3408        "this": True,
3409        "expressions": False,
3410        "nested": False,
3411        "values": False,
3412        "prefix": False,
3413        "kind": False,
3414    }
3415
3416    class Type(AutoName):
3417        ARRAY = auto()
3418        BIGDECIMAL = auto()
3419        BIGINT = auto()
3420        BIGSERIAL = auto()
3421        BINARY = auto()
3422        BIT = auto()
3423        BOOLEAN = auto()
3424        CHAR = auto()
3425        DATE = auto()
3426        DATEMULTIRANGE = auto()
3427        DATERANGE = auto()
3428        DATETIME = auto()
3429        DATETIME64 = auto()
3430        DECIMAL = auto()
3431        DOUBLE = auto()
3432        ENUM = auto()
3433        ENUM8 = auto()
3434        ENUM16 = auto()
3435        FIXEDSTRING = auto()
3436        FLOAT = auto()
3437        GEOGRAPHY = auto()
3438        GEOMETRY = auto()
3439        HLLSKETCH = auto()
3440        HSTORE = auto()
3441        IMAGE = auto()
3442        INET = auto()
3443        INT = auto()
3444        INT128 = auto()
3445        INT256 = auto()
3446        INT4MULTIRANGE = auto()
3447        INT4RANGE = auto()
3448        INT8MULTIRANGE = auto()
3449        INT8RANGE = auto()
3450        INTERVAL = auto()
3451        IPADDRESS = auto()
3452        IPPREFIX = auto()
3453        JSON = auto()
3454        JSONB = auto()
3455        LONGBLOB = auto()
3456        LONGTEXT = auto()
3457        LOWCARDINALITY = auto()
3458        MAP = auto()
3459        MEDIUMBLOB = auto()
3460        MEDIUMTEXT = auto()
3461        MONEY = auto()
3462        NCHAR = auto()
3463        NESTED = auto()
3464        NULL = auto()
3465        NULLABLE = auto()
3466        NUMMULTIRANGE = auto()
3467        NUMRANGE = auto()
3468        NVARCHAR = auto()
3469        OBJECT = auto()
3470        ROWVERSION = auto()
3471        SERIAL = auto()
3472        SET = auto()
3473        SMALLINT = auto()
3474        SMALLMONEY = auto()
3475        SMALLSERIAL = auto()
3476        STRUCT = auto()
3477        SUPER = auto()
3478        TEXT = auto()
3479        TIME = auto()
3480        TIMETZ = auto()
3481        TIMESTAMP = auto()
3482        TIMESTAMPLTZ = auto()
3483        TIMESTAMPTZ = auto()
3484        TINYINT = auto()
3485        TSMULTIRANGE = auto()
3486        TSRANGE = auto()
3487        TSTZMULTIRANGE = auto()
3488        TSTZRANGE = auto()
3489        UBIGINT = auto()
3490        UINT = auto()
3491        UINT128 = auto()
3492        UINT256 = auto()
3493        UNIQUEIDENTIFIER = auto()
3494        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3495        USERDEFINED = "USER-DEFINED"
3496        USMALLINT = auto()
3497        UTINYINT = auto()
3498        UUID = auto()
3499        VARBINARY = auto()
3500        VARCHAR = auto()
3501        VARIANT = auto()
3502        XML = auto()
3503
3504    TEXT_TYPES = {
3505        Type.CHAR,
3506        Type.NCHAR,
3507        Type.VARCHAR,
3508        Type.NVARCHAR,
3509        Type.TEXT,
3510    }
3511
3512    INTEGER_TYPES = {
3513        Type.INT,
3514        Type.TINYINT,
3515        Type.SMALLINT,
3516        Type.BIGINT,
3517        Type.INT128,
3518        Type.INT256,
3519    }
3520
3521    FLOAT_TYPES = {
3522        Type.FLOAT,
3523        Type.DOUBLE,
3524    }
3525
3526    NUMERIC_TYPES = {
3527        *INTEGER_TYPES,
3528        *FLOAT_TYPES,
3529    }
3530
3531    TEMPORAL_TYPES = {
3532        Type.TIME,
3533        Type.TIMETZ,
3534        Type.TIMESTAMP,
3535        Type.TIMESTAMPTZ,
3536        Type.TIMESTAMPLTZ,
3537        Type.DATE,
3538        Type.DATETIME,
3539        Type.DATETIME64,
3540    }
3541
3542    @classmethod
3543    def build(
3544        cls,
3545        dtype: str | DataType | DataType.Type,
3546        dialect: DialectType = None,
3547        udt: bool = False,
3548        **kwargs,
3549    ) -> DataType:
3550        """
3551        Constructs a DataType object.
3552
3553        Args:
3554            dtype: the data type of interest.
3555            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3556            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3557                DataType, thus creating a user-defined type.
3558            kawrgs: additional arguments to pass in the constructor of DataType.
3559
3560        Returns:
3561            The constructed DataType object.
3562        """
3563        from sqlglot import parse_one
3564
3565        if isinstance(dtype, str):
3566            if dtype.upper() == "UNKNOWN":
3567                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3568
3569            try:
3570                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3571            except ParseError:
3572                if udt:
3573                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3574                raise
3575        elif isinstance(dtype, DataType.Type):
3576            data_type_exp = DataType(this=dtype)
3577        elif isinstance(dtype, DataType):
3578            return dtype
3579        else:
3580            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3581
3582        return DataType(**{**data_type_exp.args, **kwargs})
3583
3584    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3585        """
3586        Checks whether this DataType matches one of the provided data types. Nested types or precision
3587        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3588
3589        Args:
3590            dtypes: the data types to compare this DataType to.
3591
3592        Returns:
3593            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3594        """
3595        for dtype in dtypes:
3596            other = DataType.build(dtype, udt=True)
3597
3598            if (
3599                other.expressions
3600                or self.this == DataType.Type.USERDEFINED
3601                or other.this == DataType.Type.USERDEFINED
3602            ):
3603                matches = self == other
3604            else:
3605                matches = self.this == other.this
3606
3607            if matches:
3608                return True
3609        return False
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False, 'kind': False}
TEXT_TYPES = {<Type.NVARCHAR: 'NVARCHAR'>, <Type.TEXT: 'TEXT'>, <Type.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>}
INTEGER_TYPES = {<Type.TINYINT: 'TINYINT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT256: 'INT256'>, <Type.INT: 'INT'>, <Type.INT128: 'INT128'>, <Type.SMALLINT: 'SMALLINT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.TINYINT: 'TINYINT'>, <Type.BIGINT: 'BIGINT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.INT256: 'INT256'>, <Type.INT: 'INT'>, <Type.FLOAT: 'FLOAT'>, <Type.INT128: 'INT128'>}
TEMPORAL_TYPES = {<Type.DATE: 'DATE'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIMETZ: 'TIMETZ'>, <Type.TIME: 'TIME'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.DATETIME: 'DATETIME'>, <Type.DATETIME64: 'DATETIME64'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>}
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, udt: bool = False, **kwargs) -> sqlglot.expressions.DataType:
3542    @classmethod
3543    def build(
3544        cls,
3545        dtype: str | DataType | DataType.Type,
3546        dialect: DialectType = None,
3547        udt: bool = False,
3548        **kwargs,
3549    ) -> DataType:
3550        """
3551        Constructs a DataType object.
3552
3553        Args:
3554            dtype: the data type of interest.
3555            dialect: the dialect to use for parsing `dtype`, in case it's a string.
3556            udt: when set to True, `dtype` will be used as-is if it can't be parsed into a
3557                DataType, thus creating a user-defined type.
3558            kawrgs: additional arguments to pass in the constructor of DataType.
3559
3560        Returns:
3561            The constructed DataType object.
3562        """
3563        from sqlglot import parse_one
3564
3565        if isinstance(dtype, str):
3566            if dtype.upper() == "UNKNOWN":
3567                return DataType(this=DataType.Type.UNKNOWN, **kwargs)
3568
3569            try:
3570                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3571            except ParseError:
3572                if udt:
3573                    return DataType(this=DataType.Type.USERDEFINED, kind=dtype, **kwargs)
3574                raise
3575        elif isinstance(dtype, DataType.Type):
3576            data_type_exp = DataType(this=dtype)
3577        elif isinstance(dtype, DataType):
3578            return dtype
3579        else:
3580            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3581
3582        return DataType(**{**data_type_exp.args, **kwargs})

Constructs a DataType object.

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

The constructed DataType object.

def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3584    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3585        """
3586        Checks whether this DataType matches one of the provided data types. Nested types or precision
3587        will be compared using "structural equivalence" semantics, so e.g. array<int> != array<float>.
3588
3589        Args:
3590            dtypes: the data types to compare this DataType to.
3591
3592        Returns:
3593            True, if and only if there is a type in `dtypes` which is equal to this DataType.
3594        """
3595        for dtype in dtypes:
3596            other = DataType.build(dtype, udt=True)
3597
3598            if (
3599                other.expressions
3600                or self.this == DataType.Type.USERDEFINED
3601                or other.this == DataType.Type.USERDEFINED
3602            ):
3603                matches = self == other
3604            else:
3605                matches = self.this == other.this
3606
3607            if matches:
3608                return True
3609        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):
3416    class Type(AutoName):
3417        ARRAY = auto()
3418        BIGDECIMAL = auto()
3419        BIGINT = auto()
3420        BIGSERIAL = auto()
3421        BINARY = auto()
3422        BIT = auto()
3423        BOOLEAN = auto()
3424        CHAR = auto()
3425        DATE = auto()
3426        DATEMULTIRANGE = auto()
3427        DATERANGE = auto()
3428        DATETIME = auto()
3429        DATETIME64 = auto()
3430        DECIMAL = auto()
3431        DOUBLE = auto()
3432        ENUM = auto()
3433        ENUM8 = auto()
3434        ENUM16 = auto()
3435        FIXEDSTRING = auto()
3436        FLOAT = auto()
3437        GEOGRAPHY = auto()
3438        GEOMETRY = auto()
3439        HLLSKETCH = auto()
3440        HSTORE = auto()
3441        IMAGE = auto()
3442        INET = auto()
3443        INT = auto()
3444        INT128 = auto()
3445        INT256 = auto()
3446        INT4MULTIRANGE = auto()
3447        INT4RANGE = auto()
3448        INT8MULTIRANGE = auto()
3449        INT8RANGE = auto()
3450        INTERVAL = auto()
3451        IPADDRESS = auto()
3452        IPPREFIX = auto()
3453        JSON = auto()
3454        JSONB = auto()
3455        LONGBLOB = auto()
3456        LONGTEXT = auto()
3457        LOWCARDINALITY = auto()
3458        MAP = auto()
3459        MEDIUMBLOB = auto()
3460        MEDIUMTEXT = auto()
3461        MONEY = auto()
3462        NCHAR = auto()
3463        NESTED = auto()
3464        NULL = auto()
3465        NULLABLE = auto()
3466        NUMMULTIRANGE = auto()
3467        NUMRANGE = auto()
3468        NVARCHAR = auto()
3469        OBJECT = auto()
3470        ROWVERSION = auto()
3471        SERIAL = auto()
3472        SET = auto()
3473        SMALLINT = auto()
3474        SMALLMONEY = auto()
3475        SMALLSERIAL = auto()
3476        STRUCT = auto()
3477        SUPER = auto()
3478        TEXT = auto()
3479        TIME = auto()
3480        TIMETZ = auto()
3481        TIMESTAMP = auto()
3482        TIMESTAMPLTZ = auto()
3483        TIMESTAMPTZ = auto()
3484        TINYINT = auto()
3485        TSMULTIRANGE = auto()
3486        TSRANGE = auto()
3487        TSTZMULTIRANGE = auto()
3488        TSTZRANGE = auto()
3489        UBIGINT = auto()
3490        UINT = auto()
3491        UINT128 = auto()
3492        UINT256 = auto()
3493        UNIQUEIDENTIFIER = auto()
3494        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3495        USERDEFINED = "USER-DEFINED"
3496        USMALLINT = auto()
3497        UTINYINT = auto()
3498        UUID = auto()
3499        VARBINARY = auto()
3500        VARCHAR = auto()
3501        VARIANT = auto()
3502        XML = auto()

An enumeration.

ARRAY = <Type.ARRAY: 'ARRAY'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <Type.BIGINT: 'BIGINT'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
BINARY = <Type.BINARY: 'BINARY'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
CHAR = <Type.CHAR: 'CHAR'>
DATE = <Type.DATE: 'DATE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
ENUM = <Type.ENUM: 'ENUM'>
ENUM8 = <Type.ENUM8: 'ENUM8'>
ENUM16 = <Type.ENUM16: 'ENUM16'>
FIXEDSTRING = <Type.FIXEDSTRING: 'FIXEDSTRING'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
IPADDRESS = <Type.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <Type.IPPREFIX: 'IPPREFIX'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
LOWCARDINALITY = <Type.LOWCARDINALITY: 'LOWCARDINALITY'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NESTED = <Type.NESTED: 'NESTED'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TIME = <Type.TIME: 'TIME'>
TIMETZ = <Type.TIMETZ: 'TIMETZ'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3613class PseudoType(Expression):
3614    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3618class SubqueryPredicate(Predicate):
3619    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3622class All(SubqueryPredicate):
3623    pass
key = 'all'
class Any(SubqueryPredicate):
3626class Any(SubqueryPredicate):
3627    pass
key = 'any'
class Exists(SubqueryPredicate):
3630class Exists(SubqueryPredicate):
3631    pass
key = 'exists'
class Command(Expression):
3636class Command(Expression):
3637    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3640class Transaction(Expression):
3641    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3644class Commit(Expression):
3645    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3648class Rollback(Expression):
3649    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3652class AlterTable(Expression):
3653    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3656class AddConstraint(Expression):
3657    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3660class DropPartition(Expression):
3661    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3665class Binary(Condition):
3666    arg_types = {"this": True, "expression": True}
3667
3668    @property
3669    def left(self):
3670        return self.this
3671
3672    @property
3673    def right(self):
3674        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3677class Add(Binary):
3678    pass
key = 'add'
class Connector(Binary):
3681class Connector(Binary):
3682    pass
key = 'connector'
class And(Connector):
3685class And(Connector):
3686    pass
key = 'and'
class Or(Connector):
3689class Or(Connector):
3690    pass
key = 'or'
class BitwiseAnd(Binary):
3693class BitwiseAnd(Binary):
3694    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3697class BitwiseLeftShift(Binary):
3698    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3701class BitwiseOr(Binary):
3702    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3705class BitwiseRightShift(Binary):
3706    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3709class BitwiseXor(Binary):
3710    pass
key = 'bitwisexor'
class Div(Binary):
3713class Div(Binary):
3714    pass
key = 'div'
class Overlaps(Binary):
3717class Overlaps(Binary):
3718    pass
key = 'overlaps'
class Dot(Binary):
3721class Dot(Binary):
3722    @property
3723    def name(self) -> str:
3724        return self.expression.name
3725
3726    @property
3727    def output_name(self) -> str:
3728        return self.name
3729
3730    @classmethod
3731    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3732        """Build a Dot object with a sequence of expressions."""
3733        if len(expressions) < 2:
3734            raise ValueError(f"Dot requires >= 2 expressions.")
3735
3736        a, b, *expressions = expressions
3737        dot = Dot(this=a, expression=b)
3738
3739        for expression in expressions:
3740            dot = Dot(this=dot, expression=expression)
3741
3742        return dot
name: str
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3730    @classmethod
3731    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3732        """Build a Dot object with a sequence of expressions."""
3733        if len(expressions) < 2:
3734            raise ValueError(f"Dot requires >= 2 expressions.")
3735
3736        a, b, *expressions = expressions
3737        dot = Dot(this=a, expression=b)
3738
3739        for expression in expressions:
3740            dot = Dot(this=dot, expression=expression)
3741
3742        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3745class DPipe(Binary):
3746    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3749class SafeDPipe(DPipe):
3750    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3753class EQ(Binary, Predicate):
3754    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3757class NullSafeEQ(Binary, Predicate):
3758    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3761class NullSafeNEQ(Binary, Predicate):
3762    pass
key = 'nullsafeneq'
class Distance(Binary):
3765class Distance(Binary):
3766    pass
key = 'distance'
class Escape(Binary):
3769class Escape(Binary):
3770    pass
key = 'escape'
class Glob(Binary, Predicate):
3773class Glob(Binary, Predicate):
3774    pass
key = 'glob'
class GT(Binary, Predicate):
3777class GT(Binary, Predicate):
3778    pass
key = 'gt'
class GTE(Binary, Predicate):
3781class GTE(Binary, Predicate):
3782    pass
key = 'gte'
class ILike(Binary, Predicate):
3785class ILike(Binary, Predicate):
3786    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3789class ILikeAny(Binary, Predicate):
3790    pass
key = 'ilikeany'
class IntDiv(Binary):
3793class IntDiv(Binary):
3794    pass
key = 'intdiv'
class Is(Binary, Predicate):
3797class Is(Binary, Predicate):
3798    pass
key = 'is'
class Kwarg(Binary):
3801class Kwarg(Binary):
3802    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3805class Like(Binary, Predicate):
3806    pass
key = 'like'
class LikeAny(Binary, Predicate):
3809class LikeAny(Binary, Predicate):
3810    pass
key = 'likeany'
class LT(Binary, Predicate):
3813class LT(Binary, Predicate):
3814    pass
key = 'lt'
class LTE(Binary, Predicate):
3817class LTE(Binary, Predicate):
3818    pass
key = 'lte'
class Mod(Binary):
3821class Mod(Binary):
3822    pass
key = 'mod'
class Mul(Binary):
3825class Mul(Binary):
3826    pass
key = 'mul'
class NEQ(Binary, Predicate):
3829class NEQ(Binary, Predicate):
3830    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3833class SimilarTo(Binary, Predicate):
3834    pass
key = 'similarto'
class Slice(Binary):
3837class Slice(Binary):
3838    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3841class Sub(Binary):
3842    pass
key = 'sub'
class ArrayOverlaps(Binary):
3845class ArrayOverlaps(Binary):
3846    pass
key = 'arrayoverlaps'
class Unary(Condition):
3851class Unary(Condition):
3852    pass
key = 'unary'
class BitwiseNot(Unary):
3855class BitwiseNot(Unary):
3856    pass
key = 'bitwisenot'
class Not(Unary):
3859class Not(Unary):
3860    pass
key = 'not'
class Paren(Unary):
3863class Paren(Unary):
3864    arg_types = {"this": True, "with": False}
3865
3866    @property
3867    def output_name(self) -> str:
3868        return self.this.name
arg_types = {'this': True, 'with': False}
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'paren'
class Neg(Unary):
3871class Neg(Unary):
3872    pass
key = 'neg'
class Alias(Expression):
3875class Alias(Expression):
3876    arg_types = {"this": True, "alias": False}
3877
3878    @property
3879    def output_name(self) -> str:
3880        return self.alias
arg_types = {'this': True, 'alias': False}
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'alias'
class Aliases(Expression):
3883class Aliases(Expression):
3884    arg_types = {"this": True, "expressions": True}
3885
3886    @property
3887    def aliases(self):
3888        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3891class AtTimeZone(Expression):
3892    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3895class Between(Predicate):
3896    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3899class Bracket(Condition):
3900    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3903class SafeBracket(Bracket):
3904    """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):
3907class Distinct(Expression):
3908    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3911class In(Predicate):
3912    arg_types = {
3913        "this": True,
3914        "expressions": False,
3915        "query": False,
3916        "unnest": False,
3917        "field": False,
3918        "is_global": False,
3919    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3922class TimeUnit(Expression):
3923    """Automatically converts unit arg into a var."""
3924
3925    arg_types = {"unit": False}
3926
3927    def __init__(self, **args):
3928        unit = args.get("unit")
3929        if isinstance(unit, (Column, Literal)):
3930            args["unit"] = Var(this=unit.name)
3931        elif isinstance(unit, Week):
3932            unit.set("this", Var(this=unit.this.name))
3933
3934        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3927    def __init__(self, **args):
3928        unit = args.get("unit")
3929        if isinstance(unit, (Column, Literal)):
3930            args["unit"] = Var(this=unit.name)
3931        elif isinstance(unit, Week):
3932            unit.set("this", Var(this=unit.this.name))
3933
3934        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class IntervalYearToMonthSpan(Expression):
3939class IntervalYearToMonthSpan(Expression):
3940    arg_types = {}
arg_types = {}
key = 'intervalyeartomonthspan'
class IntervalDayToSecondSpan(Expression):
3945class IntervalDayToSecondSpan(Expression):
3946    arg_types = {}
arg_types = {}
key = 'intervaldaytosecondspan'
class Interval(TimeUnit):
3949class Interval(TimeUnit):
3950    arg_types = {"this": False, "unit": False}
3951
3952    @property
3953    def unit(self) -> t.Optional[Var]:
3954        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3957class IgnoreNulls(Expression):
3958    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3961class RespectNulls(Expression):
3962    pass
key = 'respectnulls'
class Func(Condition):
3966class Func(Condition):
3967    """
3968    The base class for all function expressions.
3969
3970    Attributes:
3971        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3972            treated as a variable length argument and the argument's value will be stored as a list.
3973        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3974            for this function expression. These values are used to map this node to a name during parsing
3975            as well as to provide the function's name during SQL string generation. By default the SQL
3976            name is set to the expression's class name transformed to snake case.
3977    """
3978
3979    is_var_len_args = False
3980
3981    @classmethod
3982    def from_arg_list(cls, args):
3983        if cls.is_var_len_args:
3984            all_arg_keys = list(cls.arg_types)
3985            # If this function supports variable length argument treat the last argument as such.
3986            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3987            num_non_var = len(non_var_len_arg_keys)
3988
3989            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3990            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3991        else:
3992            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3993
3994        return cls(**args_dict)
3995
3996    @classmethod
3997    def sql_names(cls):
3998        if cls is Func:
3999            raise NotImplementedError(
4000                "SQL name is only supported by concrete function implementations"
4001            )
4002        if "_sql_names" not in cls.__dict__:
4003            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4004        return cls._sql_names
4005
4006    @classmethod
4007    def sql_name(cls):
4008        return cls.sql_names()[0]
4009
4010    @classmethod
4011    def default_parser_mappings(cls):
4012        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):
3981    @classmethod
3982    def from_arg_list(cls, args):
3983        if cls.is_var_len_args:
3984            all_arg_keys = list(cls.arg_types)
3985            # If this function supports variable length argument treat the last argument as such.
3986            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3987            num_non_var = len(non_var_len_arg_keys)
3988
3989            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3990            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3991        else:
3992            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3993
3994        return cls(**args_dict)
@classmethod
def sql_names(cls):
3996    @classmethod
3997    def sql_names(cls):
3998        if cls is Func:
3999            raise NotImplementedError(
4000                "SQL name is only supported by concrete function implementations"
4001            )
4002        if "_sql_names" not in cls.__dict__:
4003            cls._sql_names = [camel_to_snake_case(cls.__name__)]
4004        return cls._sql_names
@classmethod
def sql_name(cls):
4006    @classmethod
4007    def sql_name(cls):
4008        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
4010    @classmethod
4011    def default_parser_mappings(cls):
4012        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
4015class AggFunc(Func):
4016    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
4019class ParameterizedAgg(AggFunc):
4020    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
4023class Abs(Func):
4024    pass
key = 'abs'
class Transform(Func):
4028class Transform(Func):
4029    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
4032class Anonymous(Func):
4033    arg_types = {"this": True, "expressions": False}
4034    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
4039class Hll(AggFunc):
4040    arg_types = {"this": True, "expressions": False}
4041    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
4044class ApproxDistinct(AggFunc):
4045    arg_types = {"this": True, "accuracy": False}
4046    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
4049class Array(Func):
4050    arg_types = {"expressions": False}
4051    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
4055class ToChar(Func):
4056    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
4059class GenerateSeries(Func):
4060    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
4063class ArrayAgg(AggFunc):
4064    pass
key = 'arrayagg'
class ArrayAll(Func):
4067class ArrayAll(Func):
4068    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4071class ArrayAny(Func):
4072    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4075class ArrayConcat(Func):
4076    _sql_names = ["ARRAY_CONCAT", "ARRAY_CAT"]
4077    arg_types = {"this": True, "expressions": False}
4078    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4081class ArrayContains(Binary, Func):
4082    pass
key = 'arraycontains'
class ArrayContained(Binary):
4085class ArrayContained(Binary):
4086    pass
key = 'arraycontained'
class ArrayFilter(Func):
4089class ArrayFilter(Func):
4090    arg_types = {"this": True, "expression": True}
4091    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4094class ArrayJoin(Func):
4095    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4098class ArraySize(Func):
4099    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4102class ArraySort(Func):
4103    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4106class ArraySum(Func):
4107    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4110class ArrayUnionAgg(AggFunc):
4111    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4114class Avg(AggFunc):
4115    pass
key = 'avg'
class AnyValue(AggFunc):
4118class AnyValue(AggFunc):
4119    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):
4122class First(Func):
4123    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'first'
class Last(Func):
4126class Last(Func):
4127    arg_types = {"this": True, "ignore_nulls": False}
arg_types = {'this': True, 'ignore_nulls': False}
key = 'last'
class Case(Func):
4130class Case(Func):
4131    arg_types = {"this": False, "ifs": True, "default": False}
4132
4133    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4134        instance = maybe_copy(self, copy)
4135        instance.append(
4136            "ifs",
4137            If(
4138                this=maybe_parse(condition, copy=copy, **opts),
4139                true=maybe_parse(then, copy=copy, **opts),
4140            ),
4141        )
4142        return instance
4143
4144    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4145        instance = maybe_copy(self, copy)
4146        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4147        return instance
arg_types = {'this': False, 'ifs': True, 'default': False}
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4133    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4134        instance = maybe_copy(self, copy)
4135        instance.append(
4136            "ifs",
4137            If(
4138                this=maybe_parse(condition, copy=copy, **opts),
4139                true=maybe_parse(then, copy=copy, **opts),
4140            ),
4141        )
4142        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4144    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4145        instance = maybe_copy(self, copy)
4146        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4147        return instance
key = 'case'
class Cast(Func):
4150class Cast(Func):
4151    arg_types = {"this": True, "to": True, "format": False}
4152
4153    @property
4154    def name(self) -> str:
4155        return self.this.name
4156
4157    @property
4158    def to(self) -> DataType:
4159        return self.args["to"]
4160
4161    @property
4162    def output_name(self) -> str:
4163        return self.name
4164
4165    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4166        """
4167        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4168        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4169        array<int> != array<float>.
4170
4171        Args:
4172            dtypes: the data types to compare this Cast's DataType to.
4173
4174        Returns:
4175            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4176        """
4177        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True, 'format': False}
name: str
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
4165    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4166        """
4167        Checks whether this Cast's DataType matches one of the provided data types. Nested types
4168        like arrays or structs will be compared using "structural equivalence" semantics, so e.g.
4169        array<int> != array<float>.
4170
4171        Args:
4172            dtypes: the data types to compare this Cast's DataType to.
4173
4174        Returns:
4175            True, if and only if there is a type in `dtypes` which is equal to this Cast's DataType.
4176        """
4177        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):
4180class TryCast(Cast):
4181    pass
key = 'trycast'
class CastToStrType(Func):
4184class CastToStrType(Func):
4185    arg_types = {"this": True, "to": True}
arg_types = {'this': True, 'to': True}
key = 'casttostrtype'
class Collate(Binary):
4188class Collate(Binary):
4189    pass
key = 'collate'
class Ceil(Func):
4192class Ceil(Func):
4193    arg_types = {"this": True, "decimals": False}
4194    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4197class Coalesce(Func):
4198    arg_types = {"this": True, "expressions": False}
4199    is_var_len_args = True
4200    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4203class Concat(Func):
4204    arg_types = {"expressions": True}
4205    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4208class SafeConcat(Concat):
4209    pass
key = 'safeconcat'
class ConcatWs(Concat):
4212class ConcatWs(Concat):
4213    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4216class Count(AggFunc):
4217    arg_types = {"this": False, "expressions": False}
4218    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4221class CountIf(AggFunc):
4222    pass
key = 'countif'
class CurrentDate(Func):
4225class CurrentDate(Func):
4226    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4229class CurrentDatetime(Func):
4230    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4233class CurrentTime(Func):
4234    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4237class CurrentTimestamp(Func):
4238    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4241class CurrentUser(Func):
4242    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4245class DateAdd(Func, TimeUnit):
4246    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4249class DateSub(Func, TimeUnit):
4250    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4253class DateDiff(Func, TimeUnit):
4254    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4255    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4258class DateTrunc(Func):
4259    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4262class DatetimeAdd(Func, TimeUnit):
4263    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4266class DatetimeSub(Func, TimeUnit):
4267    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4270class DatetimeDiff(Func, TimeUnit):
4271    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4274class DatetimeTrunc(Func, TimeUnit):
4275    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4278class DayOfWeek(Func):
4279    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4282class DayOfMonth(Func):
4283    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4286class DayOfYear(Func):
4287    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4290class WeekOfYear(Func):
4291    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4294class MonthsBetween(Func):
4295    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4298class LastDateOfMonth(Func):
4299    pass
key = 'lastdateofmonth'
class Extract(Func):
4302class Extract(Func):
4303    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4306class TimestampAdd(Func, TimeUnit):
4307    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4310class TimestampSub(Func, TimeUnit):
4311    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4314class TimestampDiff(Func, TimeUnit):
4315    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4318class TimestampTrunc(Func, TimeUnit):
4319    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4322class TimeAdd(Func, TimeUnit):
4323    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4326class TimeSub(Func, TimeUnit):
4327    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4330class TimeDiff(Func, TimeUnit):
4331    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4334class TimeTrunc(Func, TimeUnit):
4335    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4338class DateFromParts(Func):
4339    _sql_names = ["DATEFROMPARTS"]
4340    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4343class DateStrToDate(Func):
4344    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4347class DateToDateStr(Func):
4348    pass
key = 'datetodatestr'
class DateToDi(Func):
4351class DateToDi(Func):
4352    pass
key = 'datetodi'
class Date(Func):
4356class Date(Func):
4357    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4360class Day(Func):
4361    pass
key = 'day'
class Decode(Func):
4364class Decode(Func):
4365    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4368class DiToDate(Func):
4369    pass
key = 'ditodate'
class Encode(Func):
4372class Encode(Func):
4373    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4376class Exp(Func):
4377    pass
key = 'exp'
class Explode(Func):
4380class Explode(Func):
4381    pass
key = 'explode'
class Floor(Func):
4384class Floor(Func):
4385    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4388class FromBase64(Func):
4389    pass
key = 'frombase64'
class ToBase64(Func):
4392class ToBase64(Func):
4393    pass
key = 'tobase64'
class Greatest(Func):
4396class Greatest(Func):
4397    arg_types = {"this": True, "expressions": False}
4398    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4401class GroupConcat(Func):
4402    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4405class Hex(Func):
4406    pass
key = 'hex'
class Xor(Connector, Func):
4409class Xor(Connector, Func):
4410    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4413class If(Func):
4414    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4417class Initcap(Func):
4418    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4421class IsNan(Func):
4422    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class JSONKeyValue(Expression):
4425class JSONKeyValue(Expression):
4426    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4429class JSONObject(Func):
4430    arg_types = {
4431        "expressions": False,
4432        "null_handling": False,
4433        "unique_keys": False,
4434        "return_type": False,
4435        "format_json": False,
4436        "encoding": False,
4437    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4440class OpenJSONColumnDef(Expression):
4441    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):
4444class OpenJSON(Func):
4445    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4448class JSONBContains(Binary):
4449    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4452class JSONExtract(Binary, Func):
4453    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4456class JSONExtractScalar(JSONExtract):
4457    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4460class JSONBExtract(JSONExtract):
4461    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4464class JSONBExtractScalar(JSONExtract):
4465    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4468class JSONFormat(Func):
4469    arg_types = {"this": False, "options": False}
4470    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4474class JSONArrayContains(Binary, Predicate, Func):
4475    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4478class Least(Func):
4479    arg_types = {"this": True, "expressions": False}
4480    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4483class Left(Func):
4484    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4491class Length(Func):
4492    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4495class Levenshtein(Func):
4496    arg_types = {
4497        "this": True,
4498        "expression": False,
4499        "ins_cost": False,
4500        "del_cost": False,
4501        "sub_cost": False,
4502    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4505class Ln(Func):
4506    pass
key = 'ln'
class Log(Func):
4509class Log(Func):
4510    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4513class Log2(Func):
4514    pass
key = 'log2'
class Log10(Func):
4517class Log10(Func):
4518    pass
key = 'log10'
class LogicalOr(AggFunc):
4521class LogicalOr(AggFunc):
4522    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4525class LogicalAnd(AggFunc):
4526    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4529class Lower(Func):
4530    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4533class Map(Func):
4534    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4537class MapFromEntries(Func):
4538    pass
key = 'mapfromentries'
class StarMap(Func):
4541class StarMap(Func):
4542    pass
key = 'starmap'
class VarMap(Func):
4545class VarMap(Func):
4546    arg_types = {"keys": True, "values": True}
4547    is_var_len_args = True
4548
4549    @property
4550    def keys(self) -> t.List[Expression]:
4551        return self.args["keys"].expressions
4552
4553    @property
4554    def values(self) -> t.List[Expression]:
4555        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4559class MatchAgainst(Func):
4560    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4563class Max(AggFunc):
4564    arg_types = {"this": True, "expressions": False}
4565    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4568class MD5(Func):
4569    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4573class MD5Digest(Func):
4574    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4577class Min(AggFunc):
4578    arg_types = {"this": True, "expressions": False}
4579    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4582class Month(Func):
4583    pass
key = 'month'
class Nvl2(Func):
4586class Nvl2(Func):
4587    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4590class Posexplode(Func):
4591    pass
key = 'posexplode'
class Pow(Binary, Func):
4594class Pow(Binary, Func):
4595    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4598class PercentileCont(AggFunc):
4599    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4602class PercentileDisc(AggFunc):
4603    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4606class Quantile(AggFunc):
4607    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4610class ApproxQuantile(Quantile):
4611    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):
4614class RangeN(Func):
4615    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4618class ReadCSV(Func):
4619    _sql_names = ["READ_CSV"]
4620    is_var_len_args = True
4621    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4624class Reduce(Func):
4625    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):
4628class RegexpExtract(Func):
4629    arg_types = {
4630        "this": True,
4631        "expression": True,
4632        "position": False,
4633        "occurrence": False,
4634        "parameters": False,
4635        "group": False,
4636    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4639class RegexpReplace(Func):
4640    arg_types = {
4641        "this": True,
4642        "expression": True,
4643        "replacement": True,
4644        "position": False,
4645        "occurrence": False,
4646        "parameters": False,
4647    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4650class RegexpLike(Binary, Func):
4651    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4654class RegexpILike(Func):
4655    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4660class RegexpSplit(Func):
4661    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4664class Repeat(Func):
4665    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4668class Round(Func):
4669    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4672class RowNumber(Func):
4673    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4676class SafeDivide(Func):
4677    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4680class SetAgg(AggFunc):
4681    pass
key = 'setagg'
class SHA(Func):
4684class SHA(Func):
4685    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4688class SHA2(Func):
4689    _sql_names = ["SHA2"]
4690    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4693class SortArray(Func):
4694    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4697class Split(Func):
4698    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4703class Substring(Func):
4704    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4707class StandardHash(Func):
4708    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4711class StartsWith(Func):
4712    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4713    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4716class StrPosition(Func):
4717    arg_types = {
4718        "this": True,
4719        "substr": True,
4720        "position": False,
4721        "instance": False,
4722    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4725class StrToDate(Func):
4726    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4729class StrToTime(Func):
4730    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4735class StrToUnix(Func):
4736    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class StrToMap(Func):
4741class StrToMap(Func):
4742    arg_types = {
4743        "this": True,
4744        "pair_delim": False,
4745        "key_value_delim": False,
4746        "duplicate_resolution_callback": False,
4747    }
arg_types = {'this': True, 'pair_delim': False, 'key_value_delim': False, 'duplicate_resolution_callback': False}
key = 'strtomap'
class NumberToStr(Func):
4750class NumberToStr(Func):
4751    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'numbertostr'
class FromBase(Func):
4754class FromBase(Func):
4755    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4758class Struct(Func):
4759    arg_types = {"expressions": True}
4760    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4763class StructExtract(Func):
4764    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Stuff(Func):
4769class Stuff(Func):
4770    _sql_names = ["STUFF", "INSERT"]
4771    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):
4774class Sum(AggFunc):
4775    pass
key = 'sum'
class Sqrt(Func):
4778class Sqrt(Func):
4779    pass
key = 'sqrt'
class Stddev(AggFunc):
4782class Stddev(AggFunc):
4783    pass
key = 'stddev'
class StddevPop(AggFunc):
4786class StddevPop(AggFunc):
4787    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4790class StddevSamp(AggFunc):
4791    pass
key = 'stddevsamp'
class TimeToStr(Func):
4794class TimeToStr(Func):
4795    arg_types = {"this": True, "format": True, "culture": False}
arg_types = {'this': True, 'format': True, 'culture': False}
key = 'timetostr'
class TimeToTimeStr(Func):
4798class TimeToTimeStr(Func):
4799    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4802class TimeToUnix(Func):
4803    pass
key = 'timetounix'
class TimeStrToDate(Func):
4806class TimeStrToDate(Func):
4807    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4810class TimeStrToTime(Func):
4811    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4814class TimeStrToUnix(Func):
4815    pass
key = 'timestrtounix'
class Trim(Func):
4818class Trim(Func):
4819    arg_types = {
4820        "this": True,
4821        "expression": False,
4822        "position": False,
4823        "collation": False,
4824    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4827class TsOrDsAdd(Func, TimeUnit):
4828    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4831class TsOrDsToDateStr(Func):
4832    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4835class TsOrDsToDate(Func):
4836    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4839class TsOrDiToDi(Func):
4840    pass
key = 'tsorditodi'
class Unhex(Func):
4843class Unhex(Func):
4844    pass
key = 'unhex'
class UnixToStr(Func):
4847class UnixToStr(Func):
4848    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4853class UnixToTime(Func):
4854    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4855
4856    SECONDS = Literal.string("seconds")
4857    MILLIS = Literal.string("millis")
4858    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):
4861class UnixToTimeStr(Func):
4862    pass
key = 'unixtotimestr'
class Upper(Func):
4865class Upper(Func):
4866    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4869class Variance(AggFunc):
4870    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4873class VariancePop(AggFunc):
4874    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4877class Week(Func):
4878    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4881class XMLTable(Func):
4882    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):
4885class Year(Func):
4886    pass
key = 'year'
class Use(Expression):
4889class Use(Expression):
4890    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4893class Merge(Expression):
4894    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):
4897class When(Func):
4898    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):
4903class NextValueFor(Func):
4904    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.First'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.IsNan'>, <class 'sqlglot.expressions.JSONArrayContains'>, <class 'sqlglot.expressions.JSONBExtract'>, <class 'sqlglot.expressions.JSONBExtractScalar'>, <class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.JSONExtractScalar'>, <class 'sqlglot.expressions.JSONFormat'>, <class 'sqlglot.expressions.JSONObject'>, <class 'sqlglot.expressions.Last'>, <class 'sqlglot.expressions.LastDateOfMonth'>, <class 'sqlglot.expressions.Least'>, <class 'sqlglot.expressions.Left'>, <class 'sqlglot.expressions.Length'>, <class 'sqlglot.expressions.Levenshtein'>, <class 'sqlglot.expressions.Ln'>, <class 'sqlglot.expressions.Log'>, <class 'sqlglot.expressions.Log10'>, <class 'sqlglot.expressions.Log2'>, <class 'sqlglot.expressions.LogicalAnd'>, <class 'sqlglot.expressions.LogicalOr'>, <class 'sqlglot.expressions.Lower'>, <class 'sqlglot.expressions.MD5'>, <class 'sqlglot.expressions.MD5Digest'>, <class 'sqlglot.expressions.Map'>, <class 'sqlglot.expressions.MapFromEntries'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <class 'sqlglot.expressions.MonthsBetween'>, <class 'sqlglot.expressions.NextValueFor'>, <class 'sqlglot.expressions.NumberToStr'>, <class 'sqlglot.expressions.Nvl2'>, <class 'sqlglot.expressions.OpenJSON'>, <class 'sqlglot.expressions.ParameterizedAgg'>, <class 'sqlglot.expressions.PercentileCont'>, <class 'sqlglot.expressions.PercentileDisc'>, <class 'sqlglot.expressions.Posexplode'>, <class 'sqlglot.expressions.Pow'>, <class 'sqlglot.expressions.Quantile'>, <class 'sqlglot.expressions.RangeN'>, <class 'sqlglot.expressions.ReadCSV'>, <class 'sqlglot.expressions.Reduce'>, <class 'sqlglot.expressions.RegexpExtract'>, <class 'sqlglot.expressions.RegexpILike'>, <class 'sqlglot.expressions.RegexpLike'>, <class 'sqlglot.expressions.RegexpReplace'>, <class 'sqlglot.expressions.RegexpSplit'>, <class 'sqlglot.expressions.Repeat'>, <class 'sqlglot.expressions.Right'>, <class 'sqlglot.expressions.Round'>, <class 'sqlglot.expressions.RowNumber'>, <class 'sqlglot.expressions.SHA'>, <class 'sqlglot.expressions.SHA2'>, <class 'sqlglot.expressions.SafeConcat'>, <class 'sqlglot.expressions.SafeDivide'>, <class 'sqlglot.expressions.SetAgg'>, <class 'sqlglot.expressions.SortArray'>, <class 'sqlglot.expressions.Split'>, <class 'sqlglot.expressions.Sqrt'>, <class 'sqlglot.expressions.StandardHash'>, <class 'sqlglot.expressions.StarMap'>, <class 'sqlglot.expressions.StartsWith'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToMap'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Stuff'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.Transform'>, <class 'sqlglot.expressions.Trim'>, <class 'sqlglot.expressions.TryCast'>, <class 'sqlglot.expressions.TsOrDiToDi'>, <class 'sqlglot.expressions.TsOrDsAdd'>, <class 'sqlglot.expressions.TsOrDsToDate'>, <class 'sqlglot.expressions.TsOrDsToDateStr'>, <class 'sqlglot.expressions.Unhex'>, <class 'sqlglot.expressions.UnixToStr'>, <class 'sqlglot.expressions.UnixToTime'>, <class 'sqlglot.expressions.UnixToTimeStr'>, <class 'sqlglot.expressions.Upper'>, <class 'sqlglot.expressions.VarMap'>, <class 'sqlglot.expressions.Variance'>, <class 'sqlglot.expressions.VariancePop'>, <class 'sqlglot.expressions.Week'>, <class 'sqlglot.expressions.WeekOfYear'>, <class 'sqlglot.expressions.When'>, <class 'sqlglot.expressions.XMLTable'>, <class 'sqlglot.expressions.Xor'>, <class 'sqlglot.expressions.Year'>]
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4941def maybe_parse(
4942    sql_or_expression: ExpOrStr,
4943    *,
4944    into: t.Optional[IntoType] = None,
4945    dialect: DialectType = None,
4946    prefix: t.Optional[str] = None,
4947    copy: bool = False,
4948    **opts,
4949) -> Expression:
4950    """Gracefully handle a possible string or expression.
4951
4952    Example:
4953        >>> maybe_parse("1")
4954        (LITERAL this: 1, is_string: False)
4955        >>> maybe_parse(to_identifier("x"))
4956        (IDENTIFIER this: x, quoted: False)
4957
4958    Args:
4959        sql_or_expression: the SQL code string or an expression
4960        into: the SQLGlot Expression to parse into
4961        dialect: the dialect used to parse the input expressions (in the case that an
4962            input expression is a SQL string).
4963        prefix: a string to prefix the sql with before it gets parsed
4964            (automatically includes a space)
4965        copy: whether or not to copy the expression.
4966        **opts: other options to use to parse the input expressions (again, in the case
4967            that an input expression is a SQL string).
4968
4969    Returns:
4970        Expression: the parsed or given expression.
4971    """
4972    if isinstance(sql_or_expression, Expression):
4973        if copy:
4974            return sql_or_expression.copy()
4975        return sql_or_expression
4976
4977    if sql_or_expression is None:
4978        raise ParseError(f"SQL cannot be None")
4979
4980    import sqlglot
4981
4982    sql = str(sql_or_expression)
4983    if prefix:
4984        sql = f"{prefix} {sql}"
4985
4986    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):
4999def maybe_copy(instance, copy=True):
5000    return instance.copy() if copy and instance else instance
def union( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Union:
5180def union(
5181    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5182) -> Union:
5183    """
5184    Initializes a syntax tree from one UNION expression.
5185
5186    Example:
5187        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5188        'SELECT * FROM foo UNION SELECT * FROM bla'
5189
5190    Args:
5191        left: the SQL code string corresponding to the left-hand side.
5192            If an `Expression` instance is passed, it will be used as-is.
5193        right: the SQL code string corresponding to the right-hand side.
5194            If an `Expression` instance is passed, it will be used as-is.
5195        distinct: set the DISTINCT flag if and only if this is true.
5196        dialect: the dialect used to parse the input expression.
5197        opts: other options to use to parse the input expressions.
5198
5199    Returns:
5200        The new Union instance.
5201    """
5202    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5203    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5204
5205    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

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

The new Union instance.

def intersect( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Intersect:
5208def intersect(
5209    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5210) -> Intersect:
5211    """
5212    Initializes a syntax tree from one INTERSECT expression.
5213
5214    Example:
5215        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5216        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5217
5218    Args:
5219        left: the SQL code string corresponding to the left-hand side.
5220            If an `Expression` instance is passed, it will be used as-is.
5221        right: the SQL code string corresponding to the right-hand side.
5222            If an `Expression` instance is passed, it will be used as-is.
5223        distinct: set the DISTINCT flag if and only if this is true.
5224        dialect: the dialect used to parse the input expression.
5225        opts: other options to use to parse the input expressions.
5226
5227    Returns:
5228        The new Intersect instance.
5229    """
5230    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5231    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5232
5233    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

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

The new Intersect instance.

def except_( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Except:
5236def except_(
5237    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5238) -> Except:
5239    """
5240    Initializes a syntax tree from one EXCEPT expression.
5241
5242    Example:
5243        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5244        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5245
5246    Args:
5247        left: the SQL code string corresponding to the left-hand side.
5248            If an `Expression` instance is passed, it will be used as-is.
5249        right: the SQL code string corresponding to the right-hand side.
5250            If an `Expression` instance is passed, it will be used as-is.
5251        distinct: set the DISTINCT flag if and only if this is true.
5252        dialect: the dialect used to parse the input expression.
5253        opts: other options to use to parse the input expressions.
5254
5255    Returns:
5256        The new Except instance.
5257    """
5258    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5259    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5260
5261    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

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

The new Except instance.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5264def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5265    """
5266    Initializes a syntax tree from one or multiple SELECT expressions.
5267
5268    Example:
5269        >>> select("col1", "col2").from_("tbl").sql()
5270        'SELECT col1, col2 FROM tbl'
5271
5272    Args:
5273        *expressions: the SQL code string to parse as the expressions of a
5274            SELECT statement. If an Expression instance is passed, this is used as-is.
5275        dialect: the dialect used to parse the input expressions (in the case that an
5276            input expression is a SQL string).
5277        **opts: other options to use to parse the input expressions (again, in the case
5278            that an input expression is a SQL string).
5279
5280    Returns:
5281        Select: the syntax tree for the SELECT statement.
5282    """
5283    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5286def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5287    """
5288    Initializes a syntax tree from a FROM expression.
5289
5290    Example:
5291        >>> from_("tbl").select("col1", "col2").sql()
5292        'SELECT col1, col2 FROM tbl'
5293
5294    Args:
5295        *expression: the SQL code string to parse as the FROM expressions of a
5296            SELECT statement. If an Expression instance is passed, this is used as-is.
5297        dialect: the dialect used to parse the input expression (in the case that the
5298            input expression is a SQL string).
5299        **opts: other options to use to parse the input expressions (again, in the case
5300            that the input expression is a SQL string).
5301
5302    Returns:
5303        Select: the syntax tree for the SELECT statement.
5304    """
5305    return Select().from_(expression, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expression: the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
5308def update(
5309    table: str | Table,
5310    properties: dict,
5311    where: t.Optional[ExpOrStr] = None,
5312    from_: t.Optional[ExpOrStr] = None,
5313    dialect: DialectType = None,
5314    **opts,
5315) -> Update:
5316    """
5317    Creates an update statement.
5318
5319    Example:
5320        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5321        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5322
5323    Args:
5324        *properties: dictionary of properties to set which are
5325            auto converted to sql objects eg None -> NULL
5326        where: sql conditional parsed into a WHERE statement
5327        from_: sql statement parsed into a FROM statement
5328        dialect: the dialect used to parse the input expressions.
5329        **opts: other options to use to parse the input expressions.
5330
5331    Returns:
5332        Update: the syntax tree for the UPDATE statement.
5333    """
5334    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5335    update_expr.set(
5336        "expressions",
5337        [
5338            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5339            for k, v in properties.items()
5340        ],
5341    )
5342    if from_:
5343        update_expr.set(
5344            "from",
5345            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5346        )
5347    if isinstance(where, Condition):
5348        where = Where(this=where)
5349    if where:
5350        update_expr.set(
5351            "where",
5352            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5353        )
5354    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
5357def delete(
5358    table: ExpOrStr,
5359    where: t.Optional[ExpOrStr] = None,
5360    returning: t.Optional[ExpOrStr] = None,
5361    dialect: DialectType = None,
5362    **opts,
5363) -> Delete:
5364    """
5365    Builds a delete statement.
5366
5367    Example:
5368        >>> delete("my_table", where="id > 1").sql()
5369        'DELETE FROM my_table WHERE id > 1'
5370
5371    Args:
5372        where: sql conditional parsed into a WHERE statement
5373        returning: sql conditional parsed into a RETURNING statement
5374        dialect: the dialect used to parse the input expressions.
5375        **opts: other options to use to parse the input expressions.
5376
5377    Returns:
5378        Delete: the syntax tree for the DELETE statement.
5379    """
5380    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5381    if where:
5382        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5383    if returning:
5384        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5385    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def insert( expression: Union[str, sqlglot.expressions.Expression], into: Union[str, sqlglot.expressions.Expression], columns: Optional[Sequence[Union[str, sqlglot.expressions.Expression]]] = None, overwrite: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Insert:
5388def insert(
5389    expression: ExpOrStr,
5390    into: ExpOrStr,
5391    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5392    overwrite: t.Optional[bool] = None,
5393    dialect: DialectType = None,
5394    copy: bool = True,
5395    **opts,
5396) -> Insert:
5397    """
5398    Builds an INSERT statement.
5399
5400    Example:
5401        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5402        'INSERT INTO tbl VALUES (1, 2, 3)'
5403
5404    Args:
5405        expression: the sql string or expression of the INSERT statement
5406        into: the tbl to insert data to.
5407        columns: optionally the table's column names.
5408        overwrite: whether to INSERT OVERWRITE or not.
5409        dialect: the dialect used to parse the input expressions.
5410        copy: whether or not to copy the expression.
5411        **opts: other options to use to parse the input expressions.
5412
5413    Returns:
5414        Insert: the syntax tree for the INSERT statement.
5415    """
5416    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5417    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5418
5419    if columns:
5420        this = _apply_list_builder(
5421            *columns,
5422            instance=Schema(this=this),
5423            arg="expressions",
5424            into=Identifier,
5425            copy=False,
5426            dialect=dialect,
5427            **opts,
5428        )
5429
5430    return Insert(this=this, expression=expr, overwrite=overwrite)

Builds an INSERT statement.

Example:
>>> insert("VALUES (1, 2, 3)", "tbl").sql()
'INSERT INTO tbl VALUES (1, 2, 3)'
Arguments:
  • expression: the sql string or expression of the INSERT statement
  • into: the tbl to insert data to.
  • columns: optionally the table's column names.
  • overwrite: whether to INSERT OVERWRITE or not.
  • dialect: the dialect used to parse the input expressions.
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Insert: the syntax tree for the INSERT statement.

def condition( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5433def condition(
5434    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5435) -> Condition:
5436    """
5437    Initialize a logical condition expression.
5438
5439    Example:
5440        >>> condition("x=1").sql()
5441        'x = 1'
5442
5443        This is helpful for composing larger logical syntax trees:
5444        >>> where = condition("x=1")
5445        >>> where = where.and_("y=1")
5446        >>> Select().from_("tbl").select("*").where(where).sql()
5447        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5448
5449    Args:
5450        *expression: the SQL code string to parse.
5451            If an Expression instance is passed, this is used as-is.
5452        dialect: the dialect used to parse the input expression (in the case that the
5453            input expression is a SQL string).
5454        copy: Whether or not to copy `expression` (only applies to expressions).
5455        **opts: other options to use to parse the input expressions (again, in the case
5456            that the input expression is a SQL string).
5457
5458    Returns:
5459        The new Condition instance
5460    """
5461    return maybe_parse(
5462        expression,
5463        into=Condition,
5464        dialect=dialect,
5465        copy=copy,
5466        **opts,
5467    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • copy: Whether or not to copy expression (only applies to expressions).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

The new Condition instance

def and_( *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5470def and_(
5471    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5472) -> Condition:
5473    """
5474    Combine multiple conditions with an AND logical operator.
5475
5476    Example:
5477        >>> and_("x=1", and_("y=1", "z=1")).sql()
5478        'x = 1 AND (y = 1 AND z = 1)'
5479
5480    Args:
5481        *expressions: the SQL code strings to parse.
5482            If an Expression instance is passed, this is used as-is.
5483        dialect: the dialect used to parse the input expression.
5484        copy: whether or not to copy `expressions` (only applies to Expressions).
5485        **opts: other options to use to parse the input expressions.
5486
5487    Returns:
5488        And: the new condition
5489    """
5490    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))

Combine multiple conditions with an AND logical operator.

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

And: the new condition

def or_( *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5493def or_(
5494    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5495) -> Condition:
5496    """
5497    Combine multiple conditions with an OR logical operator.
5498
5499    Example:
5500        >>> or_("x=1", or_("y=1", "z=1")).sql()
5501        'x = 1 OR (y = 1 OR z = 1)'
5502
5503    Args:
5504        *expressions: the SQL code strings to parse.
5505            If an Expression instance is passed, this is used as-is.
5506        dialect: the dialect used to parse the input expression.
5507        copy: whether or not to copy `expressions` (only applies to Expressions).
5508        **opts: other options to use to parse the input expressions.
5509
5510    Returns:
5511        Or: the new condition
5512    """
5513    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))

Combine multiple conditions with an OR logical operator.

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

Or: the new condition

def not_( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Not:
5516def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5517    """
5518    Wrap a condition with a NOT operator.
5519
5520    Example:
5521        >>> not_("this_suit='black'").sql()
5522        "NOT this_suit = 'black'"
5523
5524    Args:
5525        expression: the SQL code string to parse.
5526            If an Expression instance is passed, this is used as-is.
5527        dialect: the dialect used to parse the input expression.
5528        copy: whether to copy the expression or not.
5529        **opts: other options to use to parse the input expressions.
5530
5531    Returns:
5532        The new condition.
5533    """
5534    this = condition(
5535        expression,
5536        dialect=dialect,
5537        copy=copy,
5538        **opts,
5539    )
5540    return Not(this=_wrap(this, Connector))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the expression or not.
  • **opts: other options to use to parse the input expressions.
Returns:

The new condition.

def paren( expression: Union[str, sqlglot.expressions.Expression], copy: bool = True) -> sqlglot.expressions.Paren:
5543def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5544    """
5545    Wrap an expression in parentheses.
5546
5547    Example:
5548        >>> paren("5 + 3").sql()
5549        '(5 + 3)'
5550
5551    Args:
5552        expression: the SQL code string to parse.
5553            If an Expression instance is passed, this is used as-is.
5554        copy: whether to copy the expression or not.
5555
5556    Returns:
5557        The wrapped expression.
5558    """
5559    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):
5577def to_identifier(name, quoted=None, copy=True):
5578    """Builds an identifier.
5579
5580    Args:
5581        name: The name to turn into an identifier.
5582        quoted: Whether or not force quote the identifier.
5583        copy: Whether or not to copy a passed in Identefier node.
5584
5585    Returns:
5586        The identifier ast node.
5587    """
5588
5589    if name is None:
5590        return None
5591
5592    if isinstance(name, Identifier):
5593        identifier = maybe_copy(name, copy)
5594    elif isinstance(name, str):
5595        identifier = Identifier(
5596            this=name,
5597            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5598        )
5599    else:
5600        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5601    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
  • copy: Whether or not to copy a passed in Identefier node.
Returns:

The identifier ast node.

INTERVAL_STRING_RE = re.compile('\\s*([0-9]+)\\s*([a-zA-Z]+)\\s*')
def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
5607def to_interval(interval: str | Literal) -> Interval:
5608    """Builds an interval expression from a string like '1 day' or '5 months'."""
5609    if isinstance(interval, Literal):
5610        if not interval.is_string:
5611            raise ValueError("Invalid interval string.")
5612
5613        interval = interval.this
5614
5615    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5616
5617    if not interval_parts:
5618        raise ValueError("Invalid interval string.")
5619
5620    return Interval(
5621        this=Literal.string(interval_parts.group(1)),
5622        unit=Var(this=interval_parts.group(2)),
5623    )

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

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Optional[sqlglot.expressions.Table]:
5636def to_table(
5637    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5638) -> t.Optional[Table]:
5639    """
5640    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5641    If a table is passed in then that table is returned.
5642
5643    Args:
5644        sql_path: a `[catalog].[schema].[table]` string.
5645        dialect: the source dialect according to which the table name will be parsed.
5646        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5647
5648    Returns:
5649        A table expression.
5650    """
5651    if sql_path is None or isinstance(sql_path, Table):
5652        return sql_path
5653    if not isinstance(sql_path, str):
5654        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5655
5656    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5657    if table:
5658        for k, v in kwargs.items():
5659            table.set(k, v)
5660
5661    return table

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
  • dialect: the source dialect according to which the table name will be parsed.
  • kwargs: the kwargs to instantiate the resulting Table expression with.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
5664def to_column(sql_path: str | Column, **kwargs) -> Column:
5665    """
5666    Create a column from a `[table].[column]` sql path. Schema is optional.
5667
5668    If a column is passed in then that column is returned.
5669
5670    Args:
5671        sql_path: `[table].[column]` string
5672    Returns:
5673        Table: A column expression
5674    """
5675    if sql_path is None or isinstance(sql_path, Column):
5676        return sql_path
5677    if not isinstance(sql_path, str):
5678        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5679    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts):
5682def alias_(
5683    expression: ExpOrStr,
5684    alias: str | Identifier,
5685    table: bool | t.Sequence[str | Identifier] = False,
5686    quoted: t.Optional[bool] = None,
5687    dialect: DialectType = None,
5688    copy: bool = True,
5689    **opts,
5690):
5691    """Create an Alias expression.
5692
5693    Example:
5694        >>> alias_('foo', 'bar').sql()
5695        'foo AS bar'
5696
5697        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5698        '(SELECT 1, 2) AS bar(a, b)'
5699
5700    Args:
5701        expression: the SQL code strings to parse.
5702            If an Expression instance is passed, this is used as-is.
5703        alias: the alias name to use. If the name has
5704            special characters it is quoted.
5705        table: Whether or not to create a table alias, can also be a list of columns.
5706        quoted: whether or not to quote the alias
5707        dialect: the dialect used to parse the input expression.
5708        copy: Whether or not to copy the expression.
5709        **opts: other options to use to parse the input expressions.
5710
5711    Returns:
5712        Alias: the aliased expression
5713    """
5714    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5715    alias = to_identifier(alias, quoted=quoted)
5716
5717    if table:
5718        table_alias = TableAlias(this=alias)
5719        exp.set("alias", table_alias)
5720
5721        if not isinstance(table, bool):
5722            for column in table:
5723                table_alias.append("columns", to_identifier(column, quoted=quoted))
5724
5725        return exp
5726
5727    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5728    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5729    # for the complete Window expression.
5730    #
5731    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5732
5733    if "alias" in exp.arg_types and not isinstance(exp, Window):
5734        exp.set("alias", alias)
5735        return exp
5736    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • copy: Whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery( expression: Union[str, sqlglot.expressions.Expression], alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5739def subquery(
5740    expression: ExpOrStr,
5741    alias: t.Optional[Identifier | str] = None,
5742    dialect: DialectType = None,
5743    **opts,
5744) -> Select:
5745    """
5746    Build a subquery expression.
5747
5748    Example:
5749        >>> subquery('select x from tbl', 'bar').select('x').sql()
5750        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5751
5752    Args:
5753        expression: the SQL code strings to parse.
5754            If an Expression instance is passed, this is used as-is.
5755        alias: the alias name to use.
5756        dialect: the dialect used to parse the input expression.
5757        **opts: other options to use to parse the input expressions.
5758
5759    Returns:
5760        A new Select instance with the subquery expression included.
5761    """
5762
5763    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5764    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use.
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

A new Select instance with the subquery expression included.

def column( col: str | sqlglot.expressions.Identifier, table: Union[sqlglot.expressions.Identifier, str, NoneType] = None, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
5767def column(
5768    col: str | Identifier,
5769    table: t.Optional[str | Identifier] = None,
5770    db: t.Optional[str | Identifier] = None,
5771    catalog: t.Optional[str | Identifier] = None,
5772    quoted: t.Optional[bool] = None,
5773) -> Column:
5774    """
5775    Build a Column.
5776
5777    Args:
5778        col: Column name.
5779        table: Table name.
5780        db: Database name.
5781        catalog: Catalog name.
5782        quoted: Whether to force quotes on the column's identifiers.
5783
5784    Returns:
5785        The new Column instance.
5786    """
5787    return Column(
5788        this=to_identifier(col, quoted=quoted),
5789        table=to_identifier(table, quoted=quoted),
5790        db=to_identifier(db, quoted=quoted),
5791        catalog=to_identifier(catalog, quoted=quoted),
5792    )

Build a Column.

Arguments:
  • col: Column name.
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quoted: Whether to force quotes on the column's identifiers.
Returns:

The new Column instance.

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
5795def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5796    """Cast an expression to a data type.
5797
5798    Example:
5799        >>> cast('x + 1', 'int').sql()
5800        'CAST(x + 1 AS INT)'
5801
5802    Args:
5803        expression: The expression to cast.
5804        to: The datatype to cast to.
5805
5806    Returns:
5807        The new Cast instance.
5808    """
5809    expression = maybe_parse(expression, **opts)
5810    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

The new Cast instance.

def table_( table: sqlglot.expressions.Identifier | str, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None, alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None) -> sqlglot.expressions.Table:
5813def table_(
5814    table: Identifier | str,
5815    db: t.Optional[Identifier | str] = None,
5816    catalog: t.Optional[Identifier | str] = None,
5817    quoted: t.Optional[bool] = None,
5818    alias: t.Optional[Identifier | str] = None,
5819) -> Table:
5820    """Build a Table.
5821
5822    Args:
5823        table: Table name.
5824        db: Database name.
5825        catalog: Catalog name.
5826        quote: Whether to force quotes on the table's identifiers.
5827        alias: Table's alias.
5828
5829    Returns:
5830        The new Table instance.
5831    """
5832    return Table(
5833        this=to_identifier(table, quoted=quoted),
5834        db=to_identifier(db, quoted=quoted),
5835        catalog=to_identifier(catalog, quoted=quoted),
5836        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5837    )

Build a Table.

Arguments:
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quote: Whether to force quotes on the table's identifiers.
  • alias: Table's alias.
Returns:

The new Table instance.

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
5840def values(
5841    values: t.Iterable[t.Tuple[t.Any, ...]],
5842    alias: t.Optional[str] = None,
5843    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5844) -> Values:
5845    """Build VALUES statement.
5846
5847    Example:
5848        >>> values([(1, '2')]).sql()
5849        "VALUES (1, '2')"
5850
5851    Args:
5852        values: values statements that will be converted to SQL
5853        alias: optional alias
5854        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5855         If either are provided then an alias is also required.
5856
5857    Returns:
5858        Values: the Values expression object
5859    """
5860    if columns and not alias:
5861        raise ValueError("Alias is required when providing columns")
5862
5863    return Values(
5864        expressions=[convert(tup) for tup in values],
5865        alias=(
5866            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5867            if columns
5868            else (TableAlias(this=to_identifier(alias)) if alias else None)
5869        ),
5870    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
5873def var(name: t.Optional[ExpOrStr]) -> Var:
5874    """Build a SQL variable.
5875
5876    Example:
5877        >>> repr(var('x'))
5878        '(VAR this: x)'
5879
5880        >>> repr(var(column('x', table='y')))
5881        '(VAR this: x)'
5882
5883    Args:
5884        name: The name of the var or an expression who's name will become the var.
5885
5886    Returns:
5887        The new variable node.
5888    """
5889    if not name:
5890        raise ValueError("Cannot convert empty name into var.")
5891
5892    if isinstance(name, Expression):
5893        name = name.name
5894    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
5897def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5898    """Build ALTER TABLE... RENAME... expression
5899
5900    Args:
5901        old_name: The old name of the table
5902        new_name: The new name of the table
5903
5904    Returns:
5905        Alter table expression
5906    """
5907    old_table = to_table(old_name)
5908    new_table = to_table(new_name)
5909    return AlterTable(
5910        this=old_table,
5911        actions=[
5912            RenameTable(this=new_table),
5913        ],
5914    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value: Any, copy: bool = False) -> sqlglot.expressions.Expression:
5917def convert(value: t.Any, copy: bool = False) -> Expression:
5918    """Convert a python value into an expression object.
5919
5920    Raises an error if a conversion is not possible.
5921
5922    Args:
5923        value: A python object.
5924        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5925
5926    Returns:
5927        Expression: the equivalent expression object.
5928    """
5929    if isinstance(value, Expression):
5930        return maybe_copy(value, copy)
5931    if isinstance(value, str):
5932        return Literal.string(value)
5933    if isinstance(value, bool):
5934        return Boolean(this=value)
5935    if value is None or (isinstance(value, float) and math.isnan(value)):
5936        return NULL
5937    if isinstance(value, numbers.Number):
5938        return Literal.number(value)
5939    if isinstance(value, datetime.datetime):
5940        datetime_literal = Literal.string(
5941            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5942        )
5943        return TimeStrToTime(this=datetime_literal)
5944    if isinstance(value, datetime.date):
5945        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5946        return DateStrToDate(this=date_literal)
5947    if isinstance(value, tuple):
5948        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5949    if isinstance(value, list):
5950        return Array(expressions=[convert(v, copy=copy) for v in value])
5951    if isinstance(value, dict):
5952        return Map(
5953            keys=Array(expressions=[convert(k, copy=copy) for k in value]),
5954            values=Array(expressions=[convert(v, copy=copy) for v in value.values()]),
5955        )
5956    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value: A python object.
  • copy: Whether or not to copy value (only applies to Expressions and collections).
Returns:

Expression: the equivalent expression object.

def replace_children( expression: sqlglot.expressions.Expression, fun: Callable, *args, **kwargs) -> None:
5959def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5960    """
5961    Replace children of an expression with the result of a lambda fun(child) -> exp.
5962    """
5963    for k, v in expression.args.items():
5964        is_list_arg = type(v) is list
5965
5966        child_nodes = v if is_list_arg else [v]
5967        new_child_nodes = []
5968
5969        for cn in child_nodes:
5970            if isinstance(cn, Expression):
5971                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5972                    new_child_nodes.append(child_node)
5973                    child_node.parent = expression
5974                    child_node.arg_key = k
5975            else:
5976                new_child_nodes.append(cn)
5977
5978        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names( expression: sqlglot.expressions.Expression, exclude: str = '') -> Set[str]:
5981def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5982    """
5983    Return all table names referenced through columns in an expression.
5984
5985    Example:
5986        >>> import sqlglot
5987        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5988        ['a', 'c']
5989
5990    Args:
5991        expression: expression to find table names.
5992        exclude: a table name to exclude
5993
5994    Returns:
5995        A list of unique names.
5996    """
5997    return {
5998        table
5999        for table in (column.table for column in expression.find_all(Column))
6000        if table and table != exclude
6001    }

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
['a', 'c']
Arguments:
  • expression: expression to find table names.
  • exclude: a table name to exclude
Returns:

A list of unique names.

def table_name( table: sqlglot.expressions.Table | str, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) -> str:
6004def table_name(table: Table | str, dialect: DialectType = None) -> str:
6005    """Get the full name of a table as a string.
6006
6007    Args:
6008        table: Table expression node or string.
6009        dialect: The dialect to generate the table name for.
6010
6011    Examples:
6012        >>> from sqlglot import exp, parse_one
6013        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
6014        'a.b.c'
6015
6016    Returns:
6017        The table name.
6018    """
6019
6020    table = maybe_parse(table, into=Table)
6021
6022    if not table:
6023        raise ValueError(f"Cannot parse {table}")
6024
6025    return ".".join(
6026        part.sql(dialect=dialect, identify=True)
6027        if not SAFE_IDENTIFIER_RE.match(part.name)
6028        else part.name
6029        for part in table.parts
6030    )

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:
6033def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
6034    """Replace all tables in expression according to the mapping.
6035
6036    Args:
6037        expression: expression node to be transformed and replaced.
6038        mapping: mapping of table names.
6039        copy: whether or not to copy the expression.
6040
6041    Examples:
6042        >>> from sqlglot import exp, parse_one
6043        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
6044        'SELECT * FROM c'
6045
6046    Returns:
6047        The mapped expression.
6048    """
6049
6050    def _replace_tables(node: Expression) -> Expression:
6051        if isinstance(node, Table):
6052            new_name = mapping.get(table_name(node))
6053            if new_name:
6054                return to_table(
6055                    new_name,
6056                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
6057                )
6058        return node
6059
6060    return expression.transform(_replace_tables, copy=copy)

Replace all tables in expression according to the mapping.

Arguments:
  • expression: expression node to be transformed and replaced.
  • mapping: mapping of table names.
  • copy: whether or not to copy the expression.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders( expression: sqlglot.expressions.Expression, *args, **kwargs) -> sqlglot.expressions.Expression:
6063def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
6064    """Replace placeholders in an expression.
6065
6066    Args:
6067        expression: expression node to be transformed and replaced.
6068        args: positional names that will substitute unnamed placeholders in the given order.
6069        kwargs: keyword arguments that will substitute named placeholders.
6070
6071    Examples:
6072        >>> from sqlglot import exp, parse_one
6073        >>> replace_placeholders(
6074        ...     parse_one("select * from :tbl where ? = ?"),
6075        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
6076        ... ).sql()
6077        "SELECT * FROM foo WHERE str_col = 'b'"
6078
6079    Returns:
6080        The mapped expression.
6081    """
6082
6083    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
6084        if isinstance(node, Placeholder):
6085            if node.name:
6086                new_name = kwargs.get(node.name)
6087                if new_name:
6088                    return convert(new_name)
6089            else:
6090                try:
6091                    return convert(next(args))
6092                except StopIteration:
6093                    pass
6094        return node
6095
6096    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression: expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy: bool = True) -> sqlglot.expressions.Expression:
6099def expand(
6100    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
6101) -> Expression:
6102    """Transforms an expression by expanding all referenced sources into subqueries.
6103
6104    Examples:
6105        >>> from sqlglot import parse_one
6106        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
6107        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
6108
6109        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
6110        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
6111
6112    Args:
6113        expression: The expression to expand.
6114        sources: A dictionary of name to Subqueryables.
6115        copy: Whether or not to copy the expression during transformation. Defaults to True.
6116
6117    Returns:
6118        The transformed expression.
6119    """
6120
6121    def _expand(node: Expression):
6122        if isinstance(node, Table):
6123            name = table_name(node)
6124            source = sources.get(name)
6125            if source:
6126                subquery = source.subquery(node.alias or name)
6127                subquery.comments = [f"source: {name}"]
6128                return subquery.transform(_expand, copy=False)
6129        return node
6130
6131    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
6134def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6135    """
6136    Returns a Func expression.
6137
6138    Examples:
6139        >>> func("abs", 5).sql()
6140        'ABS(5)'
6141
6142        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6143        'CAST(5 AS DOUBLE)'
6144
6145    Args:
6146        name: the name of the function to build.
6147        args: the args used to instantiate the function of interest.
6148        dialect: the source dialect.
6149        kwargs: the kwargs used to instantiate the function of interest.
6150
6151    Note:
6152        The arguments `args` and `kwargs` are mutually exclusive.
6153
6154    Returns:
6155        An instance of the function of interest, or an anonymous function, if `name` doesn't
6156        correspond to an existing `sqlglot.expressions.Func` class.
6157    """
6158    if args and kwargs:
6159        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6160
6161    from sqlglot.dialects.dialect import Dialect
6162
6163    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6164    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6165
6166    parser = Dialect.get_or_raise(dialect)().parser()
6167    from_args_list = parser.FUNCTIONS.get(name.upper())
6168
6169    if from_args_list:
6170        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6171    else:
6172        kwargs = kwargs or {"expressions": converted}
6173        function = Anonymous(this=name, **kwargs)
6174
6175    for error_message in function.error_messages(converted):
6176        raise ValueError(error_message)
6177
6178    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true() -> sqlglot.expressions.Boolean:
6181def true() -> Boolean:
6182    """
6183    Returns a true Boolean expression.
6184    """
6185    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
6188def false() -> Boolean:
6189    """
6190    Returns a false Boolean expression.
6191    """
6192    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6195def null() -> Null:
6196    """
6197    Returns a Null expression.
6198    """
6199    return Null()

Returns a Null expression.

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