Edit on GitHub

Expressions

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

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


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

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

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

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

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

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

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

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

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

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

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

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

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

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

Returns a deep copy of the expression.

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

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

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

Sets arg_key to value.

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

Returns the depth of this tree.

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

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

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

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

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

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

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

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

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

The generator object.

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

Returns a nearest parent matching expression_types.

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

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

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

Returns the root expression of this tree.

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

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

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

the generator object.

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

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

Returns:

The generator object.

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

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

Returns:

The generator object.

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

Returns the first non parenthesis child or self.

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

Returns the inner expression if this is an Alias.

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

Returns unnested operands as a tuple.

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

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

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

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

Returns SQL string representation of this tree.

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

The SQL string.

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

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

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

The transformed tree.

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

Swap out this expression with a new expression.

For example::

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

The new expression or expressions.

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

Remove this expression from its AST.

Returns:

The popped expression.

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

Assert that this Expression is an instance of type_.

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

Examples:

This is useful for type security in chained expressions:

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

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

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

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

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

Dump this Expression to a JSON-serializable dict.

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

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

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

AND this condition with one or multiple expressions.

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

The new And condition.

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

OR this condition with one or multiple expressions.

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

The new Or condition.

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

Wrap this condition with NOT.

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

The new Not instance.

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

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

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

Builds a UNION expression.

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

The new Union expression.

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

Builds an INTERSECT expression.

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

The new Intersect expression.

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

Builds an EXCEPT expression.

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

The new Except expression.

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

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

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

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

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

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

Converts the column into a dot expression.

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

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

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

Delete: the modified expression.

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

Append to or set the WHERE expressions.

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

Delete: the modified expression.

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

Set the RETURNING expression. Not supported by all dialects.

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

Delete: the modified expression.

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

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

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

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

Append to or set the common table expressions.

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

The modified expression.

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

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

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

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

Append to or set the ON expressions.

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

The modified Join expression.

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

Append to or set the USING expressions.

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

The modified Join expression.

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

An enumeration.

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

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

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

Alias: the subquery

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

Append to or set the common table expressions.

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

The modified expression.

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

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

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

Set the LIMIT expression.

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

The limited subqueryable.

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

Append to or set the SELECT of the union recursively.

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

Union: the modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

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

Set the FROM expression.

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

The modified Select expression.

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

Set the GROUP BY expression.

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

The modified Select expression.

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

Set the ORDER BY expression.

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

The modified Select expression.

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

Set the SORT BY expression.

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

The modified Select expression.

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

Set the CLUSTER BY expression.

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

The modified Select expression.

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

Set the LIMIT expression.

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

Select: the modified expression.

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

Set the OFFSET expression.

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

The modified Select expression.

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

Append to or set the SELECT expressions.

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

The modified Select expression.

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

Append to or set the LATERAL expressions.

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

The modified Select expression.

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

Append to or set the JOIN expressions.

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

Use join_type to change the type of join:

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

Select: the modified expression.

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

Append to or set the WHERE expressions.

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

Select: the modified expression.

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

Append to or set the HAVING expressions.

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

The modified Select expression.

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

Set the OFFSET expression.

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

Select: the modified expression.

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

Convert this expression to a CREATE TABLE AS statement.

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

The new Create expression.

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

Set the locking read mode for this expression.

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

The modified expression.

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

Set hints for this expression.

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

The modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

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

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name: str

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

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

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

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3303class Pivot(Expression):
3304    arg_types = {
3305        "this": False,
3306        "alias": False,
3307        "expressions": True,
3308        "field": False,
3309        "unpivot": False,
3310        "using": False,
3311        "group": False,
3312        "columns": False,
3313    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3316class Window(Expression):
3317    arg_types = {
3318        "this": True,
3319        "partition_by": False,
3320        "order": False,
3321        "spec": False,
3322        "alias": False,
3323        "over": False,
3324        "first": False,
3325    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3328class WindowSpec(Expression):
3329    arg_types = {
3330        "kind": False,
3331        "start": False,
3332        "start_side": False,
3333        "end": False,
3334        "end_side": False,
3335    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3338class Where(Expression):
3339    pass
key = 'where'
class Star(Expression):
3342class Star(Expression):
3343    arg_types = {"except": False, "replace": False}
3344
3345    @property
3346    def name(self) -> str:
3347        return "*"
3348
3349    @property
3350    def output_name(self) -> str:
3351        return self.name
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):
3354class Parameter(Condition):
3355    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3358class SessionParameter(Condition):
3359    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3362class Placeholder(Condition):
3363    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3366class Null(Condition):
3367    arg_types: t.Dict[str, t.Any] = {}
3368
3369    @property
3370    def name(self) -> str:
3371        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3374class Boolean(Condition):
3375    pass
key = 'boolean'
class DataTypeSize(Expression):
3378class DataTypeSize(Expression):
3379    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3382class DataType(Expression):
3383    arg_types = {
3384        "this": True,
3385        "expressions": False,
3386        "nested": False,
3387        "values": False,
3388        "prefix": False,
3389    }
3390
3391    class Type(AutoName):
3392        ARRAY = auto()
3393        BIGDECIMAL = auto()
3394        BIGINT = auto()
3395        BIGSERIAL = auto()
3396        BINARY = auto()
3397        BIT = auto()
3398        BOOLEAN = auto()
3399        CHAR = auto()
3400        DATE = auto()
3401        DATETIME = auto()
3402        DATETIME64 = auto()
3403        ENUM = auto()
3404        INT4RANGE = auto()
3405        INT4MULTIRANGE = auto()
3406        INT8RANGE = auto()
3407        INT8MULTIRANGE = auto()
3408        NUMRANGE = auto()
3409        NUMMULTIRANGE = auto()
3410        TSRANGE = auto()
3411        TSMULTIRANGE = auto()
3412        TSTZRANGE = auto()
3413        TSTZMULTIRANGE = auto()
3414        DATERANGE = auto()
3415        DATEMULTIRANGE = auto()
3416        DECIMAL = auto()
3417        DOUBLE = auto()
3418        FLOAT = auto()
3419        GEOGRAPHY = auto()
3420        GEOMETRY = auto()
3421        HLLSKETCH = auto()
3422        HSTORE = auto()
3423        IMAGE = auto()
3424        INET = auto()
3425        IPADDRESS = auto()
3426        IPPREFIX = auto()
3427        INT = auto()
3428        INT128 = auto()
3429        INT256 = auto()
3430        INTERVAL = auto()
3431        JSON = auto()
3432        JSONB = auto()
3433        LONGBLOB = auto()
3434        LONGTEXT = auto()
3435        MAP = auto()
3436        MEDIUMBLOB = auto()
3437        MEDIUMTEXT = auto()
3438        MONEY = auto()
3439        NCHAR = auto()
3440        NULL = auto()
3441        NULLABLE = auto()
3442        NVARCHAR = auto()
3443        OBJECT = auto()
3444        ROWVERSION = auto()
3445        SERIAL = auto()
3446        SET = auto()
3447        SMALLINT = auto()
3448        SMALLMONEY = auto()
3449        SMALLSERIAL = auto()
3450        STRUCT = auto()
3451        SUPER = auto()
3452        TEXT = auto()
3453        TIME = auto()
3454        TIMESTAMP = auto()
3455        TIMESTAMPTZ = auto()
3456        TIMESTAMPLTZ = auto()
3457        TINYINT = auto()
3458        UBIGINT = auto()
3459        UINT = auto()
3460        USMALLINT = auto()
3461        UTINYINT = auto()
3462        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3463        UINT128 = auto()
3464        UINT256 = auto()
3465        UNIQUEIDENTIFIER = auto()
3466        USERDEFINED = "USER-DEFINED"
3467        UUID = auto()
3468        VARBINARY = auto()
3469        VARCHAR = auto()
3470        VARIANT = auto()
3471        XML = auto()
3472
3473    TEXT_TYPES = {
3474        Type.CHAR,
3475        Type.NCHAR,
3476        Type.VARCHAR,
3477        Type.NVARCHAR,
3478        Type.TEXT,
3479    }
3480
3481    INTEGER_TYPES = {
3482        Type.INT,
3483        Type.TINYINT,
3484        Type.SMALLINT,
3485        Type.BIGINT,
3486        Type.INT128,
3487        Type.INT256,
3488    }
3489
3490    FLOAT_TYPES = {
3491        Type.FLOAT,
3492        Type.DOUBLE,
3493    }
3494
3495    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3496
3497    TEMPORAL_TYPES = {
3498        Type.TIME,
3499        Type.TIMESTAMP,
3500        Type.TIMESTAMPTZ,
3501        Type.TIMESTAMPLTZ,
3502        Type.DATE,
3503        Type.DATETIME,
3504        Type.DATETIME64,
3505    }
3506
3507    META_TYPES = {"UNKNOWN", "NULL"}
3508
3509    @classmethod
3510    def build(
3511        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3512    ) -> DataType:
3513        from sqlglot import parse_one
3514
3515        if isinstance(dtype, str):
3516            upper = dtype.upper()
3517            if upper in DataType.META_TYPES:
3518                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3519            else:
3520                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3521
3522            if data_type_exp is None:
3523                raise ValueError(f"Unparsable data type value: {dtype}")
3524        elif isinstance(dtype, DataType.Type):
3525            data_type_exp = DataType(this=dtype)
3526        elif isinstance(dtype, DataType):
3527            return dtype
3528        else:
3529            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3530
3531        return DataType(**{**data_type_exp.args, **kwargs})
3532
3533    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3534        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False}
TEXT_TYPES = {<Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.TEXT: 'TEXT'>, <Type.VARCHAR: 'VARCHAR'>}
INTEGER_TYPES = {<Type.SMALLINT: 'SMALLINT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT128: 'INT128'>, <Type.INT256: 'INT256'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.SMALLINT: 'SMALLINT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>, <Type.FLOAT: 'FLOAT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT128: 'INT128'>, <Type.DOUBLE: 'DOUBLE'>, <Type.INT256: 'INT256'>}
TEMPORAL_TYPES = {<Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATETIME64: 'DATETIME64'>, <Type.DATE: 'DATE'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.DATETIME: 'DATETIME'>, <Type.TIME: 'TIME'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>}
META_TYPES = {'NULL', 'UNKNOWN'}
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
3509    @classmethod
3510    def build(
3511        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3512    ) -> DataType:
3513        from sqlglot import parse_one
3514
3515        if isinstance(dtype, str):
3516            upper = dtype.upper()
3517            if upper in DataType.META_TYPES:
3518                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3519            else:
3520                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3521
3522            if data_type_exp is None:
3523                raise ValueError(f"Unparsable data type value: {dtype}")
3524        elif isinstance(dtype, DataType.Type):
3525            data_type_exp = DataType(this=dtype)
3526        elif isinstance(dtype, DataType):
3527            return dtype
3528        else:
3529            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3530
3531        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3533    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3534        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3391    class Type(AutoName):
3392        ARRAY = auto()
3393        BIGDECIMAL = auto()
3394        BIGINT = auto()
3395        BIGSERIAL = auto()
3396        BINARY = auto()
3397        BIT = auto()
3398        BOOLEAN = auto()
3399        CHAR = auto()
3400        DATE = auto()
3401        DATETIME = auto()
3402        DATETIME64 = auto()
3403        ENUM = auto()
3404        INT4RANGE = auto()
3405        INT4MULTIRANGE = auto()
3406        INT8RANGE = auto()
3407        INT8MULTIRANGE = auto()
3408        NUMRANGE = auto()
3409        NUMMULTIRANGE = auto()
3410        TSRANGE = auto()
3411        TSMULTIRANGE = auto()
3412        TSTZRANGE = auto()
3413        TSTZMULTIRANGE = auto()
3414        DATERANGE = auto()
3415        DATEMULTIRANGE = auto()
3416        DECIMAL = auto()
3417        DOUBLE = auto()
3418        FLOAT = auto()
3419        GEOGRAPHY = auto()
3420        GEOMETRY = auto()
3421        HLLSKETCH = auto()
3422        HSTORE = auto()
3423        IMAGE = auto()
3424        INET = auto()
3425        IPADDRESS = auto()
3426        IPPREFIX = auto()
3427        INT = auto()
3428        INT128 = auto()
3429        INT256 = auto()
3430        INTERVAL = auto()
3431        JSON = auto()
3432        JSONB = auto()
3433        LONGBLOB = auto()
3434        LONGTEXT = auto()
3435        MAP = auto()
3436        MEDIUMBLOB = auto()
3437        MEDIUMTEXT = auto()
3438        MONEY = auto()
3439        NCHAR = auto()
3440        NULL = auto()
3441        NULLABLE = auto()
3442        NVARCHAR = auto()
3443        OBJECT = auto()
3444        ROWVERSION = auto()
3445        SERIAL = auto()
3446        SET = auto()
3447        SMALLINT = auto()
3448        SMALLMONEY = auto()
3449        SMALLSERIAL = auto()
3450        STRUCT = auto()
3451        SUPER = auto()
3452        TEXT = auto()
3453        TIME = auto()
3454        TIMESTAMP = auto()
3455        TIMESTAMPTZ = auto()
3456        TIMESTAMPLTZ = auto()
3457        TINYINT = auto()
3458        UBIGINT = auto()
3459        UINT = auto()
3460        USMALLINT = auto()
3461        UTINYINT = auto()
3462        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3463        UINT128 = auto()
3464        UINT256 = auto()
3465        UNIQUEIDENTIFIER = auto()
3466        USERDEFINED = "USER-DEFINED"
3467        UUID = auto()
3468        VARBINARY = auto()
3469        VARCHAR = auto()
3470        VARIANT = auto()
3471        XML = auto()

An enumeration.

ARRAY = <Type.ARRAY: 'ARRAY'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <Type.BIGINT: 'BIGINT'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
BINARY = <Type.BINARY: 'BINARY'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
CHAR = <Type.CHAR: 'CHAR'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
ENUM = <Type.ENUM: 'ENUM'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
IPADDRESS = <Type.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <Type.IPPREFIX: 'IPPREFIX'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3538class PseudoType(Expression):
3539    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3543class SubqueryPredicate(Predicate):
3544    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3547class All(SubqueryPredicate):
3548    pass
key = 'all'
class Any(SubqueryPredicate):
3551class Any(SubqueryPredicate):
3552    pass
key = 'any'
class Exists(SubqueryPredicate):
3555class Exists(SubqueryPredicate):
3556    pass
key = 'exists'
class Command(Expression):
3561class Command(Expression):
3562    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3565class Transaction(Expression):
3566    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3569class Commit(Expression):
3570    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3573class Rollback(Expression):
3574    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3577class AlterTable(Expression):
3578    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3581class AddConstraint(Expression):
3582    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3585class DropPartition(Expression):
3586    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3590class Binary(Condition):
3591    arg_types = {"this": True, "expression": True}
3592
3593    @property
3594    def left(self):
3595        return self.this
3596
3597    @property
3598    def right(self):
3599        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3602class Add(Binary):
3603    pass
key = 'add'
class Connector(Binary):
3606class Connector(Binary):
3607    pass
key = 'connector'
class And(Connector):
3610class And(Connector):
3611    pass
key = 'and'
class Or(Connector):
3614class Or(Connector):
3615    pass
key = 'or'
class BitwiseAnd(Binary):
3618class BitwiseAnd(Binary):
3619    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3622class BitwiseLeftShift(Binary):
3623    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3626class BitwiseOr(Binary):
3627    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3630class BitwiseRightShift(Binary):
3631    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3634class BitwiseXor(Binary):
3635    pass
key = 'bitwisexor'
class Div(Binary):
3638class Div(Binary):
3639    pass
key = 'div'
class Overlaps(Binary):
3642class Overlaps(Binary):
3643    pass
key = 'overlaps'
class Dot(Binary):
3646class Dot(Binary):
3647    @property
3648    def name(self) -> str:
3649        return self.expression.name
3650
3651    @property
3652    def output_name(self) -> str:
3653        return self.name
3654
3655    @classmethod
3656    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3657        """Build a Dot object with a sequence of expressions."""
3658        if len(expressions) < 2:
3659            raise ValueError(f"Dot requires >= 2 expressions.")
3660
3661        a, b, *expressions = expressions
3662        dot = Dot(this=a, expression=b)
3663
3664        for expression in expressions:
3665            dot = Dot(this=dot, expression=expression)
3666
3667        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:
3655    @classmethod
3656    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3657        """Build a Dot object with a sequence of expressions."""
3658        if len(expressions) < 2:
3659            raise ValueError(f"Dot requires >= 2 expressions.")
3660
3661        a, b, *expressions = expressions
3662        dot = Dot(this=a, expression=b)
3663
3664        for expression in expressions:
3665            dot = Dot(this=dot, expression=expression)
3666
3667        return dot

Build a Dot object with a sequence of expressions.

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

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

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

Automatically converts unit arg into a var.

TimeUnit(**args)
3852    def __init__(self, **args):
3853        unit = args.get("unit")
3854        if isinstance(unit, (Column, Literal)):
3855            args["unit"] = Var(this=unit.name)
3856        elif isinstance(unit, Week):
3857            unit.set("this", Var(this=unit.this.name))
3858
3859        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3862class Interval(TimeUnit):
3863    arg_types = {"this": False, "unit": False}
3864
3865    @property
3866    def unit(self) -> t.Optional[Var]:
3867        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3870class IgnoreNulls(Expression):
3871    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3874class RespectNulls(Expression):
3875    pass
key = 'respectnulls'
class Func(Condition):
3879class Func(Condition):
3880    """
3881    The base class for all function expressions.
3882
3883    Attributes:
3884        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3885            treated as a variable length argument and the argument's value will be stored as a list.
3886        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3887            for this function expression. These values are used to map this node to a name during parsing
3888            as well as to provide the function's name during SQL string generation. By default the SQL
3889            name is set to the expression's class name transformed to snake case.
3890    """
3891
3892    is_var_len_args = False
3893
3894    @classmethod
3895    def from_arg_list(cls, args):
3896        if cls.is_var_len_args:
3897            all_arg_keys = list(cls.arg_types)
3898            # If this function supports variable length argument treat the last argument as such.
3899            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3900            num_non_var = len(non_var_len_arg_keys)
3901
3902            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3903            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3904        else:
3905            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3906
3907        return cls(**args_dict)
3908
3909    @classmethod
3910    def sql_names(cls):
3911        if cls is Func:
3912            raise NotImplementedError(
3913                "SQL name is only supported by concrete function implementations"
3914            )
3915        if "_sql_names" not in cls.__dict__:
3916            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3917        return cls._sql_names
3918
3919    @classmethod
3920    def sql_name(cls):
3921        return cls.sql_names()[0]
3922
3923    @classmethod
3924    def default_parser_mappings(cls):
3925        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):
3894    @classmethod
3895    def from_arg_list(cls, args):
3896        if cls.is_var_len_args:
3897            all_arg_keys = list(cls.arg_types)
3898            # If this function supports variable length argument treat the last argument as such.
3899            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3900            num_non_var = len(non_var_len_arg_keys)
3901
3902            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3903            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3904        else:
3905            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3906
3907        return cls(**args_dict)
@classmethod
def sql_names(cls):
3909    @classmethod
3910    def sql_names(cls):
3911        if cls is Func:
3912            raise NotImplementedError(
3913                "SQL name is only supported by concrete function implementations"
3914            )
3915        if "_sql_names" not in cls.__dict__:
3916            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3917        return cls._sql_names
@classmethod
def sql_name(cls):
3919    @classmethod
3920    def sql_name(cls):
3921        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3923    @classmethod
3924    def default_parser_mappings(cls):
3925        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3928class AggFunc(Func):
3929    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3932class ParameterizedAgg(AggFunc):
3933    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3936class Abs(Func):
3937    pass
key = 'abs'
class Transform(Func):
3941class Transform(Func):
3942    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
3945class Anonymous(Func):
3946    arg_types = {"this": True, "expressions": False}
3947    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3952class Hll(AggFunc):
3953    arg_types = {"this": True, "expressions": False}
3954    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3957class ApproxDistinct(AggFunc):
3958    arg_types = {"this": True, "accuracy": False}
3959    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3962class Array(Func):
3963    arg_types = {"expressions": False}
3964    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3968class ToChar(Func):
3969    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3972class GenerateSeries(Func):
3973    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3976class ArrayAgg(AggFunc):
3977    pass
key = 'arrayagg'
class ArrayAll(Func):
3980class ArrayAll(Func):
3981    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3984class ArrayAny(Func):
3985    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3988class ArrayConcat(Func):
3989    arg_types = {"this": True, "expressions": False}
3990    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3993class ArrayContains(Binary, Func):
3994    pass
key = 'arraycontains'
class ArrayContained(Binary):
3997class ArrayContained(Binary):
3998    pass
key = 'arraycontained'
class ArrayFilter(Func):
4001class ArrayFilter(Func):
4002    arg_types = {"this": True, "expression": True}
4003    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4006class ArrayJoin(Func):
4007    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4010class ArraySize(Func):
4011    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4014class ArraySort(Func):
4015    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4018class ArraySum(Func):
4019    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4022class ArrayUnionAgg(AggFunc):
4023    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4026class Avg(AggFunc):
4027    pass
key = 'avg'
class AnyValue(AggFunc):
4030class AnyValue(AggFunc):
4031    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
4034class Case(Func):
4035    arg_types = {"this": False, "ifs": True, "default": False}
4036
4037    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4038        instance = maybe_copy(self, copy)
4039        instance.append(
4040            "ifs",
4041            If(
4042                this=maybe_parse(condition, copy=copy, **opts),
4043                true=maybe_parse(then, copy=copy, **opts),
4044            ),
4045        )
4046        return instance
4047
4048    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4049        instance = maybe_copy(self, copy)
4050        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4051        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:
4037    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4038        instance = maybe_copy(self, copy)
4039        instance.append(
4040            "ifs",
4041            If(
4042                this=maybe_parse(condition, copy=copy, **opts),
4043                true=maybe_parse(then, copy=copy, **opts),
4044            ),
4045        )
4046        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4048    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4049        instance = maybe_copy(self, copy)
4050        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4051        return instance
key = 'case'
class Cast(Func):
4054class Cast(Func):
4055    arg_types = {"this": True, "to": True, "format": False}
4056
4057    @property
4058    def name(self) -> str:
4059        return self.this.name
4060
4061    @property
4062    def to(self) -> DataType:
4063        return self.args["to"]
4064
4065    @property
4066    def output_name(self) -> str:
4067        return self.name
4068
4069    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4070        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:
4069    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4070        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
4073class CastToStrType(Func):
4074    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
4077class Collate(Binary):
4078    pass
key = 'collate'
class TryCast(Cast):
4081class TryCast(Cast):
4082    pass
key = 'trycast'
class Ceil(Func):
4085class Ceil(Func):
4086    arg_types = {"this": True, "decimals": False}
4087    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4090class Coalesce(Func):
4091    arg_types = {"this": True, "expressions": False}
4092    is_var_len_args = True
4093    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4096class Concat(Func):
4097    arg_types = {"expressions": True}
4098    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4101class SafeConcat(Concat):
4102    pass
key = 'safeconcat'
class ConcatWs(Concat):
4105class ConcatWs(Concat):
4106    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4109class Count(AggFunc):
4110    arg_types = {"this": False, "expressions": False}
4111    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4114class CountIf(AggFunc):
4115    pass
key = 'countif'
class CurrentDate(Func):
4118class CurrentDate(Func):
4119    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4122class CurrentDatetime(Func):
4123    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4126class CurrentTime(Func):
4127    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4130class CurrentTimestamp(Func):
4131    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4134class CurrentUser(Func):
4135    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4138class DateAdd(Func, TimeUnit):
4139    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4142class DateSub(Func, TimeUnit):
4143    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4146class DateDiff(Func, TimeUnit):
4147    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4148    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4151class DateTrunc(Func):
4152    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4155class DatetimeAdd(Func, TimeUnit):
4156    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4159class DatetimeSub(Func, TimeUnit):
4160    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4163class DatetimeDiff(Func, TimeUnit):
4164    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4167class DatetimeTrunc(Func, TimeUnit):
4168    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4171class DayOfWeek(Func):
4172    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4175class DayOfMonth(Func):
4176    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4179class DayOfYear(Func):
4180    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4183class WeekOfYear(Func):
4184    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4187class MonthsBetween(Func):
4188    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4191class LastDateOfMonth(Func):
4192    pass
key = 'lastdateofmonth'
class Extract(Func):
4195class Extract(Func):
4196    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4199class TimestampAdd(Func, TimeUnit):
4200    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4203class TimestampSub(Func, TimeUnit):
4204    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4207class TimestampDiff(Func, TimeUnit):
4208    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4211class TimestampTrunc(Func, TimeUnit):
4212    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4215class TimeAdd(Func, TimeUnit):
4216    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4219class TimeSub(Func, TimeUnit):
4220    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4223class TimeDiff(Func, TimeUnit):
4224    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4227class TimeTrunc(Func, TimeUnit):
4228    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4231class DateFromParts(Func):
4232    _sql_names = ["DATEFROMPARTS"]
4233    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4236class DateStrToDate(Func):
4237    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4240class DateToDateStr(Func):
4241    pass
key = 'datetodatestr'
class DateToDi(Func):
4244class DateToDi(Func):
4245    pass
key = 'datetodi'
class Date(Func):
4249class Date(Func):
4250    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4253class Day(Func):
4254    pass
key = 'day'
class Decode(Func):
4257class Decode(Func):
4258    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4261class DiToDate(Func):
4262    pass
key = 'ditodate'
class Encode(Func):
4265class Encode(Func):
4266    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4269class Exp(Func):
4270    pass
key = 'exp'
class Explode(Func):
4273class Explode(Func):
4274    pass
key = 'explode'
class Floor(Func):
4277class Floor(Func):
4278    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4281class FromBase64(Func):
4282    pass
key = 'frombase64'
class ToBase64(Func):
4285class ToBase64(Func):
4286    pass
key = 'tobase64'
class Greatest(Func):
4289class Greatest(Func):
4290    arg_types = {"this": True, "expressions": False}
4291    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4294class GroupConcat(Func):
4295    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4298class Hex(Func):
4299    pass
key = 'hex'
class Xor(Connector, Func):
4302class Xor(Connector, Func):
4303    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4306class If(Func):
4307    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4310class Initcap(Func):
4311    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4314class IsNan(Func):
4315    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class JSONKeyValue(Expression):
4318class JSONKeyValue(Expression):
4319    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4322class JSONObject(Func):
4323    arg_types = {
4324        "expressions": False,
4325        "null_handling": False,
4326        "unique_keys": False,
4327        "return_type": False,
4328        "format_json": False,
4329        "encoding": False,
4330    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4333class OpenJSONColumnDef(Expression):
4334    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):
4337class OpenJSON(Func):
4338    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4341class JSONBContains(Binary):
4342    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4345class JSONExtract(Binary, Func):
4346    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4349class JSONExtractScalar(JSONExtract):
4350    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4353class JSONBExtract(JSONExtract):
4354    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4357class JSONBExtractScalar(JSONExtract):
4358    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4361class JSONFormat(Func):
4362    arg_types = {"this": False, "options": False}
4363    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4367class JSONArrayContains(Binary, Predicate, Func):
4368    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4371class Least(Func):
4372    arg_types = {"this": True, "expressions": False}
4373    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4376class Left(Func):
4377    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4384class Length(Func):
4385    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4388class Levenshtein(Func):
4389    arg_types = {
4390        "this": True,
4391        "expression": False,
4392        "ins_cost": False,
4393        "del_cost": False,
4394        "sub_cost": False,
4395    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4398class Ln(Func):
4399    pass
key = 'ln'
class Log(Func):
4402class Log(Func):
4403    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4406class Log2(Func):
4407    pass
key = 'log2'
class Log10(Func):
4410class Log10(Func):
4411    pass
key = 'log10'
class LogicalOr(AggFunc):
4414class LogicalOr(AggFunc):
4415    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4418class LogicalAnd(AggFunc):
4419    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4422class Lower(Func):
4423    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4426class Map(Func):
4427    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4430class MapFromEntries(Func):
4431    pass
key = 'mapfromentries'
class StarMap(Func):
4434class StarMap(Func):
4435    pass
key = 'starmap'
class VarMap(Func):
4438class VarMap(Func):
4439    arg_types = {"keys": True, "values": True}
4440    is_var_len_args = True
4441
4442    @property
4443    def keys(self) -> t.List[Expression]:
4444        return self.args["keys"].expressions
4445
4446    @property
4447    def values(self) -> t.List[Expression]:
4448        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4452class MatchAgainst(Func):
4453    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4456class Max(AggFunc):
4457    arg_types = {"this": True, "expressions": False}
4458    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4461class MD5(Func):
4462    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4466class MD5Digest(Func):
4467    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4470class Min(AggFunc):
4471    arg_types = {"this": True, "expressions": False}
4472    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4475class Month(Func):
4476    pass
key = 'month'
class Nvl2(Func):
4479class Nvl2(Func):
4480    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4483class Posexplode(Func):
4484    pass
key = 'posexplode'
class Pow(Binary, Func):
4487class Pow(Binary, Func):
4488    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4491class PercentileCont(AggFunc):
4492    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4495class PercentileDisc(AggFunc):
4496    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4499class Quantile(AggFunc):
4500    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4503class ApproxQuantile(Quantile):
4504    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):
4507class RangeN(Func):
4508    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4511class ReadCSV(Func):
4512    _sql_names = ["READ_CSV"]
4513    is_var_len_args = True
4514    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4517class Reduce(Func):
4518    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):
4521class RegexpExtract(Func):
4522    arg_types = {
4523        "this": True,
4524        "expression": True,
4525        "position": False,
4526        "occurrence": False,
4527        "parameters": False,
4528        "group": False,
4529    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4532class RegexpReplace(Func):
4533    arg_types = {
4534        "this": True,
4535        "expression": True,
4536        "replacement": True,
4537        "position": False,
4538        "occurrence": False,
4539        "parameters": False,
4540    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4543class RegexpLike(Binary, Func):
4544    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4547class RegexpILike(Func):
4548    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4553class RegexpSplit(Func):
4554    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4557class Repeat(Func):
4558    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4561class Round(Func):
4562    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4565class RowNumber(Func):
4566    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4569class SafeDivide(Func):
4570    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4573class SetAgg(AggFunc):
4574    pass
key = 'setagg'
class SHA(Func):
4577class SHA(Func):
4578    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4581class SHA2(Func):
4582    _sql_names = ["SHA2"]
4583    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4586class SortArray(Func):
4587    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4590class Split(Func):
4591    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4596class Substring(Func):
4597    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4600class StandardHash(Func):
4601    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4604class StartsWith(Func):
4605    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4606    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4609class StrPosition(Func):
4610    arg_types = {
4611        "this": True,
4612        "substr": True,
4613        "position": False,
4614        "instance": False,
4615    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4618class StrToDate(Func):
4619    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4622class StrToTime(Func):
4623    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4628class StrToUnix(Func):
4629    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4632class NumberToStr(Func):
4633    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4636class FromBase(Func):
4637    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4640class Struct(Func):
4641    arg_types = {"expressions": True}
4642    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4645class StructExtract(Func):
4646    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4649class Sum(AggFunc):
4650    pass
key = 'sum'
class Sqrt(Func):
4653class Sqrt(Func):
4654    pass
key = 'sqrt'
class Stddev(AggFunc):
4657class Stddev(AggFunc):
4658    pass
key = 'stddev'
class StddevPop(AggFunc):
4661class StddevPop(AggFunc):
4662    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4665class StddevSamp(AggFunc):
4666    pass
key = 'stddevsamp'
class TimeToStr(Func):
4669class TimeToStr(Func):
4670    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4673class TimeToTimeStr(Func):
4674    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4677class TimeToUnix(Func):
4678    pass
key = 'timetounix'
class TimeStrToDate(Func):
4681class TimeStrToDate(Func):
4682    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4685class TimeStrToTime(Func):
4686    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4689class TimeStrToUnix(Func):
4690    pass
key = 'timestrtounix'
class Trim(Func):
4693class Trim(Func):
4694    arg_types = {
4695        "this": True,
4696        "expression": False,
4697        "position": False,
4698        "collation": False,
4699    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4702class TsOrDsAdd(Func, TimeUnit):
4703    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4706class TsOrDsToDateStr(Func):
4707    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4710class TsOrDsToDate(Func):
4711    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4714class TsOrDiToDi(Func):
4715    pass
key = 'tsorditodi'
class Unhex(Func):
4718class Unhex(Func):
4719    pass
key = 'unhex'
class UnixToStr(Func):
4722class UnixToStr(Func):
4723    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4728class UnixToTime(Func):
4729    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4730
4731    SECONDS = Literal.string("seconds")
4732    MILLIS = Literal.string("millis")
4733    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):
4736class UnixToTimeStr(Func):
4737    pass
key = 'unixtotimestr'
class Upper(Func):
4740class Upper(Func):
4741    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4744class Variance(AggFunc):
4745    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4748class VariancePop(AggFunc):
4749    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4752class Week(Func):
4753    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4756class XMLTable(Func):
4757    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):
4760class Year(Func):
4761    pass
key = 'year'
class Use(Expression):
4764class Use(Expression):
4765    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4768class Merge(Expression):
4769    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):
4772class When(Func):
4773    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):
4778class NextValueFor(Func):
4779    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.IsNan'>, <class 'sqlglot.expressions.JSONArrayContains'>, <class 'sqlglot.expressions.JSONBExtract'>, <class 'sqlglot.expressions.JSONBExtractScalar'>, <class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.JSONExtractScalar'>, <class 'sqlglot.expressions.JSONFormat'>, <class 'sqlglot.expressions.JSONObject'>, <class 'sqlglot.expressions.LastDateOfMonth'>, <class 'sqlglot.expressions.Least'>, <class 'sqlglot.expressions.Left'>, <class 'sqlglot.expressions.Length'>, <class 'sqlglot.expressions.Levenshtein'>, <class 'sqlglot.expressions.Ln'>, <class 'sqlglot.expressions.Log'>, <class 'sqlglot.expressions.Log10'>, <class 'sqlglot.expressions.Log2'>, <class 'sqlglot.expressions.LogicalAnd'>, <class 'sqlglot.expressions.LogicalOr'>, <class 'sqlglot.expressions.Lower'>, <class 'sqlglot.expressions.MD5'>, <class 'sqlglot.expressions.MD5Digest'>, <class 'sqlglot.expressions.Map'>, <class 'sqlglot.expressions.MapFromEntries'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <class 'sqlglot.expressions.MonthsBetween'>, <class 'sqlglot.expressions.NextValueFor'>, <class 'sqlglot.expressions.NumberToStr'>, <class 'sqlglot.expressions.Nvl2'>, <class 'sqlglot.expressions.OpenJSON'>, <class 'sqlglot.expressions.ParameterizedAgg'>, <class 'sqlglot.expressions.PercentileCont'>, <class 'sqlglot.expressions.PercentileDisc'>, <class 'sqlglot.expressions.Posexplode'>, <class 'sqlglot.expressions.Pow'>, <class 'sqlglot.expressions.Quantile'>, <class 'sqlglot.expressions.RangeN'>, <class 'sqlglot.expressions.ReadCSV'>, <class 'sqlglot.expressions.Reduce'>, <class 'sqlglot.expressions.RegexpExtract'>, <class 'sqlglot.expressions.RegexpILike'>, <class 'sqlglot.expressions.RegexpLike'>, <class 'sqlglot.expressions.RegexpReplace'>, <class 'sqlglot.expressions.RegexpSplit'>, <class 'sqlglot.expressions.Repeat'>, <class 'sqlglot.expressions.Right'>, <class 'sqlglot.expressions.Round'>, <class 'sqlglot.expressions.RowNumber'>, <class 'sqlglot.expressions.SHA'>, <class 'sqlglot.expressions.SHA2'>, <class 'sqlglot.expressions.SafeConcat'>, <class 'sqlglot.expressions.SafeDivide'>, <class 'sqlglot.expressions.SetAgg'>, <class 'sqlglot.expressions.SortArray'>, <class 'sqlglot.expressions.Split'>, <class 'sqlglot.expressions.Sqrt'>, <class 'sqlglot.expressions.StandardHash'>, <class 'sqlglot.expressions.StarMap'>, <class 'sqlglot.expressions.StartsWith'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.Transform'>, <class 'sqlglot.expressions.Trim'>, <class 'sqlglot.expressions.TryCast'>, <class 'sqlglot.expressions.TsOrDiToDi'>, <class 'sqlglot.expressions.TsOrDsAdd'>, <class 'sqlglot.expressions.TsOrDsToDate'>, <class 'sqlglot.expressions.TsOrDsToDateStr'>, <class 'sqlglot.expressions.Unhex'>, <class 'sqlglot.expressions.UnixToStr'>, <class 'sqlglot.expressions.UnixToTime'>, <class 'sqlglot.expressions.UnixToTimeStr'>, <class 'sqlglot.expressions.Upper'>, <class 'sqlglot.expressions.VarMap'>, <class 'sqlglot.expressions.Variance'>, <class 'sqlglot.expressions.VariancePop'>, <class 'sqlglot.expressions.Week'>, <class 'sqlglot.expressions.WeekOfYear'>, <class 'sqlglot.expressions.When'>, <class 'sqlglot.expressions.XMLTable'>, <class 'sqlglot.expressions.Xor'>, <class 'sqlglot.expressions.Year'>]
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4816def maybe_parse(
4817    sql_or_expression: ExpOrStr,
4818    *,
4819    into: t.Optional[IntoType] = None,
4820    dialect: DialectType = None,
4821    prefix: t.Optional[str] = None,
4822    copy: bool = False,
4823    **opts,
4824) -> Expression:
4825    """Gracefully handle a possible string or expression.
4826
4827    Example:
4828        >>> maybe_parse("1")
4829        (LITERAL this: 1, is_string: False)
4830        >>> maybe_parse(to_identifier("x"))
4831        (IDENTIFIER this: x, quoted: False)
4832
4833    Args:
4834        sql_or_expression: the SQL code string or an expression
4835        into: the SQLGlot Expression to parse into
4836        dialect: the dialect used to parse the input expressions (in the case that an
4837            input expression is a SQL string).
4838        prefix: a string to prefix the sql with before it gets parsed
4839            (automatically includes a space)
4840        copy: whether or not to copy the expression.
4841        **opts: other options to use to parse the input expressions (again, in the case
4842            that an input expression is a SQL string).
4843
4844    Returns:
4845        Expression: the parsed or given expression.
4846    """
4847    if isinstance(sql_or_expression, Expression):
4848        if copy:
4849            return sql_or_expression.copy()
4850        return sql_or_expression
4851
4852    if sql_or_expression is None:
4853        raise ParseError(f"SQL cannot be None")
4854
4855    import sqlglot
4856
4857    sql = str(sql_or_expression)
4858    if prefix:
4859        sql = f"{prefix} {sql}"
4860
4861    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):
4874def maybe_copy(instance, copy=True):
4875    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:
5055def union(
5056    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5057) -> Union:
5058    """
5059    Initializes a syntax tree from one UNION expression.
5060
5061    Example:
5062        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5063        'SELECT * FROM foo UNION SELECT * FROM bla'
5064
5065    Args:
5066        left: the SQL code string corresponding to the left-hand side.
5067            If an `Expression` instance is passed, it will be used as-is.
5068        right: the SQL code string corresponding to the right-hand side.
5069            If an `Expression` instance is passed, it will be used as-is.
5070        distinct: set the DISTINCT flag if and only if this is true.
5071        dialect: the dialect used to parse the input expression.
5072        opts: other options to use to parse the input expressions.
5073
5074    Returns:
5075        The new Union instance.
5076    """
5077    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5078    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5079
5080    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:
5083def intersect(
5084    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5085) -> Intersect:
5086    """
5087    Initializes a syntax tree from one INTERSECT expression.
5088
5089    Example:
5090        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5091        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5092
5093    Args:
5094        left: the SQL code string corresponding to the left-hand side.
5095            If an `Expression` instance is passed, it will be used as-is.
5096        right: the SQL code string corresponding to the right-hand side.
5097            If an `Expression` instance is passed, it will be used as-is.
5098        distinct: set the DISTINCT flag if and only if this is true.
5099        dialect: the dialect used to parse the input expression.
5100        opts: other options to use to parse the input expressions.
5101
5102    Returns:
5103        The new Intersect instance.
5104    """
5105    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5106    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5107
5108    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:
5111def except_(
5112    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5113) -> Except:
5114    """
5115    Initializes a syntax tree from one EXCEPT expression.
5116
5117    Example:
5118        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5119        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5120
5121    Args:
5122        left: the SQL code string corresponding to the left-hand side.
5123            If an `Expression` instance is passed, it will be used as-is.
5124        right: the SQL code string corresponding to the right-hand side.
5125            If an `Expression` instance is passed, it will be used as-is.
5126        distinct: set the DISTINCT flag if and only if this is true.
5127        dialect: the dialect used to parse the input expression.
5128        opts: other options to use to parse the input expressions.
5129
5130    Returns:
5131        The new Except instance.
5132    """
5133    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5134    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5135
5136    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:
5139def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5140    """
5141    Initializes a syntax tree from one or multiple SELECT expressions.
5142
5143    Example:
5144        >>> select("col1", "col2").from_("tbl").sql()
5145        'SELECT col1, col2 FROM tbl'
5146
5147    Args:
5148        *expressions: the SQL code string to parse as the expressions of a
5149            SELECT statement. If an Expression instance is passed, this is used as-is.
5150        dialect: the dialect used to parse the input expressions (in the case that an
5151            input expression is a SQL string).
5152        **opts: other options to use to parse the input expressions (again, in the case
5153            that an input expression is a SQL string).
5154
5155    Returns:
5156        Select: the syntax tree for the SELECT statement.
5157    """
5158    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:
5161def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5162    """
5163    Initializes a syntax tree from a FROM expression.
5164
5165    Example:
5166        >>> from_("tbl").select("col1", "col2").sql()
5167        'SELECT col1, col2 FROM tbl'
5168
5169    Args:
5170        *expression: the SQL code string to parse as the FROM expressions of a
5171            SELECT statement. If an Expression instance is passed, this is used as-is.
5172        dialect: the dialect used to parse the input expression (in the case that the
5173            input expression is a SQL string).
5174        **opts: other options to use to parse the input expressions (again, in the case
5175            that the input expression is a SQL string).
5176
5177    Returns:
5178        Select: the syntax tree for the SELECT statement.
5179    """
5180    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:
5183def update(
5184    table: str | Table,
5185    properties: dict,
5186    where: t.Optional[ExpOrStr] = None,
5187    from_: t.Optional[ExpOrStr] = None,
5188    dialect: DialectType = None,
5189    **opts,
5190) -> Update:
5191    """
5192    Creates an update statement.
5193
5194    Example:
5195        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5196        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5197
5198    Args:
5199        *properties: dictionary of properties to set which are
5200            auto converted to sql objects eg None -> NULL
5201        where: sql conditional parsed into a WHERE statement
5202        from_: sql statement parsed into a FROM statement
5203        dialect: the dialect used to parse the input expressions.
5204        **opts: other options to use to parse the input expressions.
5205
5206    Returns:
5207        Update: the syntax tree for the UPDATE statement.
5208    """
5209    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5210    update_expr.set(
5211        "expressions",
5212        [
5213            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5214            for k, v in properties.items()
5215        ],
5216    )
5217    if from_:
5218        update_expr.set(
5219            "from",
5220            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5221        )
5222    if isinstance(where, Condition):
5223        where = Where(this=where)
5224    if where:
5225        update_expr.set(
5226            "where",
5227            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5228        )
5229    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:
5232def delete(
5233    table: ExpOrStr,
5234    where: t.Optional[ExpOrStr] = None,
5235    returning: t.Optional[ExpOrStr] = None,
5236    dialect: DialectType = None,
5237    **opts,
5238) -> Delete:
5239    """
5240    Builds a delete statement.
5241
5242    Example:
5243        >>> delete("my_table", where="id > 1").sql()
5244        'DELETE FROM my_table WHERE id > 1'
5245
5246    Args:
5247        where: sql conditional parsed into a WHERE statement
5248        returning: sql conditional parsed into a RETURNING statement
5249        dialect: the dialect used to parse the input expressions.
5250        **opts: other options to use to parse the input expressions.
5251
5252    Returns:
5253        Delete: the syntax tree for the DELETE statement.
5254    """
5255    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5256    if where:
5257        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5258    if returning:
5259        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5260    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:
5263def insert(
5264    expression: ExpOrStr,
5265    into: ExpOrStr,
5266    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5267    overwrite: t.Optional[bool] = None,
5268    dialect: DialectType = None,
5269    copy: bool = True,
5270    **opts,
5271) -> Insert:
5272    """
5273    Builds an INSERT statement.
5274
5275    Example:
5276        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5277        'INSERT INTO tbl VALUES (1, 2, 3)'
5278
5279    Args:
5280        expression: the sql string or expression of the INSERT statement
5281        into: the tbl to insert data to.
5282        columns: optionally the table's column names.
5283        overwrite: whether to INSERT OVERWRITE or not.
5284        dialect: the dialect used to parse the input expressions.
5285        copy: whether or not to copy the expression.
5286        **opts: other options to use to parse the input expressions.
5287
5288    Returns:
5289        Insert: the syntax tree for the INSERT statement.
5290    """
5291    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5292    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5293
5294    if columns:
5295        this = _apply_list_builder(
5296            *columns,
5297            instance=Schema(this=this),
5298            arg="expressions",
5299            into=Identifier,
5300            copy=False,
5301            dialect=dialect,
5302            **opts,
5303        )
5304
5305    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:
5308def condition(
5309    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5310) -> Condition:
5311    """
5312    Initialize a logical condition expression.
5313
5314    Example:
5315        >>> condition("x=1").sql()
5316        'x = 1'
5317
5318        This is helpful for composing larger logical syntax trees:
5319        >>> where = condition("x=1")
5320        >>> where = where.and_("y=1")
5321        >>> Select().from_("tbl").select("*").where(where).sql()
5322        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5323
5324    Args:
5325        *expression: the SQL code string to parse.
5326            If an Expression instance is passed, this is used as-is.
5327        dialect: the dialect used to parse the input expression (in the case that the
5328            input expression is a SQL string).
5329        copy: Whether or not to copy `expression` (only applies to expressions).
5330        **opts: other options to use to parse the input expressions (again, in the case
5331            that the input expression is a SQL string).
5332
5333    Returns:
5334        The new Condition instance
5335    """
5336    return maybe_parse(
5337        expression,
5338        into=Condition,
5339        dialect=dialect,
5340        copy=copy,
5341        **opts,
5342    )

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:
5345def and_(
5346    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5347) -> Condition:
5348    """
5349    Combine multiple conditions with an AND logical operator.
5350
5351    Example:
5352        >>> and_("x=1", and_("y=1", "z=1")).sql()
5353        'x = 1 AND (y = 1 AND z = 1)'
5354
5355    Args:
5356        *expressions: the SQL code strings to parse.
5357            If an Expression instance is passed, this is used as-is.
5358        dialect: the dialect used to parse the input expression.
5359        copy: whether or not to copy `expressions` (only applies to Expressions).
5360        **opts: other options to use to parse the input expressions.
5361
5362    Returns:
5363        And: the new condition
5364    """
5365    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:
5368def or_(
5369    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5370) -> Condition:
5371    """
5372    Combine multiple conditions with an OR logical operator.
5373
5374    Example:
5375        >>> or_("x=1", or_("y=1", "z=1")).sql()
5376        'x = 1 OR (y = 1 OR z = 1)'
5377
5378    Args:
5379        *expressions: the SQL code strings to parse.
5380            If an Expression instance is passed, this is used as-is.
5381        dialect: the dialect used to parse the input expression.
5382        copy: whether or not to copy `expressions` (only applies to Expressions).
5383        **opts: other options to use to parse the input expressions.
5384
5385    Returns:
5386        Or: the new condition
5387    """
5388    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:
5391def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5392    """
5393    Wrap a condition with a NOT operator.
5394
5395    Example:
5396        >>> not_("this_suit='black'").sql()
5397        "NOT this_suit = 'black'"
5398
5399    Args:
5400        expression: the SQL code string to parse.
5401            If an Expression instance is passed, this is used as-is.
5402        dialect: the dialect used to parse the input expression.
5403        copy: whether to copy the expression or not.
5404        **opts: other options to use to parse the input expressions.
5405
5406    Returns:
5407        The new condition.
5408    """
5409    this = condition(
5410        expression,
5411        dialect=dialect,
5412        copy=copy,
5413        **opts,
5414    )
5415    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:
5418def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5419    """
5420    Wrap an expression in parentheses.
5421
5422    Example:
5423        >>> paren("5 + 3").sql()
5424        '(5 + 3)'
5425
5426    Args:
5427        expression: the SQL code string to parse.
5428            If an Expression instance is passed, this is used as-is.
5429        copy: whether to copy the expression or not.
5430
5431    Returns:
5432        The wrapped expression.
5433    """
5434    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):
5452def to_identifier(name, quoted=None, copy=True):
5453    """Builds an identifier.
5454
5455    Args:
5456        name: The name to turn into an identifier.
5457        quoted: Whether or not force quote the identifier.
5458        copy: Whether or not to copy a passed in Identefier node.
5459
5460    Returns:
5461        The identifier ast node.
5462    """
5463
5464    if name is None:
5465        return None
5466
5467    if isinstance(name, Identifier):
5468        identifier = maybe_copy(name, copy)
5469    elif isinstance(name, str):
5470        identifier = Identifier(
5471            this=name,
5472            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5473        )
5474    else:
5475        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5476    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:
5482def to_interval(interval: str | Literal) -> Interval:
5483    """Builds an interval expression from a string like '1 day' or '5 months'."""
5484    if isinstance(interval, Literal):
5485        if not interval.is_string:
5486            raise ValueError("Invalid interval string.")
5487
5488        interval = interval.this
5489
5490    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5491
5492    if not interval_parts:
5493        raise ValueError("Invalid interval string.")
5494
5495    return Interval(
5496        this=Literal.string(interval_parts.group(1)),
5497        unit=Var(this=interval_parts.group(2)),
5498    )

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]:
5511def to_table(
5512    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5513) -> t.Optional[Table]:
5514    """
5515    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5516    If a table is passed in then that table is returned.
5517
5518    Args:
5519        sql_path: a `[catalog].[schema].[table]` string.
5520        dialect: the source dialect according to which the table name will be parsed.
5521        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5522
5523    Returns:
5524        A table expression.
5525    """
5526    if sql_path is None or isinstance(sql_path, Table):
5527        return sql_path
5528    if not isinstance(sql_path, str):
5529        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5530
5531    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5532    if table:
5533        for k, v in kwargs.items():
5534            table.set(k, v)
5535
5536    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:
5539def to_column(sql_path: str | Column, **kwargs) -> Column:
5540    """
5541    Create a column from a `[table].[column]` sql path. Schema is optional.
5542
5543    If a column is passed in then that column is returned.
5544
5545    Args:
5546        sql_path: `[table].[column]` string
5547    Returns:
5548        Table: A column expression
5549    """
5550    if sql_path is None or isinstance(sql_path, Column):
5551        return sql_path
5552    if not isinstance(sql_path, str):
5553        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5554    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):
5557def alias_(
5558    expression: ExpOrStr,
5559    alias: str | Identifier,
5560    table: bool | t.Sequence[str | Identifier] = False,
5561    quoted: t.Optional[bool] = None,
5562    dialect: DialectType = None,
5563    copy: bool = True,
5564    **opts,
5565):
5566    """Create an Alias expression.
5567
5568    Example:
5569        >>> alias_('foo', 'bar').sql()
5570        'foo AS bar'
5571
5572        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5573        '(SELECT 1, 2) AS bar(a, b)'
5574
5575    Args:
5576        expression: the SQL code strings to parse.
5577            If an Expression instance is passed, this is used as-is.
5578        alias: the alias name to use. If the name has
5579            special characters it is quoted.
5580        table: Whether or not to create a table alias, can also be a list of columns.
5581        quoted: whether or not to quote the alias
5582        dialect: the dialect used to parse the input expression.
5583        copy: Whether or not to copy the expression.
5584        **opts: other options to use to parse the input expressions.
5585
5586    Returns:
5587        Alias: the aliased expression
5588    """
5589    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5590    alias = to_identifier(alias, quoted=quoted)
5591
5592    if table:
5593        table_alias = TableAlias(this=alias)
5594        exp.set("alias", table_alias)
5595
5596        if not isinstance(table, bool):
5597            for column in table:
5598                table_alias.append("columns", to_identifier(column, quoted=quoted))
5599
5600        return exp
5601
5602    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5603    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5604    # for the complete Window expression.
5605    #
5606    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5607
5608    if "alias" in exp.arg_types and not isinstance(exp, Window):
5609        exp.set("alias", alias)
5610        return exp
5611    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:
5614def subquery(
5615    expression: ExpOrStr,
5616    alias: t.Optional[Identifier | str] = None,
5617    dialect: DialectType = None,
5618    **opts,
5619) -> Select:
5620    """
5621    Build a subquery expression.
5622
5623    Example:
5624        >>> subquery('select x from tbl', 'bar').select('x').sql()
5625        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5626
5627    Args:
5628        expression: the SQL code strings to parse.
5629            If an Expression instance is passed, this is used as-is.
5630        alias: the alias name to use.
5631        dialect: the dialect used to parse the input expression.
5632        **opts: other options to use to parse the input expressions.
5633
5634    Returns:
5635        A new Select instance with the subquery expression included.
5636    """
5637
5638    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5639    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:
5642def column(
5643    col: str | Identifier,
5644    table: t.Optional[str | Identifier] = None,
5645    db: t.Optional[str | Identifier] = None,
5646    catalog: t.Optional[str | Identifier] = None,
5647    quoted: t.Optional[bool] = None,
5648) -> Column:
5649    """
5650    Build a Column.
5651
5652    Args:
5653        col: Column name.
5654        table: Table name.
5655        db: Database name.
5656        catalog: Catalog name.
5657        quoted: Whether to force quotes on the column's identifiers.
5658
5659    Returns:
5660        The new Column instance.
5661    """
5662    return Column(
5663        this=to_identifier(col, quoted=quoted),
5664        table=to_identifier(table, quoted=quoted),
5665        db=to_identifier(db, quoted=quoted),
5666        catalog=to_identifier(catalog, quoted=quoted),
5667    )

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:
5670def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5671    """Cast an expression to a data type.
5672
5673    Example:
5674        >>> cast('x + 1', 'int').sql()
5675        'CAST(x + 1 AS INT)'
5676
5677    Args:
5678        expression: The expression to cast.
5679        to: The datatype to cast to.
5680
5681    Returns:
5682        The new Cast instance.
5683    """
5684    expression = maybe_parse(expression, **opts)
5685    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:
5688def table_(
5689    table: Identifier | str,
5690    db: t.Optional[Identifier | str] = None,
5691    catalog: t.Optional[Identifier | str] = None,
5692    quoted: t.Optional[bool] = None,
5693    alias: t.Optional[Identifier | str] = None,
5694) -> Table:
5695    """Build a Table.
5696
5697    Args:
5698        table: Table name.
5699        db: Database name.
5700        catalog: Catalog name.
5701        quote: Whether to force quotes on the table's identifiers.
5702        alias: Table's alias.
5703
5704    Returns:
5705        The new Table instance.
5706    """
5707    return Table(
5708        this=to_identifier(table, quoted=quoted),
5709        db=to_identifier(db, quoted=quoted),
5710        catalog=to_identifier(catalog, quoted=quoted),
5711        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5712    )

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:
5715def values(
5716    values: t.Iterable[t.Tuple[t.Any, ...]],
5717    alias: t.Optional[str] = None,
5718    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5719) -> Values:
5720    """Build VALUES statement.
5721
5722    Example:
5723        >>> values([(1, '2')]).sql()
5724        "VALUES (1, '2')"
5725
5726    Args:
5727        values: values statements that will be converted to SQL
5728        alias: optional alias
5729        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5730         If either are provided then an alias is also required.
5731
5732    Returns:
5733        Values: the Values expression object
5734    """
5735    if columns and not alias:
5736        raise ValueError("Alias is required when providing columns")
5737
5738    return Values(
5739        expressions=[convert(tup) for tup in values],
5740        alias=(
5741            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5742            if columns
5743            else (TableAlias(this=to_identifier(alias)) if alias else None)
5744        ),
5745    )

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:
5748def var(name: t.Optional[ExpOrStr]) -> Var:
5749    """Build a SQL variable.
5750
5751    Example:
5752        >>> repr(var('x'))
5753        '(VAR this: x)'
5754
5755        >>> repr(var(column('x', table='y')))
5756        '(VAR this: x)'
5757
5758    Args:
5759        name: The name of the var or an expression who's name will become the var.
5760
5761    Returns:
5762        The new variable node.
5763    """
5764    if not name:
5765        raise ValueError("Cannot convert empty name into var.")
5766
5767    if isinstance(name, Expression):
5768        name = name.name
5769    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:
5772def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5773    """Build ALTER TABLE... RENAME... expression
5774
5775    Args:
5776        old_name: The old name of the table
5777        new_name: The new name of the table
5778
5779    Returns:
5780        Alter table expression
5781    """
5782    old_table = to_table(old_name)
5783    new_table = to_table(new_name)
5784    return AlterTable(
5785        this=old_table,
5786        actions=[
5787            RenameTable(this=new_table),
5788        ],
5789    )

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:
5792def convert(value: t.Any, copy: bool = False) -> Expression:
5793    """Convert a python value into an expression object.
5794
5795    Raises an error if a conversion is not possible.
5796
5797    Args:
5798        value: A python object.
5799        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5800
5801    Returns:
5802        Expression: the equivalent expression object.
5803    """
5804    if isinstance(value, Expression):
5805        return maybe_copy(value, copy)
5806    if isinstance(value, str):
5807        return Literal.string(value)
5808    if isinstance(value, bool):
5809        return Boolean(this=value)
5810    if value is None or (isinstance(value, float) and math.isnan(value)):
5811        return NULL
5812    if isinstance(value, numbers.Number):
5813        return Literal.number(value)
5814    if isinstance(value, datetime.datetime):
5815        datetime_literal = Literal.string(
5816            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5817        )
5818        return TimeStrToTime(this=datetime_literal)
5819    if isinstance(value, datetime.date):
5820        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5821        return DateStrToDate(this=date_literal)
5822    if isinstance(value, tuple):
5823        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5824    if isinstance(value, list):
5825        return Array(expressions=[convert(v, copy=copy) for v in value])
5826    if isinstance(value, dict):
5827        return Map(
5828            keys=[convert(k, copy=copy) for k in value],
5829            values=[convert(v, copy=copy) for v in value.values()],
5830        )
5831    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:
5834def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5835    """
5836    Replace children of an expression with the result of a lambda fun(child) -> exp.
5837    """
5838    for k, v in expression.args.items():
5839        is_list_arg = type(v) is list
5840
5841        child_nodes = v if is_list_arg else [v]
5842        new_child_nodes = []
5843
5844        for cn in child_nodes:
5845            if isinstance(cn, Expression):
5846                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5847                    new_child_nodes.append(child_node)
5848                    child_node.parent = expression
5849                    child_node.arg_key = k
5850            else:
5851                new_child_nodes.append(cn)
5852
5853        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]:
5856def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5857    """
5858    Return all table names referenced through columns in an expression.
5859
5860    Example:
5861        >>> import sqlglot
5862        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5863        ['a', 'c']
5864
5865    Args:
5866        expression: expression to find table names.
5867        exclude: a table name to exclude
5868
5869    Returns:
5870        A list of unique names.
5871    """
5872    return {
5873        table
5874        for table in (column.table for column in expression.find_all(Column))
5875        if table and table != exclude
5876    }

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:
5879def table_name(table: Table | str, dialect: DialectType = None) -> str:
5880    """Get the full name of a table as a string.
5881
5882    Args:
5883        table: Table expression node or string.
5884        dialect: The dialect to generate the table name for.
5885
5886    Examples:
5887        >>> from sqlglot import exp, parse_one
5888        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5889        'a.b.c'
5890
5891    Returns:
5892        The table name.
5893    """
5894
5895    table = maybe_parse(table, into=Table)
5896
5897    if not table:
5898        raise ValueError(f"Cannot parse {table}")
5899
5900    return ".".join(
5901        part.sql(dialect=dialect, identify=True)
5902        if not SAFE_IDENTIFIER_RE.match(part.name)
5903        else part.name
5904        for part in table.parts
5905    )

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

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
6063def false() -> Boolean:
6064    """
6065    Returns a false Boolean expression.
6066    """
6067    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6070def null() -> Null:
6071    """
6072    Returns a Null expression.
6073    """
6074    return Null()

Returns a Null expression.

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