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

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):
252    def copy(self):
253        """
254        Returns a deep copy of the expression.
255        """
256        new = deepcopy(self)
257        new.parent = self.parent
258        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
260    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
261        if self.comments is None:
262            self.comments = []
263        if comments:
264            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
266    def append(self, arg_key: str, value: t.Any) -> None:
267        """
268        Appends value to arg_key if it's a list or sets it as a new list.
269
270        Args:
271            arg_key (str): name of the list expression arg
272            value (Any): value to append to the list
273        """
274        if not isinstance(self.args.get(arg_key), list):
275            self.args[arg_key] = []
276        self.args[arg_key].append(value)
277        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:
279    def set(self, arg_key: str, value: t.Any) -> None:
280        """
281        Sets `arg_key` to `value`.
282
283        Args:
284            arg_key (str): name of the expression arg.
285            value: value to set the arg to.
286        """
287        self.args[arg_key] = value
288        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): 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]]:
309    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
310        """Yields the key and expression for all arguments, exploding list args."""
311        for k, vs in self.args.items():
312            if type(vs) is list:
313                for v in vs:
314                    if hasattr(v, "parent"):
315                        yield k, v
316            else:
317                if hasattr(vs, "parent"):
318                    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]:
320    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
321        """
322        Returns the first node in this tree which matches at least one of
323        the specified types.
324
325        Args:
326            expression_types: the expression type(s) to match.
327            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
328
329        Returns:
330            The node which matches the criteria or None if no such node was found.
331        """
332        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]:
334    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
335        """
336        Returns a generator object which visits all nodes in this tree and only
337        yields those that match at least one of the specified expression types.
338
339        Args:
340            expression_types: the expression type(s) to match.
341            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                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]:
350    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        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:
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            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):
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            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):
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                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):
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression

Returns the first non parenthesis child or self.

def unalias(self):
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                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:
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        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):
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        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):
553    def replace(self, expression):
554        """
555        Swap out this expression with a new expression.
556
557        For example::
558
559            >>> tree = Select().select("x").from_("tbl")
560            >>> tree.find(Column).replace(Column(this="y"))
561            (COLUMN this: y)
562            >>> tree.sql()
563            'SELECT y FROM tbl'
564
565        Args:
566            expression: new node
567
568        Returns:
569            The new expression or expressions.
570        """
571        if not self.parent:
572            return expression
573
574        parent = self.parent
575        self.parent = None
576
577        replace_children(parent, lambda child: expression if child is self else child)
578        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:
580    def pop(self: E) -> E:
581        """
582        Remove this expression from its AST.
583
584        Returns:
585            The popped expression.
586        """
587        self.replace(None)
588        return self

Remove this expression from its AST.

Returns:

The popped expression.

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

Dump this Expression to a JSON-serializable dict.

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

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

key = 'predicate'
class DerivedTable(Expression):
872class DerivedTable(Expression):
873    @property
874    def alias_column_names(self) -> t.List[str]:
875        table_alias = self.args.get("alias")
876        if not table_alias:
877            return []
878        return [c.name for c in table_alias.args.get("columns") or []]
879
880    @property
881    def selects(self):
882        return self.this.selects if isinstance(self.this, Subqueryable) else []
883
884    @property
885    def named_selects(self):
886        return [select.output_name for select in self.selects]
alias_column_names: List[str]
selects
named_selects
key = 'derivedtable'
class Unionable(Expression):
889class Unionable(Expression):
890    def union(
891        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
892    ) -> Unionable:
893        """
894        Builds a UNION expression.
895
896        Example:
897            >>> import sqlglot
898            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
899            'SELECT * FROM foo UNION SELECT * FROM bla'
900
901        Args:
902            expression: the SQL code string.
903                If an `Expression` instance is passed, it will be used as-is.
904            distinct: set the DISTINCT flag if and only if this is true.
905            dialect: the dialect used to parse the input expression.
906            opts: other options to use to parse the input expressions.
907
908        Returns:
909            The new Union expression.
910        """
911        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
912
913    def intersect(
914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
915    ) -> Unionable:
916        """
917        Builds an INTERSECT expression.
918
919        Example:
920            >>> import sqlglot
921            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
922            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
923
924        Args:
925            expression: the SQL code string.
926                If an `Expression` instance is passed, it will be used as-is.
927            distinct: set the DISTINCT flag if and only if this is true.
928            dialect: the dialect used to parse the input expression.
929            opts: other options to use to parse the input expressions.
930
931        Returns:
932            The new Intersect expression.
933        """
934        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
935
936    def except_(
937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
938    ) -> Unionable:
939        """
940        Builds an EXCEPT expression.
941
942        Example:
943            >>> import sqlglot
944            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
945            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
946
947        Args:
948            expression: the SQL code string.
949                If an `Expression` instance is passed, it will be used as-is.
950            distinct: set the DISTINCT flag if and only if this is true.
951            dialect: the dialect used to parse the input expression.
952            opts: other options to use to parse the input expressions.
953
954        Returns:
955            The new Except expression.
956        """
957        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:
890    def union(
891        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
892    ) -> Unionable:
893        """
894        Builds a UNION expression.
895
896        Example:
897            >>> import sqlglot
898            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
899            'SELECT * FROM foo UNION SELECT * FROM bla'
900
901        Args:
902            expression: the SQL code string.
903                If an `Expression` instance is passed, it will be used as-is.
904            distinct: set the DISTINCT flag if and only if this is true.
905            dialect: the dialect used to parse the input expression.
906            opts: other options to use to parse the input expressions.
907
908        Returns:
909            The new Union expression.
910        """
911        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:
913    def intersect(
914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
915    ) -> Unionable:
916        """
917        Builds an INTERSECT expression.
918
919        Example:
920            >>> import sqlglot
921            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
922            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
923
924        Args:
925            expression: the SQL code string.
926                If an `Expression` instance is passed, it will be used as-is.
927            distinct: set the DISTINCT flag if and only if this is true.
928            dialect: the dialect used to parse the input expression.
929            opts: other options to use to parse the input expressions.
930
931        Returns:
932            The new Intersect expression.
933        """
934        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:
936    def except_(
937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
938    ) -> Unionable:
939        """
940        Builds an EXCEPT expression.
941
942        Example:
943            >>> import sqlglot
944            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
945            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
946
947        Args:
948            expression: the SQL code string.
949                If an `Expression` instance is passed, it will be used as-is.
950            distinct: set the DISTINCT flag if and only if this is true.
951            dialect: the dialect used to parse the input expression.
952            opts: other options to use to parse the input expressions.
953
954        Returns:
955            The new Except expression.
956        """
957        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):
960class UDTF(DerivedTable, Unionable):
961    @property
962    def selects(self):
963        alias = self.args.get("alias")
964        return alias.columns if alias else []
selects
key = 'udtf'
class Cache(Expression):
967class Cache(Expression):
968    arg_types = {
969        "with": False,
970        "this": True,
971        "lazy": False,
972        "options": False,
973        "expression": False,
974    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
977class Uncache(Expression):
978    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class Create(Expression):
981class Create(Expression):
982    arg_types = {
983        "with": False,
984        "this": True,
985        "kind": True,
986        "expression": False,
987        "exists": False,
988        "properties": False,
989        "replace": False,
990        "unique": False,
991        "indexes": False,
992        "no_schema_binding": False,
993        "begin": False,
994        "clone": False,
995    }
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):
 999class Clone(Expression):
1000    arg_types = {
1001        "this": True,
1002        "when": False,
1003        "kind": False,
1004        "expression": False,
1005    }
arg_types = {'this': True, 'when': False, 'kind': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1008class Describe(Expression):
1009    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'describe'
class Pragma(Expression):
1012class Pragma(Expression):
1013    pass
key = 'pragma'
class Set(Expression):
1016class Set(Expression):
1017    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1020class SetItem(Expression):
1021    arg_types = {
1022        "this": False,
1023        "expressions": False,
1024        "kind": False,
1025        "collate": False,  # MySQL SET NAMES statement
1026        "global": False,
1027    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1030class Show(Expression):
1031    arg_types = {
1032        "this": True,
1033        "target": False,
1034        "offset": False,
1035        "limit": False,
1036        "like": False,
1037        "where": False,
1038        "db": False,
1039        "full": False,
1040        "mutex": False,
1041        "query": False,
1042        "channel": False,
1043        "global": False,
1044        "log": False,
1045        "position": False,
1046        "types": False,
1047    }
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):
1050class UserDefinedFunction(Expression):
1051    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1054class CharacterSet(Expression):
1055    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1058class With(Expression):
1059    arg_types = {"expressions": True, "recursive": False}
1060
1061    @property
1062    def recursive(self) -> bool:
1063        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1066class WithinGroup(Expression):
1067    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1070class CTE(DerivedTable):
1071    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1074class TableAlias(Expression):
1075    arg_types = {"this": False, "columns": False}
1076
1077    @property
1078    def columns(self):
1079        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1082class BitString(Condition):
1083    pass
key = 'bitstring'
class HexString(Condition):
1086class HexString(Condition):
1087    pass
key = 'hexstring'
class ByteString(Condition):
1090class ByteString(Condition):
1091    pass
key = 'bytestring'
class RawString(Condition):
1094class RawString(Condition):
1095    pass
key = 'rawstring'
class Column(Condition):
1098class Column(Condition):
1099    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1100
1101    @property
1102    def table(self) -> str:
1103        return self.text("table")
1104
1105    @property
1106    def db(self) -> str:
1107        return self.text("db")
1108
1109    @property
1110    def catalog(self) -> str:
1111        return self.text("catalog")
1112
1113    @property
1114    def output_name(self) -> str:
1115        return self.name
1116
1117    @property
1118    def parts(self) -> t.List[Identifier]:
1119        """Return the parts of a column in order catalog, db, table, name."""
1120        return [
1121            t.cast(Identifier, self.args[part])
1122            for part in ("catalog", "db", "table", "this")
1123            if self.args.get(part)
1124        ]
1125
1126    def to_dot(self) -> Dot:
1127        """Converts the column into a dot expression."""
1128        parts = self.parts
1129        parent = self.parent
1130
1131        while parent:
1132            if isinstance(parent, Dot):
1133                parts.append(parent.expression)
1134            parent = parent.parent
1135
1136        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:
1126    def to_dot(self) -> Dot:
1127        """Converts the column into a dot expression."""
1128        parts = self.parts
1129        parent = self.parent
1130
1131        while parent:
1132            if isinstance(parent, Dot):
1133                parts.append(parent.expression)
1134            parent = parent.parent
1135
1136        return Dot.build(parts)

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1139class ColumnPosition(Expression):
1140    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1143class ColumnDef(Expression):
1144    arg_types = {
1145        "this": True,
1146        "kind": False,
1147        "constraints": False,
1148        "exists": False,
1149        "position": False,
1150    }
1151
1152    @property
1153    def constraints(self) -> t.List[ColumnConstraint]:
1154        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
key = 'columndef'
class AlterColumn(Expression):
1157class AlterColumn(Expression):
1158    arg_types = {
1159        "this": True,
1160        "dtype": False,
1161        "collate": False,
1162        "using": False,
1163        "default": False,
1164        "drop": False,
1165    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1168class RenameTable(Expression):
1169    pass
key = 'renametable'
class Comment(Expression):
1172class Comment(Expression):
1173    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):
1177class MergeTreeTTLAction(Expression):
1178    arg_types = {
1179        "this": True,
1180        "delete": False,
1181        "recompress": False,
1182        "to_disk": False,
1183        "to_volume": False,
1184    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1188class MergeTreeTTL(Expression):
1189    arg_types = {
1190        "expressions": True,
1191        "where": False,
1192        "group": False,
1193        "aggregates": False,
1194    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class ColumnConstraint(Expression):
1197class ColumnConstraint(Expression):
1198    arg_types = {"this": False, "kind": True}
1199
1200    @property
1201    def kind(self) -> ColumnConstraintKind:
1202        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1205class ColumnConstraintKind(Expression):
1206    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1209class AutoIncrementColumnConstraint(ColumnConstraintKind):
1210    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1213class CaseSpecificColumnConstraint(ColumnConstraintKind):
1214    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1217class CharacterSetColumnConstraint(ColumnConstraintKind):
1218    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1221class CheckColumnConstraint(ColumnConstraintKind):
1222    pass
key = 'checkcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1225class CollateColumnConstraint(ColumnConstraintKind):
1226    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1229class CommentColumnConstraint(ColumnConstraintKind):
1230    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1233class CompressColumnConstraint(ColumnConstraintKind):
1234    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1237class DateFormatColumnConstraint(ColumnConstraintKind):
1238    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1241class DefaultColumnConstraint(ColumnConstraintKind):
1242    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1245class EncodeColumnConstraint(ColumnConstraintKind):
1246    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1249class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1250    # this: True -> ALWAYS, this: False -> BY DEFAULT
1251    arg_types = {
1252        "this": False,
1253        "expression": False,
1254        "on_null": False,
1255        "start": False,
1256        "increment": False,
1257        "minvalue": False,
1258        "maxvalue": False,
1259        "cycle": False,
1260    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1263class InlineLengthColumnConstraint(ColumnConstraintKind):
1264    pass
key = 'inlinelengthcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1267class NotNullColumnConstraint(ColumnConstraintKind):
1268    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1272class OnUpdateColumnConstraint(ColumnConstraintKind):
1273    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1276class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1277    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1280class TitleColumnConstraint(ColumnConstraintKind):
1281    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1284class UniqueColumnConstraint(ColumnConstraintKind):
1285    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1288class UppercaseColumnConstraint(ColumnConstraintKind):
1289    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1292class PathColumnConstraint(ColumnConstraintKind):
1293    pass
key = 'pathcolumnconstraint'
class Constraint(Expression):
1296class Constraint(Expression):
1297    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1300class Delete(Expression):
1301    arg_types = {
1302        "with": False,
1303        "this": False,
1304        "using": False,
1305        "where": False,
1306        "returning": False,
1307        "limit": False,
1308    }
1309
1310    def delete(
1311        self,
1312        table: ExpOrStr,
1313        dialect: DialectType = None,
1314        copy: bool = True,
1315        **opts,
1316    ) -> Delete:
1317        """
1318        Create a DELETE expression or replace the table on an existing DELETE expression.
1319
1320        Example:
1321            >>> delete("tbl").sql()
1322            'DELETE FROM tbl'
1323
1324        Args:
1325            table: the table from which to delete.
1326            dialect: the dialect used to parse the input expression.
1327            copy: if `False`, modify this expression instance in-place.
1328            opts: other options to use to parse the input expressions.
1329
1330        Returns:
1331            Delete: the modified expression.
1332        """
1333        return _apply_builder(
1334            expression=table,
1335            instance=self,
1336            arg="this",
1337            dialect=dialect,
1338            into=Table,
1339            copy=copy,
1340            **opts,
1341        )
1342
1343    def where(
1344        self,
1345        *expressions: t.Optional[ExpOrStr],
1346        append: bool = True,
1347        dialect: DialectType = None,
1348        copy: bool = True,
1349        **opts,
1350    ) -> Delete:
1351        """
1352        Append to or set the WHERE expressions.
1353
1354        Example:
1355            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1356            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1357
1358        Args:
1359            *expressions: the SQL code strings to parse.
1360                If an `Expression` instance is passed, it will be used as-is.
1361                Multiple expressions are combined with an AND operator.
1362            append: if `True`, AND the new expressions to any existing expression.
1363                Otherwise, this resets the expression.
1364            dialect: the dialect used to parse the input expressions.
1365            copy: if `False`, modify this expression instance in-place.
1366            opts: other options to use to parse the input expressions.
1367
1368        Returns:
1369            Delete: the modified expression.
1370        """
1371        return _apply_conjunction_builder(
1372            *expressions,
1373            instance=self,
1374            arg="where",
1375            append=append,
1376            into=Where,
1377            dialect=dialect,
1378            copy=copy,
1379            **opts,
1380        )
1381
1382    def returning(
1383        self,
1384        expression: ExpOrStr,
1385        dialect: DialectType = None,
1386        copy: bool = True,
1387        **opts,
1388    ) -> Delete:
1389        """
1390        Set the RETURNING expression. Not supported by all dialects.
1391
1392        Example:
1393            >>> delete("tbl").returning("*", dialect="postgres").sql()
1394            'DELETE FROM tbl RETURNING *'
1395
1396        Args:
1397            expression: the SQL code strings to parse.
1398                If an `Expression` instance is passed, it will be used as-is.
1399            dialect: the dialect used to parse the input expressions.
1400            copy: if `False`, modify this expression instance in-place.
1401            opts: other options to use to parse the input expressions.
1402
1403        Returns:
1404            Delete: the modified expression.
1405        """
1406        return _apply_builder(
1407            expression=expression,
1408            instance=self,
1409            arg="returning",
1410            prefix="RETURNING",
1411            dialect=dialect,
1412            copy=copy,
1413            into=Returning,
1414            **opts,
1415        )
arg_types = {'with': False, 'this': False, 'using': False, 'where': False, 'returning': False, 'limit': 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:
1310    def delete(
1311        self,
1312        table: ExpOrStr,
1313        dialect: DialectType = None,
1314        copy: bool = True,
1315        **opts,
1316    ) -> Delete:
1317        """
1318        Create a DELETE expression or replace the table on an existing DELETE expression.
1319
1320        Example:
1321            >>> delete("tbl").sql()
1322            'DELETE FROM tbl'
1323
1324        Args:
1325            table: the table from which to delete.
1326            dialect: the dialect used to parse the input expression.
1327            copy: if `False`, modify this expression instance in-place.
1328            opts: other options to use to parse the input expressions.
1329
1330        Returns:
1331            Delete: the modified expression.
1332        """
1333        return _apply_builder(
1334            expression=table,
1335            instance=self,
1336            arg="this",
1337            dialect=dialect,
1338            into=Table,
1339            copy=copy,
1340            **opts,
1341        )

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:
1343    def where(
1344        self,
1345        *expressions: t.Optional[ExpOrStr],
1346        append: bool = True,
1347        dialect: DialectType = None,
1348        copy: bool = True,
1349        **opts,
1350    ) -> Delete:
1351        """
1352        Append to or set the WHERE expressions.
1353
1354        Example:
1355            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1356            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1357
1358        Args:
1359            *expressions: the SQL code strings to parse.
1360                If an `Expression` instance is passed, it will be used as-is.
1361                Multiple expressions are combined with an AND operator.
1362            append: if `True`, AND the new expressions to any existing expression.
1363                Otherwise, this resets the expression.
1364            dialect: the dialect used to parse the input expressions.
1365            copy: if `False`, modify this expression instance in-place.
1366            opts: other options to use to parse the input expressions.
1367
1368        Returns:
1369            Delete: the modified expression.
1370        """
1371        return _apply_conjunction_builder(
1372            *expressions,
1373            instance=self,
1374            arg="where",
1375            append=append,
1376            into=Where,
1377            dialect=dialect,
1378            copy=copy,
1379            **opts,
1380        )

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:
1382    def returning(
1383        self,
1384        expression: ExpOrStr,
1385        dialect: DialectType = None,
1386        copy: bool = True,
1387        **opts,
1388    ) -> Delete:
1389        """
1390        Set the RETURNING expression. Not supported by all dialects.
1391
1392        Example:
1393            >>> delete("tbl").returning("*", dialect="postgres").sql()
1394            'DELETE FROM tbl RETURNING *'
1395
1396        Args:
1397            expression: the SQL code strings to parse.
1398                If an `Expression` instance is passed, it will be used as-is.
1399            dialect: the dialect used to parse the input expressions.
1400            copy: if `False`, modify this expression instance in-place.
1401            opts: other options to use to parse the input expressions.
1402
1403        Returns:
1404            Delete: the modified expression.
1405        """
1406        return _apply_builder(
1407            expression=expression,
1408            instance=self,
1409            arg="returning",
1410            prefix="RETURNING",
1411            dialect=dialect,
1412            copy=copy,
1413            into=Returning,
1414            **opts,
1415        )

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):
1418class Drop(Expression):
1419    arg_types = {
1420        "this": False,
1421        "kind": False,
1422        "exists": False,
1423        "temporary": False,
1424        "materialized": False,
1425        "cascade": False,
1426        "constraints": False,
1427        "purge": False,
1428    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1431class Filter(Expression):
1432    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1435class Check(Expression):
1436    pass
key = 'check'
class Directory(Expression):
1439class Directory(Expression):
1440    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1441    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1444class ForeignKey(Expression):
1445    arg_types = {
1446        "expressions": True,
1447        "reference": False,
1448        "delete": False,
1449        "update": False,
1450    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1453class PrimaryKey(Expression):
1454    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1459class Into(Expression):
1460    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1463class From(Expression):
1464    @property
1465    def name(self) -> str:
1466        return self.this.name
1467
1468    @property
1469    def alias_or_name(self) -> str:
1470        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1473class Having(Expression):
1474    pass
key = 'having'
class Hint(Expression):
1477class Hint(Expression):
1478    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1481class JoinHint(Expression):
1482    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1485class Identifier(Expression):
1486    arg_types = {"this": True, "quoted": False}
1487
1488    @property
1489    def quoted(self) -> bool:
1490        return bool(self.args.get("quoted"))
1491
1492    @property
1493    def hashable_args(self) -> t.Any:
1494        if self.quoted and any(char.isupper() for char in self.this):
1495            return (self.this, self.quoted)
1496        return self.this.lower()
1497
1498    @property
1499    def output_name(self) -> str:
1500        return self.name
arg_types = {'this': True, 'quoted': 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):
1503class Index(Expression):
1504    arg_types = {
1505        "this": False,
1506        "table": False,
1507        "using": False,
1508        "where": False,
1509        "columns": False,
1510        "unique": False,
1511        "primary": False,
1512        "amp": False,  # teradata
1513        "partition_by": False,  # teradata
1514    }
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(Expression):
1517class Insert(Expression):
1518    arg_types = {
1519        "with": False,
1520        "this": True,
1521        "expression": False,
1522        "conflict": False,
1523        "returning": False,
1524        "overwrite": False,
1525        "exists": False,
1526        "partition": False,
1527        "alternative": False,
1528        "where": False,
1529    }
1530
1531    def with_(
1532        self,
1533        alias: ExpOrStr,
1534        as_: ExpOrStr,
1535        recursive: t.Optional[bool] = None,
1536        append: bool = True,
1537        dialect: DialectType = None,
1538        copy: bool = True,
1539        **opts,
1540    ) -> Insert:
1541        """
1542        Append to or set the common table expressions.
1543
1544        Example:
1545            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1546            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1547
1548        Args:
1549            alias: the SQL code string to parse as the table name.
1550                If an `Expression` instance is passed, this is used as-is.
1551            as_: the SQL code string to parse as the table expression.
1552                If an `Expression` instance is passed, it will be used as-is.
1553            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1554            append: if `True`, add to any existing expressions.
1555                Otherwise, this resets the expressions.
1556            dialect: the dialect used to parse the input expression.
1557            copy: if `False`, modify this expression instance in-place.
1558            opts: other options to use to parse the input expressions.
1559
1560        Returns:
1561            The modified expression.
1562        """
1563        return _apply_cte_builder(
1564            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1565        )
arg_types = {'with': False, 'this': True, 'expression': False, 'conflict': False, 'returning': False, 'overwrite': False, 'exists': False, 'partition': False, 'alternative': False, 'where': 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:
1531    def with_(
1532        self,
1533        alias: ExpOrStr,
1534        as_: ExpOrStr,
1535        recursive: t.Optional[bool] = None,
1536        append: bool = True,
1537        dialect: DialectType = None,
1538        copy: bool = True,
1539        **opts,
1540    ) -> Insert:
1541        """
1542        Append to or set the common table expressions.
1543
1544        Example:
1545            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1546            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1547
1548        Args:
1549            alias: the SQL code string to parse as the table name.
1550                If an `Expression` instance is passed, this is used as-is.
1551            as_: the SQL code string to parse as the table expression.
1552                If an `Expression` instance is passed, it will be used as-is.
1553            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1554            append: if `True`, add to any existing expressions.
1555                Otherwise, this resets the expressions.
1556            dialect: the dialect used to parse the input expression.
1557            copy: if `False`, modify this expression instance in-place.
1558            opts: other options to use to parse the input expressions.
1559
1560        Returns:
1561            The modified expression.
1562        """
1563        return _apply_cte_builder(
1564            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1565        )

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):
1568class OnConflict(Expression):
1569    arg_types = {
1570        "duplicate": False,
1571        "expressions": False,
1572        "nothing": False,
1573        "key": False,
1574        "constraint": False,
1575    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1578class Returning(Expression):
1579    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'returning'
class Introducer(Expression):
1583class Introducer(Expression):
1584    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1588class National(Expression):
1589    pass
key = 'national'
class LoadData(Expression):
1592class LoadData(Expression):
1593    arg_types = {
1594        "this": True,
1595        "local": False,
1596        "overwrite": False,
1597        "inpath": True,
1598        "partition": False,
1599        "input_format": False,
1600        "serde": False,
1601    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1604class Partition(Expression):
1605    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1608class Fetch(Expression):
1609    arg_types = {
1610        "direction": False,
1611        "count": False,
1612        "percent": False,
1613        "with_ties": False,
1614    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1617class Group(Expression):
1618    arg_types = {
1619        "expressions": False,
1620        "grouping_sets": False,
1621        "cube": False,
1622        "rollup": False,
1623        "totals": False,
1624        "all": False,
1625    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1628class Lambda(Expression):
1629    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1632class Limit(Expression):
1633    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1636class Literal(Condition):
1637    arg_types = {"this": True, "is_string": True}
1638
1639    @property
1640    def hashable_args(self) -> t.Any:
1641        return (self.this, self.args.get("is_string"))
1642
1643    @classmethod
1644    def number(cls, number) -> Literal:
1645        return cls(this=str(number), is_string=False)
1646
1647    @classmethod
1648    def string(cls, string) -> Literal:
1649        return cls(this=str(string), is_string=True)
1650
1651    @property
1652    def output_name(self) -> str:
1653        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1643    @classmethod
1644    def number(cls, number) -> Literal:
1645        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1647    @classmethod
1648    def string(cls, string) -> Literal:
1649        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):
1656class Join(Expression):
1657    arg_types = {
1658        "this": True,
1659        "on": False,
1660        "side": False,
1661        "kind": False,
1662        "using": False,
1663        "method": False,
1664        "global": False,
1665        "hint": False,
1666    }
1667
1668    @property
1669    def method(self) -> str:
1670        return self.text("method").upper()
1671
1672    @property
1673    def kind(self) -> str:
1674        return self.text("kind").upper()
1675
1676    @property
1677    def side(self) -> str:
1678        return self.text("side").upper()
1679
1680    @property
1681    def hint(self) -> str:
1682        return self.text("hint").upper()
1683
1684    @property
1685    def alias_or_name(self) -> str:
1686        return self.this.alias_or_name
1687
1688    def on(
1689        self,
1690        *expressions: t.Optional[ExpOrStr],
1691        append: bool = True,
1692        dialect: DialectType = None,
1693        copy: bool = True,
1694        **opts,
1695    ) -> Join:
1696        """
1697        Append to or set the ON expressions.
1698
1699        Example:
1700            >>> import sqlglot
1701            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1702            'JOIN x ON y = 1'
1703
1704        Args:
1705            *expressions: the SQL code strings to parse.
1706                If an `Expression` instance is passed, it will be used as-is.
1707                Multiple expressions are combined with an AND operator.
1708            append: if `True`, AND the new expressions to any existing expression.
1709                Otherwise, this resets the expression.
1710            dialect: the dialect used to parse the input expressions.
1711            copy: if `False`, modify this expression instance in-place.
1712            opts: other options to use to parse the input expressions.
1713
1714        Returns:
1715            The modified Join expression.
1716        """
1717        join = _apply_conjunction_builder(
1718            *expressions,
1719            instance=self,
1720            arg="on",
1721            append=append,
1722            dialect=dialect,
1723            copy=copy,
1724            **opts,
1725        )
1726
1727        if join.kind == "CROSS":
1728            join.set("kind", None)
1729
1730        return join
1731
1732    def using(
1733        self,
1734        *expressions: t.Optional[ExpOrStr],
1735        append: bool = True,
1736        dialect: DialectType = None,
1737        copy: bool = True,
1738        **opts,
1739    ) -> Join:
1740        """
1741        Append to or set the USING expressions.
1742
1743        Example:
1744            >>> import sqlglot
1745            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1746            'JOIN x USING (foo, bla)'
1747
1748        Args:
1749            *expressions: the SQL code strings to parse.
1750                If an `Expression` instance is passed, it will be used as-is.
1751            append: if `True`, concatenate the new expressions to the existing "using" list.
1752                Otherwise, this resets the expression.
1753            dialect: the dialect used to parse the input expressions.
1754            copy: if `False`, modify this expression instance in-place.
1755            opts: other options to use to parse the input expressions.
1756
1757        Returns:
1758            The modified Join expression.
1759        """
1760        join = _apply_list_builder(
1761            *expressions,
1762            instance=self,
1763            arg="using",
1764            append=append,
1765            dialect=dialect,
1766            copy=copy,
1767            **opts,
1768        )
1769
1770        if join.kind == "CROSS":
1771            join.set("kind", None)
1772
1773        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:
1688    def on(
1689        self,
1690        *expressions: t.Optional[ExpOrStr],
1691        append: bool = True,
1692        dialect: DialectType = None,
1693        copy: bool = True,
1694        **opts,
1695    ) -> Join:
1696        """
1697        Append to or set the ON expressions.
1698
1699        Example:
1700            >>> import sqlglot
1701            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1702            'JOIN x ON y = 1'
1703
1704        Args:
1705            *expressions: the SQL code strings to parse.
1706                If an `Expression` instance is passed, it will be used as-is.
1707                Multiple expressions are combined with an AND operator.
1708            append: if `True`, AND the new expressions to any existing expression.
1709                Otherwise, this resets the expression.
1710            dialect: the dialect used to parse the input expressions.
1711            copy: if `False`, modify this expression instance in-place.
1712            opts: other options to use to parse the input expressions.
1713
1714        Returns:
1715            The modified Join expression.
1716        """
1717        join = _apply_conjunction_builder(
1718            *expressions,
1719            instance=self,
1720            arg="on",
1721            append=append,
1722            dialect=dialect,
1723            copy=copy,
1724            **opts,
1725        )
1726
1727        if join.kind == "CROSS":
1728            join.set("kind", None)
1729
1730        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:
1732    def using(
1733        self,
1734        *expressions: t.Optional[ExpOrStr],
1735        append: bool = True,
1736        dialect: DialectType = None,
1737        copy: bool = True,
1738        **opts,
1739    ) -> Join:
1740        """
1741        Append to or set the USING expressions.
1742
1743        Example:
1744            >>> import sqlglot
1745            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1746            'JOIN x USING (foo, bla)'
1747
1748        Args:
1749            *expressions: the SQL code strings to parse.
1750                If an `Expression` instance is passed, it will be used as-is.
1751            append: if `True`, concatenate the new expressions to the existing "using" list.
1752                Otherwise, this resets the expression.
1753            dialect: the dialect used to parse the input expressions.
1754            copy: if `False`, modify this expression instance in-place.
1755            opts: other options to use to parse the input expressions.
1756
1757        Returns:
1758            The modified Join expression.
1759        """
1760        join = _apply_list_builder(
1761            *expressions,
1762            instance=self,
1763            arg="using",
1764            append=append,
1765            dialect=dialect,
1766            copy=copy,
1767            **opts,
1768        )
1769
1770        if join.kind == "CROSS":
1771            join.set("kind", None)
1772
1773        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):
1776class Lateral(UDTF):
1777    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):
1780class MatchRecognize(Expression):
1781    arg_types = {
1782        "partition_by": False,
1783        "order": False,
1784        "measures": False,
1785        "rows": False,
1786        "after": False,
1787        "pattern": False,
1788        "define": False,
1789        "alias": False,
1790    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1795class Final(Expression):
1796    pass
key = 'final'
class Offset(Expression):
1799class Offset(Expression):
1800    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1803class Order(Expression):
1804    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1809class Cluster(Order):
1810    pass
key = 'cluster'
class Distribute(Order):
1813class Distribute(Order):
1814    pass
key = 'distribute'
class Sort(Order):
1817class Sort(Order):
1818    pass
key = 'sort'
class Ordered(Expression):
1821class Ordered(Expression):
1822    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1825class Property(Expression):
1826    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1829class AlgorithmProperty(Property):
1830    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1833class AutoIncrementProperty(Property):
1834    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1837class BlockCompressionProperty(Property):
1838    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):
1841class CharacterSetProperty(Property):
1842    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1845class ChecksumProperty(Property):
1846    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1849class CollateProperty(Property):
1850    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1853class CopyGrantsProperty(Property):
1854    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1857class DataBlocksizeProperty(Property):
1858    arg_types = {
1859        "size": False,
1860        "units": False,
1861        "minimum": False,
1862        "maximum": False,
1863        "default": False,
1864    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1867class DefinerProperty(Property):
1868    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1871class DistKeyProperty(Property):
1872    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1875class DistStyleProperty(Property):
1876    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1879class EngineProperty(Property):
1880    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1883class ToTableProperty(Property):
1884    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1887class ExecuteAsProperty(Property):
1888    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1891class ExternalProperty(Property):
1892    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1895class FallbackProperty(Property):
1896    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1899class FileFormatProperty(Property):
1900    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1903class FreespaceProperty(Property):
1904    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1907class InputOutputFormat(Expression):
1908    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1911class IsolatedLoadingProperty(Property):
1912    arg_types = {
1913        "no": True,
1914        "concurrent": True,
1915        "for_all": True,
1916        "for_insert": True,
1917        "for_none": True,
1918    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1921class JournalProperty(Property):
1922    arg_types = {
1923        "no": False,
1924        "dual": False,
1925        "before": False,
1926        "local": False,
1927        "after": False,
1928    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1931class LanguageProperty(Property):
1932    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1936class ClusteredByProperty(Property):
1937    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1940class DictProperty(Property):
1941    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1944class DictSubProperty(Property):
1945    pass
key = 'dictsubproperty'
class DictRange(Property):
1948class DictRange(Property):
1949    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1954class OnCluster(Property):
1955    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1958class LikeProperty(Property):
1959    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1962class LocationProperty(Property):
1963    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
1966class LockingProperty(Property):
1967    arg_types = {
1968        "this": False,
1969        "kind": True,
1970        "for_or_in": True,
1971        "lock_type": True,
1972        "override": False,
1973    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
1976class LogProperty(Property):
1977    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
1980class MaterializedProperty(Property):
1981    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
1984class MergeBlockRatioProperty(Property):
1985    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):
1988class NoPrimaryIndexProperty(Property):
1989    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
1992class OnCommitProperty(Property):
1993    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
1996class PartitionedByProperty(Property):
1997    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2000class ReturnsProperty(Property):
2001    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2004class RowFormatProperty(Property):
2005    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2008class RowFormatDelimitedProperty(Property):
2009    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2010    arg_types = {
2011        "fields": False,
2012        "escaped": False,
2013        "collection_items": False,
2014        "map_keys": False,
2015        "lines": False,
2016        "null": False,
2017        "serde": False,
2018    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2021class RowFormatSerdeProperty(Property):
2022    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatserdeproperty'
class SchemaCommentProperty(Property):
2025class SchemaCommentProperty(Property):
2026    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2029class SerdeProperties(Property):
2030    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2033class SetProperty(Property):
2034    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2037class SettingsProperty(Property):
2038    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2041class SortKeyProperty(Property):
2042    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2045class SqlSecurityProperty(Property):
2046    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2049class StabilityProperty(Property):
2050    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2053class TemporaryProperty(Property):
2054    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2057class TransientProperty(Property):
2058    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2061class VolatileProperty(Property):
2062    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2065class WithDataProperty(Property):
2066    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2069class WithJournalTableProperty(Property):
2070    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2073class Properties(Expression):
2074    arg_types = {"expressions": True}
2075
2076    NAME_TO_PROPERTY = {
2077        "ALGORITHM": AlgorithmProperty,
2078        "AUTO_INCREMENT": AutoIncrementProperty,
2079        "CHARACTER SET": CharacterSetProperty,
2080        "CLUSTERED_BY": ClusteredByProperty,
2081        "COLLATE": CollateProperty,
2082        "COMMENT": SchemaCommentProperty,
2083        "DEFINER": DefinerProperty,
2084        "DISTKEY": DistKeyProperty,
2085        "DISTSTYLE": DistStyleProperty,
2086        "ENGINE": EngineProperty,
2087        "EXECUTE AS": ExecuteAsProperty,
2088        "FORMAT": FileFormatProperty,
2089        "LANGUAGE": LanguageProperty,
2090        "LOCATION": LocationProperty,
2091        "PARTITIONED_BY": PartitionedByProperty,
2092        "RETURNS": ReturnsProperty,
2093        "ROW_FORMAT": RowFormatProperty,
2094        "SORTKEY": SortKeyProperty,
2095    }
2096
2097    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2098
2099    # CREATE property locations
2100    # Form: schema specified
2101    #   create [POST_CREATE]
2102    #     table a [POST_NAME]
2103    #     (b int) [POST_SCHEMA]
2104    #     with ([POST_WITH])
2105    #     index (b) [POST_INDEX]
2106    #
2107    # Form: alias selection
2108    #   create [POST_CREATE]
2109    #     table a [POST_NAME]
2110    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2111    #     index (c) [POST_INDEX]
2112    class Location(AutoName):
2113        POST_CREATE = auto()
2114        POST_NAME = auto()
2115        POST_SCHEMA = auto()
2116        POST_WITH = auto()
2117        POST_ALIAS = auto()
2118        POST_EXPRESSION = auto()
2119        POST_INDEX = auto()
2120        UNSUPPORTED = auto()
2121
2122    @classmethod
2123    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2124        expressions = []
2125        for key, value in properties_dict.items():
2126            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2127            if property_cls:
2128                expressions.append(property_cls(this=convert(value)))
2129            else:
2130                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2131
2132        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:
2122    @classmethod
2123    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2124        expressions = []
2125        for key, value in properties_dict.items():
2126            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2127            if property_cls:
2128                expressions.append(property_cls(this=convert(value)))
2129            else:
2130                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2131
2132        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2112    class Location(AutoName):
2113        POST_CREATE = auto()
2114        POST_NAME = auto()
2115        POST_SCHEMA = auto()
2116        POST_WITH = auto()
2117        POST_ALIAS = auto()
2118        POST_EXPRESSION = auto()
2119        POST_INDEX = auto()
2120        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):
2135class Qualify(Expression):
2136    pass
key = 'qualify'
class Return(Expression):
2140class Return(Expression):
2141    pass
key = 'return'
class Reference(Expression):
2144class Reference(Expression):
2145    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2148class Tuple(Expression):
2149    arg_types = {"expressions": False}
2150
2151    def isin(
2152        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2153    ) -> In:
2154        return In(
2155            this=_maybe_copy(self, copy),
2156            expressions=[convert(e, copy=copy) for e in expressions],
2157            query=maybe_parse(query, copy=copy, **opts) if query else None,
2158        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2151    def isin(
2152        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2153    ) -> In:
2154        return In(
2155            this=_maybe_copy(self, copy),
2156            expressions=[convert(e, copy=copy) for e in expressions],
2157            query=maybe_parse(query, copy=copy, **opts) if query else None,
2158        )
key = 'tuple'
class Subqueryable(Unionable):
2161class Subqueryable(Unionable):
2162    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2163        """
2164        Convert this expression to an aliased expression that can be used as a Subquery.
2165
2166        Example:
2167            >>> subquery = Select().select("x").from_("tbl").subquery()
2168            >>> Select().select("x").from_(subquery).sql()
2169            'SELECT x FROM (SELECT x FROM tbl)'
2170
2171        Args:
2172            alias (str | Identifier): an optional alias for the subquery
2173            copy (bool): if `False`, modify this expression instance in-place.
2174
2175        Returns:
2176            Alias: the subquery
2177        """
2178        instance = _maybe_copy(self, copy)
2179        if not isinstance(alias, Expression):
2180            alias = TableAlias(this=to_identifier(alias)) if alias else None
2181
2182        return Subquery(this=instance, alias=alias)
2183
2184    def limit(
2185        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2186    ) -> Select:
2187        raise NotImplementedError
2188
2189    @property
2190    def ctes(self):
2191        with_ = self.args.get("with")
2192        if not with_:
2193            return []
2194        return with_.expressions
2195
2196    @property
2197    def selects(self):
2198        raise NotImplementedError("Subqueryable objects must implement `selects`")
2199
2200    @property
2201    def named_selects(self):
2202        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2203
2204    def with_(
2205        self,
2206        alias: ExpOrStr,
2207        as_: ExpOrStr,
2208        recursive: t.Optional[bool] = None,
2209        append: bool = True,
2210        dialect: DialectType = None,
2211        copy: bool = True,
2212        **opts,
2213    ) -> Subqueryable:
2214        """
2215        Append to or set the common table expressions.
2216
2217        Example:
2218            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2219            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2220
2221        Args:
2222            alias: the SQL code string to parse as the table name.
2223                If an `Expression` instance is passed, this is used as-is.
2224            as_: the SQL code string to parse as the table expression.
2225                If an `Expression` instance is passed, it will be used as-is.
2226            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2227            append: if `True`, add to any existing expressions.
2228                Otherwise, this resets the expressions.
2229            dialect: the dialect used to parse the input expression.
2230            copy: if `False`, modify this expression instance in-place.
2231            opts: other options to use to parse the input expressions.
2232
2233        Returns:
2234            The modified expression.
2235        """
2236        return _apply_cte_builder(
2237            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2238        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2162    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2163        """
2164        Convert this expression to an aliased expression that can be used as a Subquery.
2165
2166        Example:
2167            >>> subquery = Select().select("x").from_("tbl").subquery()
2168            >>> Select().select("x").from_(subquery).sql()
2169            'SELECT x FROM (SELECT x FROM tbl)'
2170
2171        Args:
2172            alias (str | Identifier): an optional alias for the subquery
2173            copy (bool): if `False`, modify this expression instance in-place.
2174
2175        Returns:
2176            Alias: the subquery
2177        """
2178        instance = _maybe_copy(self, copy)
2179        if not isinstance(alias, Expression):
2180            alias = TableAlias(this=to_identifier(alias)) if alias else None
2181
2182        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:
2184    def limit(
2185        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2186    ) -> Select:
2187        raise NotImplementedError
ctes
selects
named_selects
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:
2204    def with_(
2205        self,
2206        alias: ExpOrStr,
2207        as_: ExpOrStr,
2208        recursive: t.Optional[bool] = None,
2209        append: bool = True,
2210        dialect: DialectType = None,
2211        copy: bool = True,
2212        **opts,
2213    ) -> Subqueryable:
2214        """
2215        Append to or set the common table expressions.
2216
2217        Example:
2218            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2219            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2220
2221        Args:
2222            alias: the SQL code string to parse as the table name.
2223                If an `Expression` instance is passed, this is used as-is.
2224            as_: the SQL code string to parse as the table expression.
2225                If an `Expression` instance is passed, it will be used as-is.
2226            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2227            append: if `True`, add to any existing expressions.
2228                Otherwise, this resets the expressions.
2229            dialect: the dialect used to parse the input expression.
2230            copy: if `False`, modify this expression instance in-place.
2231            opts: other options to use to parse the input expressions.
2232
2233        Returns:
2234            The modified expression.
2235        """
2236        return _apply_cte_builder(
2237            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2238        )

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):
2265class WithTableHint(Expression):
2266    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2270class IndexTableHint(Expression):
2271    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2274class Table(Expression):
2275    arg_types = {
2276        "this": True,
2277        "alias": False,
2278        "db": False,
2279        "catalog": False,
2280        "laterals": False,
2281        "joins": False,
2282        "pivots": False,
2283        "hints": False,
2284        "system_time": False,
2285    }
2286
2287    @property
2288    def name(self) -> str:
2289        if isinstance(self.this, Func):
2290            return ""
2291        return self.this.name
2292
2293    @property
2294    def db(self) -> str:
2295        return self.text("db")
2296
2297    @property
2298    def catalog(self) -> str:
2299        return self.text("catalog")
2300
2301    @property
2302    def parts(self) -> t.List[Identifier]:
2303        """Return the parts of a table in order catalog, db, table."""
2304        return [
2305            t.cast(Identifier, self.args[part])
2306            for part in ("catalog", "db", "this")
2307            if self.args.get(part)
2308        ]
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

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

key = 'table'
class SystemTime(Expression):
2312class SystemTime(Expression):
2313    arg_types = {
2314        "this": False,
2315        "expression": False,
2316        "kind": True,
2317    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2320class Union(Subqueryable):
2321    arg_types = {
2322        "with": False,
2323        "this": True,
2324        "expression": True,
2325        "distinct": False,
2326        **QUERY_MODIFIERS,
2327    }
2328
2329    def limit(
2330        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2331    ) -> Select:
2332        """
2333        Set the LIMIT expression.
2334
2335        Example:
2336            >>> select("1").union(select("1")).limit(1).sql()
2337            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2338
2339        Args:
2340            expression: the SQL code string to parse.
2341                This can also be an integer.
2342                If a `Limit` instance is passed, this is used as-is.
2343                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2344            dialect: the dialect used to parse the input expression.
2345            copy: if `False`, modify this expression instance in-place.
2346            opts: other options to use to parse the input expressions.
2347
2348        Returns:
2349            The limited subqueryable.
2350        """
2351        return (
2352            select("*")
2353            .from_(self.subquery(alias="_l_0", copy=copy))
2354            .limit(expression, dialect=dialect, copy=False, **opts)
2355        )
2356
2357    def select(
2358        self,
2359        *expressions: t.Optional[ExpOrStr],
2360        append: bool = True,
2361        dialect: DialectType = None,
2362        copy: bool = True,
2363        **opts,
2364    ) -> Union:
2365        """Append to or set the SELECT of the union recursively.
2366
2367        Example:
2368            >>> from sqlglot import parse_one
2369            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2370            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2371
2372        Args:
2373            *expressions: the SQL code strings to parse.
2374                If an `Expression` instance is passed, it will be used as-is.
2375            append: if `True`, add to any existing expressions.
2376                Otherwise, this resets the expressions.
2377            dialect: the dialect used to parse the input expressions.
2378            copy: if `False`, modify this expression instance in-place.
2379            opts: other options to use to parse the input expressions.
2380
2381        Returns:
2382            Union: the modified expression.
2383        """
2384        this = self.copy() if copy else self
2385        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2386        this.expression.unnest().select(
2387            *expressions, append=append, dialect=dialect, copy=False, **opts
2388        )
2389        return this
2390
2391    @property
2392    def named_selects(self):
2393        return self.this.unnest().named_selects
2394
2395    @property
2396    def is_star(self) -> bool:
2397        return self.this.is_star or self.expression.is_star
2398
2399    @property
2400    def selects(self):
2401        return self.this.unnest().selects
2402
2403    @property
2404    def left(self):
2405        return self.this
2406
2407    @property
2408    def right(self):
2409        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:
2329    def limit(
2330        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2331    ) -> Select:
2332        """
2333        Set the LIMIT expression.
2334
2335        Example:
2336            >>> select("1").union(select("1")).limit(1).sql()
2337            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2338
2339        Args:
2340            expression: the SQL code string to parse.
2341                This can also be an integer.
2342                If a `Limit` instance is passed, this is used as-is.
2343                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2344            dialect: the dialect used to parse the input expression.
2345            copy: if `False`, modify this expression instance in-place.
2346            opts: other options to use to parse the input expressions.
2347
2348        Returns:
2349            The limited subqueryable.
2350        """
2351        return (
2352            select("*")
2353            .from_(self.subquery(alias="_l_0", copy=copy))
2354            .limit(expression, dialect=dialect, copy=False, **opts)
2355        )

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:
2357    def select(
2358        self,
2359        *expressions: t.Optional[ExpOrStr],
2360        append: bool = True,
2361        dialect: DialectType = None,
2362        copy: bool = True,
2363        **opts,
2364    ) -> Union:
2365        """Append to or set the SELECT of the union recursively.
2366
2367        Example:
2368            >>> from sqlglot import parse_one
2369            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2370            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2371
2372        Args:
2373            *expressions: the SQL code strings to parse.
2374                If an `Expression` instance is passed, it will be used as-is.
2375            append: if `True`, add to any existing expressions.
2376                Otherwise, this resets the expressions.
2377            dialect: the dialect used to parse the input expressions.
2378            copy: if `False`, modify this expression instance in-place.
2379            opts: other options to use to parse the input expressions.
2380
2381        Returns:
2382            Union: the modified expression.
2383        """
2384        this = self.copy() if copy else self
2385        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2386        this.expression.unnest().select(
2387            *expressions, append=append, dialect=dialect, copy=False, **opts
2388        )
2389        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
is_star: bool

Checks whether an expression is a star.

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

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:
2507    def group_by(
2508        self,
2509        *expressions: t.Optional[ExpOrStr],
2510        append: bool = True,
2511        dialect: DialectType = None,
2512        copy: bool = True,
2513        **opts,
2514    ) -> Select:
2515        """
2516        Set the GROUP BY expression.
2517
2518        Example:
2519            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2520            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2521
2522        Args:
2523            *expressions: the SQL code strings to parse.
2524                If a `Group` instance is passed, this is used as-is.
2525                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2526                If nothing is passed in then a group by is not applied to the expression
2527            append: if `True`, add to any existing expressions.
2528                Otherwise, this flattens all the `Group` expression into a single expression.
2529            dialect: the dialect used to parse the input expression.
2530            copy: if `False`, modify this expression instance in-place.
2531            opts: other options to use to parse the input expressions.
2532
2533        Returns:
2534            The modified Select expression.
2535        """
2536        if not expressions:
2537            return self if not copy else self.copy()
2538
2539        return _apply_child_list_builder(
2540            *expressions,
2541            instance=self,
2542            arg="group",
2543            append=append,
2544            copy=copy,
2545            prefix="GROUP BY",
2546            into=Group,
2547            dialect=dialect,
2548            **opts,
2549        )

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:
2551    def order_by(
2552        self,
2553        *expressions: t.Optional[ExpOrStr],
2554        append: bool = True,
2555        dialect: DialectType = None,
2556        copy: bool = True,
2557        **opts,
2558    ) -> Select:
2559        """
2560        Set the ORDER BY expression.
2561
2562        Example:
2563            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2564            'SELECT x FROM tbl ORDER BY x DESC'
2565
2566        Args:
2567            *expressions: the SQL code strings to parse.
2568                If a `Group` instance is passed, this is used as-is.
2569                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2570            append: if `True`, add to any existing expressions.
2571                Otherwise, this flattens all the `Order` expression into a single expression.
2572            dialect: the dialect used to parse the input expression.
2573            copy: if `False`, modify this expression instance in-place.
2574            opts: other options to use to parse the input expressions.
2575
2576        Returns:
2577            The modified Select expression.
2578        """
2579        return _apply_child_list_builder(
2580            *expressions,
2581            instance=self,
2582            arg="order",
2583            append=append,
2584            copy=copy,
2585            prefix="ORDER BY",
2586            into=Order,
2587            dialect=dialect,
2588            **opts,
2589        )

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:
2591    def sort_by(
2592        self,
2593        *expressions: t.Optional[ExpOrStr],
2594        append: bool = True,
2595        dialect: DialectType = None,
2596        copy: bool = True,
2597        **opts,
2598    ) -> Select:
2599        """
2600        Set the SORT BY expression.
2601
2602        Example:
2603            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2604            'SELECT x FROM tbl SORT BY x DESC'
2605
2606        Args:
2607            *expressions: the SQL code strings to parse.
2608                If a `Group` instance is passed, this is used as-is.
2609                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2610            append: if `True`, add to any existing expressions.
2611                Otherwise, this flattens all the `Order` expression into a single expression.
2612            dialect: the dialect used to parse the input expression.
2613            copy: if `False`, modify this expression instance in-place.
2614            opts: other options to use to parse the input expressions.
2615
2616        Returns:
2617            The modified Select expression.
2618        """
2619        return _apply_child_list_builder(
2620            *expressions,
2621            instance=self,
2622            arg="sort",
2623            append=append,
2624            copy=copy,
2625            prefix="SORT BY",
2626            into=Sort,
2627            dialect=dialect,
2628            **opts,
2629        )

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:
2631    def cluster_by(
2632        self,
2633        *expressions: t.Optional[ExpOrStr],
2634        append: bool = True,
2635        dialect: DialectType = None,
2636        copy: bool = True,
2637        **opts,
2638    ) -> Select:
2639        """
2640        Set the CLUSTER BY expression.
2641
2642        Example:
2643            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2644            'SELECT x FROM tbl CLUSTER BY x DESC'
2645
2646        Args:
2647            *expressions: the SQL code strings to parse.
2648                If a `Group` instance is passed, this is used as-is.
2649                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2650            append: if `True`, add to any existing expressions.
2651                Otherwise, this flattens all the `Order` expression into a single expression.
2652            dialect: the dialect used to parse the input expression.
2653            copy: if `False`, modify this expression instance in-place.
2654            opts: other options to use to parse the input expressions.
2655
2656        Returns:
2657            The modified Select expression.
2658        """
2659        return _apply_child_list_builder(
2660            *expressions,
2661            instance=self,
2662            arg="cluster",
2663            append=append,
2664            copy=copy,
2665            prefix="CLUSTER BY",
2666            into=Cluster,
2667            dialect=dialect,
2668            **opts,
2669        )

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:
2671    def limit(
2672        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2673    ) -> Select:
2674        """
2675        Set the LIMIT expression.
2676
2677        Example:
2678            >>> Select().from_("tbl").select("x").limit(10).sql()
2679            'SELECT x FROM tbl LIMIT 10'
2680
2681        Args:
2682            expression: the SQL code string to parse.
2683                This can also be an integer.
2684                If a `Limit` instance is passed, this is used as-is.
2685                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2686            dialect: the dialect used to parse the input expression.
2687            copy: if `False`, modify this expression instance in-place.
2688            opts: other options to use to parse the input expressions.
2689
2690        Returns:
2691            Select: the modified expression.
2692        """
2693        return _apply_builder(
2694            expression=expression,
2695            instance=self,
2696            arg="limit",
2697            into=Limit,
2698            prefix="LIMIT",
2699            dialect=dialect,
2700            copy=copy,
2701            **opts,
2702        )

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:
2704    def offset(
2705        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2706    ) -> Select:
2707        """
2708        Set the OFFSET expression.
2709
2710        Example:
2711            >>> Select().from_("tbl").select("x").offset(10).sql()
2712            'SELECT x FROM tbl OFFSET 10'
2713
2714        Args:
2715            expression: the SQL code string to parse.
2716                This can also be an integer.
2717                If a `Offset` instance is passed, this is used as-is.
2718                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2719            dialect: the dialect used to parse the input expression.
2720            copy: if `False`, modify this expression instance in-place.
2721            opts: other options to use to parse the input expressions.
2722
2723        Returns:
2724            The modified Select expression.
2725        """
2726        return _apply_builder(
2727            expression=expression,
2728            instance=self,
2729            arg="offset",
2730            into=Offset,
2731            prefix="OFFSET",
2732            dialect=dialect,
2733            copy=copy,
2734            **opts,
2735        )

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:
2737    def select(
2738        self,
2739        *expressions: t.Optional[ExpOrStr],
2740        append: bool = True,
2741        dialect: DialectType = None,
2742        copy: bool = True,
2743        **opts,
2744    ) -> Select:
2745        """
2746        Append to or set the SELECT expressions.
2747
2748        Example:
2749            >>> Select().select("x", "y").sql()
2750            'SELECT x, y'
2751
2752        Args:
2753            *expressions: the SQL code strings to parse.
2754                If an `Expression` instance is passed, it will be used as-is.
2755            append: if `True`, add to any existing expressions.
2756                Otherwise, this resets the expressions.
2757            dialect: the dialect used to parse the input expressions.
2758            copy: if `False`, modify this expression instance in-place.
2759            opts: other options to use to parse the input expressions.
2760
2761        Returns:
2762            The modified Select expression.
2763        """
2764        return _apply_list_builder(
2765            *expressions,
2766            instance=self,
2767            arg="expressions",
2768            append=append,
2769            dialect=dialect,
2770            copy=copy,
2771            **opts,
2772        )

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:
2774    def lateral(
2775        self,
2776        *expressions: t.Optional[ExpOrStr],
2777        append: bool = True,
2778        dialect: DialectType = None,
2779        copy: bool = True,
2780        **opts,
2781    ) -> Select:
2782        """
2783        Append to or set the LATERAL expressions.
2784
2785        Example:
2786            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2787            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2788
2789        Args:
2790            *expressions: the SQL code strings to parse.
2791                If an `Expression` instance is passed, it will be used as-is.
2792            append: if `True`, add to any existing expressions.
2793                Otherwise, this resets the expressions.
2794            dialect: the dialect used to parse the input expressions.
2795            copy: if `False`, modify this expression instance in-place.
2796            opts: other options to use to parse the input expressions.
2797
2798        Returns:
2799            The modified Select expression.
2800        """
2801        return _apply_list_builder(
2802            *expressions,
2803            instance=self,
2804            arg="laterals",
2805            append=append,
2806            into=Lateral,
2807            prefix="LATERAL VIEW",
2808            dialect=dialect,
2809            copy=copy,
2810            **opts,
2811        )

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, List[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:
2813    def join(
2814        self,
2815        expression: ExpOrStr,
2816        on: t.Optional[ExpOrStr] = None,
2817        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2818        append: bool = True,
2819        join_type: t.Optional[str] = None,
2820        join_alias: t.Optional[Identifier | str] = None,
2821        dialect: DialectType = None,
2822        copy: bool = True,
2823        **opts,
2824    ) -> Select:
2825        """
2826        Append to or set the JOIN expressions.
2827
2828        Example:
2829            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2830            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2831
2832            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2833            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2834
2835            Use `join_type` to change the type of join:
2836
2837            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2838            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2839
2840        Args:
2841            expression: the SQL code string to parse.
2842                If an `Expression` instance is passed, it will be used as-is.
2843            on: optionally specify the join "on" criteria as a SQL string.
2844                If an `Expression` instance is passed, it will be used as-is.
2845            using: optionally specify the join "using" criteria as a SQL string.
2846                If an `Expression` instance is passed, it will be used as-is.
2847            append: if `True`, add to any existing expressions.
2848                Otherwise, this resets the expressions.
2849            join_type: if set, alter the parsed join type.
2850            join_alias: an optional alias for the joined source.
2851            dialect: the dialect used to parse the input expressions.
2852            copy: if `False`, modify this expression instance in-place.
2853            opts: other options to use to parse the input expressions.
2854
2855        Returns:
2856            Select: the modified expression.
2857        """
2858        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2859
2860        try:
2861            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2862        except ParseError:
2863            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2864
2865        join = expression if isinstance(expression, Join) else Join(this=expression)
2866
2867        if isinstance(join.this, Select):
2868            join.this.replace(join.this.subquery())
2869
2870        if join_type:
2871            method: t.Optional[Token]
2872            side: t.Optional[Token]
2873            kind: t.Optional[Token]
2874
2875            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2876
2877            if method:
2878                join.set("method", method.text)
2879            if side:
2880                join.set("side", side.text)
2881            if kind:
2882                join.set("kind", kind.text)
2883
2884        if on:
2885            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2886            join.set("on", on)
2887
2888        if using:
2889            join = _apply_list_builder(
2890                *ensure_list(using),
2891                instance=join,
2892                arg="using",
2893                append=append,
2894                copy=copy,
2895                **opts,
2896            )
2897
2898        if join_alias:
2899            join.set("this", alias_(join.this, join_alias, table=True))
2900
2901        return _apply_list_builder(
2902            join,
2903            instance=self,
2904            arg="joins",
2905            append=append,
2906            copy=copy,
2907            **opts,
2908        )

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:
2910    def where(
2911        self,
2912        *expressions: t.Optional[ExpOrStr],
2913        append: bool = True,
2914        dialect: DialectType = None,
2915        copy: bool = True,
2916        **opts,
2917    ) -> Select:
2918        """
2919        Append to or set the WHERE expressions.
2920
2921        Example:
2922            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2923            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2924
2925        Args:
2926            *expressions: the SQL code strings to parse.
2927                If an `Expression` instance is passed, it will be used as-is.
2928                Multiple expressions are combined with an AND operator.
2929            append: if `True`, AND the new expressions to any existing expression.
2930                Otherwise, this resets the expression.
2931            dialect: the dialect used to parse the input expressions.
2932            copy: if `False`, modify this expression instance in-place.
2933            opts: other options to use to parse the input expressions.
2934
2935        Returns:
2936            Select: the modified expression.
2937        """
2938        return _apply_conjunction_builder(
2939            *expressions,
2940            instance=self,
2941            arg="where",
2942            append=append,
2943            into=Where,
2944            dialect=dialect,
2945            copy=copy,
2946            **opts,
2947        )

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:
2949    def having(
2950        self,
2951        *expressions: t.Optional[ExpOrStr],
2952        append: bool = True,
2953        dialect: DialectType = None,
2954        copy: bool = True,
2955        **opts,
2956    ) -> Select:
2957        """
2958        Append to or set the HAVING expressions.
2959
2960        Example:
2961            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2962            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2963
2964        Args:
2965            *expressions: the SQL code strings to parse.
2966                If an `Expression` instance is passed, it will be used as-is.
2967                Multiple expressions are combined with an AND operator.
2968            append: if `True`, AND the new expressions to any existing expression.
2969                Otherwise, this resets the expression.
2970            dialect: the dialect used to parse the input expressions.
2971            copy: if `False`, modify this expression instance in-place.
2972            opts: other options to use to parse the input expressions.
2973
2974        Returns:
2975            The modified Select expression.
2976        """
2977        return _apply_conjunction_builder(
2978            *expressions,
2979            instance=self,
2980            arg="having",
2981            append=append,
2982            into=Having,
2983            dialect=dialect,
2984            copy=copy,
2985            **opts,
2986        )

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:
2988    def window(
2989        self,
2990        *expressions: t.Optional[ExpOrStr],
2991        append: bool = True,
2992        dialect: DialectType = None,
2993        copy: bool = True,
2994        **opts,
2995    ) -> Select:
2996        return _apply_list_builder(
2997            *expressions,
2998            instance=self,
2999            arg="windows",
3000            append=append,
3001            into=Window,
3002            dialect=dialect,
3003            copy=copy,
3004            **opts,
3005        )
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:
3007    def qualify(
3008        self,
3009        *expressions: t.Optional[ExpOrStr],
3010        append: bool = True,
3011        dialect: DialectType = None,
3012        copy: bool = True,
3013        **opts,
3014    ) -> Select:
3015        return _apply_conjunction_builder(
3016            *expressions,
3017            instance=self,
3018            arg="qualify",
3019            append=append,
3020            into=Qualify,
3021            dialect=dialect,
3022            copy=copy,
3023            **opts,
3024        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3026    def distinct(
3027        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3028    ) -> Select:
3029        """
3030        Set the OFFSET expression.
3031
3032        Example:
3033            >>> Select().from_("tbl").select("x").distinct().sql()
3034            'SELECT DISTINCT x FROM tbl'
3035
3036        Args:
3037            ons: the expressions to distinct on
3038            distinct: whether the Select should be distinct
3039            copy: if `False`, modify this expression instance in-place.
3040
3041        Returns:
3042            Select: the modified expression.
3043        """
3044        instance = _maybe_copy(self, copy)
3045        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3046        instance.set("distinct", Distinct(on=on) if distinct else None)
3047        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:
3049    def ctas(
3050        self,
3051        table: ExpOrStr,
3052        properties: t.Optional[t.Dict] = None,
3053        dialect: DialectType = None,
3054        copy: bool = True,
3055        **opts,
3056    ) -> Create:
3057        """
3058        Convert this expression to a CREATE TABLE AS statement.
3059
3060        Example:
3061            >>> Select().select("*").from_("tbl").ctas("x").sql()
3062            'CREATE TABLE x AS SELECT * FROM tbl'
3063
3064        Args:
3065            table: the SQL code string to parse as the table name.
3066                If another `Expression` instance is passed, it will be used as-is.
3067            properties: an optional mapping of table properties
3068            dialect: the dialect used to parse the input table.
3069            copy: if `False`, modify this expression instance in-place.
3070            opts: other options to use to parse the input table.
3071
3072        Returns:
3073            The new Create expression.
3074        """
3075        instance = _maybe_copy(self, copy)
3076        table_expression = maybe_parse(
3077            table,
3078            into=Table,
3079            dialect=dialect,
3080            **opts,
3081        )
3082        properties_expression = None
3083        if properties:
3084            properties_expression = Properties.from_dict(properties)
3085
3086        return Create(
3087            this=table_expression,
3088            kind="table",
3089            expression=instance,
3090            properties=properties_expression,
3091        )

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:
3093    def lock(self, update: bool = True, copy: bool = True) -> Select:
3094        """
3095        Set the locking read mode for this expression.
3096
3097        Examples:
3098            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3099            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3100
3101            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3102            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3103
3104        Args:
3105            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3106            copy: if `False`, modify this expression instance in-place.
3107
3108        Returns:
3109            The modified expression.
3110        """
3111        inst = _maybe_copy(self, copy)
3112        inst.set("locks", [Lock(update=update)])
3113
3114        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:
3116    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3117        """
3118        Set hints for this expression.
3119
3120        Examples:
3121            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3122            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3123
3124        Args:
3125            hints: The SQL code strings to parse as the hints.
3126                If an `Expression` instance is passed, it will be used as-is.
3127            dialect: The dialect used to parse the hints.
3128            copy: If `False`, modify this expression instance in-place.
3129
3130        Returns:
3131            The modified expression.
3132        """
3133        inst = _maybe_copy(self, copy)
3134        inst.set(
3135            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3136        )
3137
3138        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):
3153class Subquery(DerivedTable, Unionable):
3154    arg_types = {
3155        "this": True,
3156        "alias": False,
3157        "with": False,
3158        **QUERY_MODIFIERS,
3159    }
3160
3161    def unnest(self):
3162        """
3163        Returns the first non subquery.
3164        """
3165        expression = self
3166        while isinstance(expression, Subquery):
3167            expression = expression.this
3168        return expression
3169
3170    @property
3171    def is_star(self) -> bool:
3172        return self.this.is_star
3173
3174    @property
3175    def output_name(self) -> str:
3176        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):
3161    def unnest(self):
3162        """
3163        Returns the first non subquery.
3164        """
3165        expression = self
3166        while isinstance(expression, Subquery):
3167            expression = expression.this
3168        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):
3179class TableSample(Expression):
3180    arg_types = {
3181        "this": False,
3182        "method": False,
3183        "bucket_numerator": False,
3184        "bucket_denominator": False,
3185        "bucket_field": False,
3186        "percent": False,
3187        "rows": False,
3188        "size": False,
3189        "seed": False,
3190        "kind": False,
3191    }
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):
3194class Tag(Expression):
3195    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3196
3197    arg_types = {
3198        "this": False,
3199        "prefix": False,
3200        "postfix": False,
3201    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3206class Pivot(Expression):
3207    arg_types = {
3208        "this": False,
3209        "alias": False,
3210        "expressions": True,
3211        "field": False,
3212        "unpivot": False,
3213        "using": False,
3214        "group": False,
3215        "columns": False,
3216    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3219class Window(Expression):
3220    arg_types = {
3221        "this": True,
3222        "partition_by": False,
3223        "order": False,
3224        "spec": False,
3225        "alias": False,
3226        "over": False,
3227        "first": False,
3228    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3231class WindowSpec(Expression):
3232    arg_types = {
3233        "kind": False,
3234        "start": False,
3235        "start_side": False,
3236        "end": False,
3237        "end_side": False,
3238    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3241class Where(Expression):
3242    pass
key = 'where'
class Star(Expression):
3245class Star(Expression):
3246    arg_types = {"except": False, "replace": False}
3247
3248    @property
3249    def name(self) -> str:
3250        return "*"
3251
3252    @property
3253    def output_name(self) -> str:
3254        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):
3257class Parameter(Condition):
3258    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3261class SessionParameter(Condition):
3262    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3265class Placeholder(Condition):
3266    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3269class Null(Condition):
3270    arg_types: t.Dict[str, t.Any] = {}
3271
3272    @property
3273    def name(self) -> str:
3274        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3277class Boolean(Condition):
3278    pass
key = 'boolean'
class DataTypeSize(Expression):
3281class DataTypeSize(Expression):
3282    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3285class DataType(Expression):
3286    arg_types = {
3287        "this": True,
3288        "expressions": False,
3289        "nested": False,
3290        "values": False,
3291        "prefix": False,
3292    }
3293
3294    class Type(AutoName):
3295        ARRAY = auto()
3296        BIGDECIMAL = auto()
3297        BIGINT = auto()
3298        BIGSERIAL = auto()
3299        BINARY = auto()
3300        BIT = auto()
3301        BOOLEAN = auto()
3302        CHAR = auto()
3303        DATE = auto()
3304        DATETIME = auto()
3305        DATETIME64 = auto()
3306        ENUM = auto()
3307        INT4RANGE = auto()
3308        INT4MULTIRANGE = auto()
3309        INT8RANGE = auto()
3310        INT8MULTIRANGE = auto()
3311        NUMRANGE = auto()
3312        NUMMULTIRANGE = auto()
3313        TSRANGE = auto()
3314        TSMULTIRANGE = auto()
3315        TSTZRANGE = auto()
3316        TSTZMULTIRANGE = auto()
3317        DATERANGE = auto()
3318        DATEMULTIRANGE = auto()
3319        DECIMAL = auto()
3320        DOUBLE = auto()
3321        FLOAT = auto()
3322        GEOGRAPHY = auto()
3323        GEOMETRY = auto()
3324        HLLSKETCH = auto()
3325        HSTORE = auto()
3326        IMAGE = auto()
3327        INET = auto()
3328        INT = auto()
3329        INT128 = auto()
3330        INT256 = auto()
3331        INTERVAL = auto()
3332        JSON = auto()
3333        JSONB = auto()
3334        LONGBLOB = auto()
3335        LONGTEXT = auto()
3336        MAP = auto()
3337        MEDIUMBLOB = auto()
3338        MEDIUMTEXT = auto()
3339        MONEY = auto()
3340        NCHAR = auto()
3341        NULL = auto()
3342        NULLABLE = auto()
3343        NVARCHAR = auto()
3344        OBJECT = auto()
3345        ROWVERSION = auto()
3346        SERIAL = auto()
3347        SET = auto()
3348        SMALLINT = auto()
3349        SMALLMONEY = auto()
3350        SMALLSERIAL = auto()
3351        STRUCT = auto()
3352        SUPER = auto()
3353        TEXT = auto()
3354        TIME = auto()
3355        TIMESTAMP = auto()
3356        TIMESTAMPTZ = auto()
3357        TIMESTAMPLTZ = auto()
3358        TINYINT = auto()
3359        UBIGINT = auto()
3360        UINT = auto()
3361        USMALLINT = auto()
3362        UTINYINT = auto()
3363        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3364        UINT128 = auto()
3365        UINT256 = auto()
3366        UNIQUEIDENTIFIER = auto()
3367        USERDEFINED = "USER-DEFINED"
3368        UUID = auto()
3369        VARBINARY = auto()
3370        VARCHAR = auto()
3371        VARIANT = auto()
3372        XML = auto()
3373
3374    TEXT_TYPES = {
3375        Type.CHAR,
3376        Type.NCHAR,
3377        Type.VARCHAR,
3378        Type.NVARCHAR,
3379        Type.TEXT,
3380    }
3381
3382    INTEGER_TYPES = {
3383        Type.INT,
3384        Type.TINYINT,
3385        Type.SMALLINT,
3386        Type.BIGINT,
3387        Type.INT128,
3388        Type.INT256,
3389    }
3390
3391    FLOAT_TYPES = {
3392        Type.FLOAT,
3393        Type.DOUBLE,
3394    }
3395
3396    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3397
3398    TEMPORAL_TYPES = {
3399        Type.TIME,
3400        Type.TIMESTAMP,
3401        Type.TIMESTAMPTZ,
3402        Type.TIMESTAMPLTZ,
3403        Type.DATE,
3404        Type.DATETIME,
3405        Type.DATETIME64,
3406    }
3407
3408    META_TYPES = {"UNKNOWN", "NULL"}
3409
3410    @classmethod
3411    def build(
3412        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3413    ) -> DataType:
3414        from sqlglot import parse_one
3415
3416        if isinstance(dtype, str):
3417            upper = dtype.upper()
3418            if upper in DataType.META_TYPES:
3419                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3420            else:
3421                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3422
3423            if data_type_exp is None:
3424                raise ValueError(f"Unparsable data type value: {dtype}")
3425        elif isinstance(dtype, DataType.Type):
3426            data_type_exp = DataType(this=dtype)
3427        elif isinstance(dtype, DataType):
3428            return dtype
3429        else:
3430            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3431
3432        return DataType(**{**data_type_exp.args, **kwargs})
3433
3434    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3435        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.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.TEXT: 'TEXT'>}
INTEGER_TYPES = {<Type.BIGINT: 'BIGINT'>, <Type.INT: 'INT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT256: 'INT256'>, <Type.INT128: 'INT128'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.TINYINT: 'TINYINT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT: 'INT'>, <Type.INT256: 'INT256'>, <Type.INT128: 'INT128'>, <Type.SMALLINT: 'SMALLINT'>}
TEMPORAL_TYPES = {<Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.TIME: 'TIME'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.DATETIME64: 'DATETIME64'>, <Type.DATETIME: 'DATETIME'>, <Type.DATE: 'DATE'>}
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:
3410    @classmethod
3411    def build(
3412        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3413    ) -> DataType:
3414        from sqlglot import parse_one
3415
3416        if isinstance(dtype, str):
3417            upper = dtype.upper()
3418            if upper in DataType.META_TYPES:
3419                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3420            else:
3421                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3422
3423            if data_type_exp is None:
3424                raise ValueError(f"Unparsable data type value: {dtype}")
3425        elif isinstance(dtype, DataType.Type):
3426            data_type_exp = DataType(this=dtype)
3427        elif isinstance(dtype, DataType):
3428            return dtype
3429        else:
3430            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3431
3432        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3434    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3435        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3294    class Type(AutoName):
3295        ARRAY = auto()
3296        BIGDECIMAL = auto()
3297        BIGINT = auto()
3298        BIGSERIAL = auto()
3299        BINARY = auto()
3300        BIT = auto()
3301        BOOLEAN = auto()
3302        CHAR = auto()
3303        DATE = auto()
3304        DATETIME = auto()
3305        DATETIME64 = auto()
3306        ENUM = auto()
3307        INT4RANGE = auto()
3308        INT4MULTIRANGE = auto()
3309        INT8RANGE = auto()
3310        INT8MULTIRANGE = auto()
3311        NUMRANGE = auto()
3312        NUMMULTIRANGE = auto()
3313        TSRANGE = auto()
3314        TSMULTIRANGE = auto()
3315        TSTZRANGE = auto()
3316        TSTZMULTIRANGE = auto()
3317        DATERANGE = auto()
3318        DATEMULTIRANGE = auto()
3319        DECIMAL = auto()
3320        DOUBLE = auto()
3321        FLOAT = auto()
3322        GEOGRAPHY = auto()
3323        GEOMETRY = auto()
3324        HLLSKETCH = auto()
3325        HSTORE = auto()
3326        IMAGE = auto()
3327        INET = auto()
3328        INT = auto()
3329        INT128 = auto()
3330        INT256 = auto()
3331        INTERVAL = auto()
3332        JSON = auto()
3333        JSONB = auto()
3334        LONGBLOB = auto()
3335        LONGTEXT = auto()
3336        MAP = auto()
3337        MEDIUMBLOB = auto()
3338        MEDIUMTEXT = auto()
3339        MONEY = auto()
3340        NCHAR = auto()
3341        NULL = auto()
3342        NULLABLE = auto()
3343        NVARCHAR = auto()
3344        OBJECT = auto()
3345        ROWVERSION = auto()
3346        SERIAL = auto()
3347        SET = auto()
3348        SMALLINT = auto()
3349        SMALLMONEY = auto()
3350        SMALLSERIAL = auto()
3351        STRUCT = auto()
3352        SUPER = auto()
3353        TEXT = auto()
3354        TIME = auto()
3355        TIMESTAMP = auto()
3356        TIMESTAMPTZ = auto()
3357        TIMESTAMPLTZ = auto()
3358        TINYINT = auto()
3359        UBIGINT = auto()
3360        UINT = auto()
3361        USMALLINT = auto()
3362        UTINYINT = auto()
3363        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3364        UINT128 = auto()
3365        UINT256 = auto()
3366        UNIQUEIDENTIFIER = auto()
3367        USERDEFINED = "USER-DEFINED"
3368        UUID = auto()
3369        VARBINARY = auto()
3370        VARCHAR = auto()
3371        VARIANT = auto()
3372        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'>
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):
3439class PseudoType(Expression):
3440    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3444class SubqueryPredicate(Predicate):
3445    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3448class All(SubqueryPredicate):
3449    pass
key = 'all'
class Any(SubqueryPredicate):
3452class Any(SubqueryPredicate):
3453    pass
key = 'any'
class Exists(SubqueryPredicate):
3456class Exists(SubqueryPredicate):
3457    pass
key = 'exists'
class Command(Expression):
3462class Command(Expression):
3463    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3466class Transaction(Expression):
3467    arg_types = {"this": False, "modes": False}
arg_types = {'this': False, 'modes': False}
key = 'transaction'
class Commit(Expression):
3470class Commit(Expression):
3471    arg_types = {"chain": False}
arg_types = {'chain': False}
key = 'commit'
class Rollback(Expression):
3474class Rollback(Expression):
3475    arg_types = {"savepoint": False}
arg_types = {'savepoint': False}
key = 'rollback'
class AlterTable(Expression):
3478class AlterTable(Expression):
3479    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3482class AddConstraint(Expression):
3483    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3486class DropPartition(Expression):
3487    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3491class Binary(Condition):
3492    arg_types = {"this": True, "expression": True}
3493
3494    @property
3495    def left(self):
3496        return self.this
3497
3498    @property
3499    def right(self):
3500        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3503class Add(Binary):
3504    pass
key = 'add'
class Connector(Binary):
3507class Connector(Binary):
3508    pass
key = 'connector'
class And(Connector):
3511class And(Connector):
3512    pass
key = 'and'
class Or(Connector):
3515class Or(Connector):
3516    pass
key = 'or'
class BitwiseAnd(Binary):
3519class BitwiseAnd(Binary):
3520    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3523class BitwiseLeftShift(Binary):
3524    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3527class BitwiseOr(Binary):
3528    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3531class BitwiseRightShift(Binary):
3532    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3535class BitwiseXor(Binary):
3536    pass
key = 'bitwisexor'
class Div(Binary):
3539class Div(Binary):
3540    pass
key = 'div'
class Overlaps(Binary):
3543class Overlaps(Binary):
3544    pass
key = 'overlaps'
class Dot(Binary):
3547class Dot(Binary):
3548    @property
3549    def name(self) -> str:
3550        return self.expression.name
3551
3552    @property
3553    def output_name(self) -> str:
3554        return self.name
3555
3556    @classmethod
3557    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3558        """Build a Dot object with a sequence of expressions."""
3559        if len(expressions) < 2:
3560            raise ValueError(f"Dot requires >= 2 expressions.")
3561
3562        a, b, *expressions = expressions
3563        dot = Dot(this=a, expression=b)
3564
3565        for expression in expressions:
3566            dot = Dot(this=dot, expression=expression)
3567
3568        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:
3556    @classmethod
3557    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3558        """Build a Dot object with a sequence of expressions."""
3559        if len(expressions) < 2:
3560            raise ValueError(f"Dot requires >= 2 expressions.")
3561
3562        a, b, *expressions = expressions
3563        dot = Dot(this=a, expression=b)
3564
3565        for expression in expressions:
3566            dot = Dot(this=dot, expression=expression)
3567
3568        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3571class DPipe(Binary):
3572    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3575class SafeDPipe(DPipe):
3576    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3579class EQ(Binary, Predicate):
3580    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3583class NullSafeEQ(Binary, Predicate):
3584    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3587class NullSafeNEQ(Binary, Predicate):
3588    pass
key = 'nullsafeneq'
class Distance(Binary):
3591class Distance(Binary):
3592    pass
key = 'distance'
class Escape(Binary):
3595class Escape(Binary):
3596    pass
key = 'escape'
class Glob(Binary, Predicate):
3599class Glob(Binary, Predicate):
3600    pass
key = 'glob'
class GT(Binary, Predicate):
3603class GT(Binary, Predicate):
3604    pass
key = 'gt'
class GTE(Binary, Predicate):
3607class GTE(Binary, Predicate):
3608    pass
key = 'gte'
class ILike(Binary, Predicate):
3611class ILike(Binary, Predicate):
3612    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3615class ILikeAny(Binary, Predicate):
3616    pass
key = 'ilikeany'
class IntDiv(Binary):
3619class IntDiv(Binary):
3620    pass
key = 'intdiv'
class Is(Binary, Predicate):
3623class Is(Binary, Predicate):
3624    pass
key = 'is'
class Kwarg(Binary):
3627class Kwarg(Binary):
3628    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3631class Like(Binary, Predicate):
3632    pass
key = 'like'
class LikeAny(Binary, Predicate):
3635class LikeAny(Binary, Predicate):
3636    pass
key = 'likeany'
class LT(Binary, Predicate):
3639class LT(Binary, Predicate):
3640    pass
key = 'lt'
class LTE(Binary, Predicate):
3643class LTE(Binary, Predicate):
3644    pass
key = 'lte'
class Mod(Binary):
3647class Mod(Binary):
3648    pass
key = 'mod'
class Mul(Binary):
3651class Mul(Binary):
3652    pass
key = 'mul'
class NEQ(Binary, Predicate):
3655class NEQ(Binary, Predicate):
3656    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3659class SimilarTo(Binary, Predicate):
3660    pass
key = 'similarto'
class Slice(Binary):
3663class Slice(Binary):
3664    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3667class Sub(Binary):
3668    pass
key = 'sub'
class ArrayOverlaps(Binary):
3671class ArrayOverlaps(Binary):
3672    pass
key = 'arrayoverlaps'
class Unary(Condition):
3677class Unary(Condition):
3678    pass
key = 'unary'
class BitwiseNot(Unary):
3681class BitwiseNot(Unary):
3682    pass
key = 'bitwisenot'
class Not(Unary):
3685class Not(Unary):
3686    pass
key = 'not'
class Paren(Unary):
3689class Paren(Unary):
3690    arg_types = {"this": True, "with": False}
3691
3692    @property
3693    def output_name(self) -> str:
3694        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):
3697class Neg(Unary):
3698    pass
key = 'neg'
class Alias(Expression):
3701class Alias(Expression):
3702    arg_types = {"this": True, "alias": False}
3703
3704    @property
3705    def output_name(self) -> str:
3706        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):
3709class Aliases(Expression):
3710    arg_types = {"this": True, "expressions": True}
3711
3712    @property
3713    def aliases(self):
3714        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3717class AtTimeZone(Expression):
3718    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3721class Between(Predicate):
3722    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3725class Bracket(Condition):
3726    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3729class SafeBracket(Bracket):
3730    """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):
3733class Distinct(Expression):
3734    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3737class In(Predicate):
3738    arg_types = {
3739        "this": True,
3740        "expressions": False,
3741        "query": False,
3742        "unnest": False,
3743        "field": False,
3744        "is_global": False,
3745    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3748class TimeUnit(Expression):
3749    """Automatically converts unit arg into a var."""
3750
3751    arg_types = {"unit": False}
3752
3753    def __init__(self, **args):
3754        unit = args.get("unit")
3755        if isinstance(unit, (Column, Literal)):
3756            args["unit"] = Var(this=unit.name)
3757        elif isinstance(unit, Week):
3758            unit.set("this", Var(this=unit.this.name))
3759
3760        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3753    def __init__(self, **args):
3754        unit = args.get("unit")
3755        if isinstance(unit, (Column, Literal)):
3756            args["unit"] = Var(this=unit.name)
3757        elif isinstance(unit, Week):
3758            unit.set("this", Var(this=unit.this.name))
3759
3760        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3763class Interval(TimeUnit):
3764    arg_types = {"this": False, "unit": False}
3765
3766    @property
3767    def unit(self) -> t.Optional[Var]:
3768        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3771class IgnoreNulls(Expression):
3772    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3775class RespectNulls(Expression):
3776    pass
key = 'respectnulls'
class Func(Condition):
3780class Func(Condition):
3781    """
3782    The base class for all function expressions.
3783
3784    Attributes:
3785        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3786            treated as a variable length argument and the argument's value will be stored as a list.
3787        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3788            for this function expression. These values are used to map this node to a name during parsing
3789            as well as to provide the function's name during SQL string generation. By default the SQL
3790            name is set to the expression's class name transformed to snake case.
3791    """
3792
3793    is_var_len_args = False
3794
3795    @classmethod
3796    def from_arg_list(cls, args):
3797        if cls.is_var_len_args:
3798            all_arg_keys = list(cls.arg_types)
3799            # If this function supports variable length argument treat the last argument as such.
3800            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3801            num_non_var = len(non_var_len_arg_keys)
3802
3803            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3804            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3805        else:
3806            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3807
3808        return cls(**args_dict)
3809
3810    @classmethod
3811    def sql_names(cls):
3812        if cls is Func:
3813            raise NotImplementedError(
3814                "SQL name is only supported by concrete function implementations"
3815            )
3816        if "_sql_names" not in cls.__dict__:
3817            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3818        return cls._sql_names
3819
3820    @classmethod
3821    def sql_name(cls):
3822        return cls.sql_names()[0]
3823
3824    @classmethod
3825    def default_parser_mappings(cls):
3826        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):
3795    @classmethod
3796    def from_arg_list(cls, args):
3797        if cls.is_var_len_args:
3798            all_arg_keys = list(cls.arg_types)
3799            # If this function supports variable length argument treat the last argument as such.
3800            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3801            num_non_var = len(non_var_len_arg_keys)
3802
3803            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3804            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3805        else:
3806            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3807
3808        return cls(**args_dict)
@classmethod
def sql_names(cls):
3810    @classmethod
3811    def sql_names(cls):
3812        if cls is Func:
3813            raise NotImplementedError(
3814                "SQL name is only supported by concrete function implementations"
3815            )
3816        if "_sql_names" not in cls.__dict__:
3817            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3818        return cls._sql_names
@classmethod
def sql_name(cls):
3820    @classmethod
3821    def sql_name(cls):
3822        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3824    @classmethod
3825    def default_parser_mappings(cls):
3826        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3829class AggFunc(Func):
3830    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3833class ParameterizedAgg(AggFunc):
3834    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3837class Abs(Func):
3838    pass
key = 'abs'
class Anonymous(Func):
3841class Anonymous(Func):
3842    arg_types = {"this": True, "expressions": False}
3843    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3848class Hll(AggFunc):
3849    arg_types = {"this": True, "expressions": False}
3850    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3853class ApproxDistinct(AggFunc):
3854    arg_types = {"this": True, "accuracy": False}
3855    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3858class Array(Func):
3859    arg_types = {"expressions": False}
3860    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3864class ToChar(Func):
3865    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3868class GenerateSeries(Func):
3869    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3872class ArrayAgg(AggFunc):
3873    pass
key = 'arrayagg'
class ArrayAll(Func):
3876class ArrayAll(Func):
3877    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3880class ArrayAny(Func):
3881    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3884class ArrayConcat(Func):
3885    arg_types = {"this": True, "expressions": False}
3886    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3889class ArrayContains(Binary, Func):
3890    pass
key = 'arraycontains'
class ArrayContained(Binary):
3893class ArrayContained(Binary):
3894    pass
key = 'arraycontained'
class ArrayFilter(Func):
3897class ArrayFilter(Func):
3898    arg_types = {"this": True, "expression": True}
3899    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3902class ArrayJoin(Func):
3903    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3906class ArraySize(Func):
3907    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3910class ArraySort(Func):
3911    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3914class ArraySum(Func):
3915    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3918class ArrayUnionAgg(AggFunc):
3919    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3922class Avg(AggFunc):
3923    pass
key = 'avg'
class AnyValue(AggFunc):
3926class AnyValue(AggFunc):
3927    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
3930class Case(Func):
3931    arg_types = {"this": False, "ifs": True, "default": False}
3932
3933    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3934        instance = _maybe_copy(self, copy)
3935        instance.append(
3936            "ifs",
3937            If(
3938                this=maybe_parse(condition, copy=copy, **opts),
3939                true=maybe_parse(then, copy=copy, **opts),
3940            ),
3941        )
3942        return instance
3943
3944    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3945        instance = _maybe_copy(self, copy)
3946        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3947        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:
3933    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3934        instance = _maybe_copy(self, copy)
3935        instance.append(
3936            "ifs",
3937            If(
3938                this=maybe_parse(condition, copy=copy, **opts),
3939                true=maybe_parse(then, copy=copy, **opts),
3940            ),
3941        )
3942        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3944    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3945        instance = _maybe_copy(self, copy)
3946        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3947        return instance
key = 'case'
class Cast(Func):
3950class Cast(Func):
3951    arg_types = {"this": True, "to": True, "format": False}
3952
3953    @property
3954    def name(self) -> str:
3955        return self.this.name
3956
3957    @property
3958    def to(self) -> DataType:
3959        return self.args["to"]
3960
3961    @property
3962    def output_name(self) -> str:
3963        return self.name
3964
3965    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3966        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:
3965    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3966        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
3969class CastToStrType(Func):
3970    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
3973class Collate(Binary):
3974    pass
key = 'collate'
class TryCast(Cast):
3977class TryCast(Cast):
3978    pass
key = 'trycast'
class Ceil(Func):
3981class Ceil(Func):
3982    arg_types = {"this": True, "decimals": False}
3983    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
3986class Coalesce(Func):
3987    arg_types = {"this": True, "expressions": False}
3988    is_var_len_args = True
3989    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
3992class Concat(Func):
3993    arg_types = {"expressions": True}
3994    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
3997class SafeConcat(Concat):
3998    pass
key = 'safeconcat'
class ConcatWs(Concat):
4001class ConcatWs(Concat):
4002    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4005class Count(AggFunc):
4006    arg_types = {"this": False, "expressions": False}
4007    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4010class CountIf(AggFunc):
4011    pass
key = 'countif'
class CurrentDate(Func):
4014class CurrentDate(Func):
4015    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4018class CurrentDatetime(Func):
4019    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4022class CurrentTime(Func):
4023    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4026class CurrentTimestamp(Func):
4027    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4030class CurrentUser(Func):
4031    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4034class DateAdd(Func, TimeUnit):
4035    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4038class DateSub(Func, TimeUnit):
4039    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4042class DateDiff(Func, TimeUnit):
4043    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4044    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4047class DateTrunc(Func):
4048    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4051class DatetimeAdd(Func, TimeUnit):
4052    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4055class DatetimeSub(Func, TimeUnit):
4056    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4059class DatetimeDiff(Func, TimeUnit):
4060    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4063class DatetimeTrunc(Func, TimeUnit):
4064    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4067class DayOfWeek(Func):
4068    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4071class DayOfMonth(Func):
4072    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4075class DayOfYear(Func):
4076    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4079class WeekOfYear(Func):
4080    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class LastDateOfMonth(Func):
4083class LastDateOfMonth(Func):
4084    pass
key = 'lastdateofmonth'
class Extract(Func):
4087class Extract(Func):
4088    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4091class TimestampAdd(Func, TimeUnit):
4092    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4095class TimestampSub(Func, TimeUnit):
4096    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4099class TimestampDiff(Func, TimeUnit):
4100    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4103class TimestampTrunc(Func, TimeUnit):
4104    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4107class TimeAdd(Func, TimeUnit):
4108    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4111class TimeSub(Func, TimeUnit):
4112    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4115class TimeDiff(Func, TimeUnit):
4116    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4119class TimeTrunc(Func, TimeUnit):
4120    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4123class DateFromParts(Func):
4124    _sql_names = ["DATEFROMPARTS"]
4125    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4128class DateStrToDate(Func):
4129    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4132class DateToDateStr(Func):
4133    pass
key = 'datetodatestr'
class DateToDi(Func):
4136class DateToDi(Func):
4137    pass
key = 'datetodi'
class Date(Func):
4140class Date(Func):
4141    arg_types = {"expressions": True}
4142    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'date'
class Day(Func):
4145class Day(Func):
4146    pass
key = 'day'
class Decode(Func):
4149class Decode(Func):
4150    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4153class DiToDate(Func):
4154    pass
key = 'ditodate'
class Encode(Func):
4157class Encode(Func):
4158    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4161class Exp(Func):
4162    pass
key = 'exp'
class Explode(Func):
4165class Explode(Func):
4166    pass
key = 'explode'
class Floor(Func):
4169class Floor(Func):
4170    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4173class FromBase64(Func):
4174    pass
key = 'frombase64'
class ToBase64(Func):
4177class ToBase64(Func):
4178    pass
key = 'tobase64'
class Greatest(Func):
4181class Greatest(Func):
4182    arg_types = {"this": True, "expressions": False}
4183    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4186class GroupConcat(Func):
4187    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4190class Hex(Func):
4191    pass
key = 'hex'
class If(Func):
4194class If(Func):
4195    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4198class Initcap(Func):
4199    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4202class JSONKeyValue(Expression):
4203    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4206class JSONObject(Func):
4207    arg_types = {
4208        "expressions": False,
4209        "null_handling": False,
4210        "unique_keys": False,
4211        "return_type": False,
4212        "format_json": False,
4213        "encoding": False,
4214    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4217class OpenJSONColumnDef(Expression):
4218    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):
4221class OpenJSON(Func):
4222    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4225class JSONBContains(Binary):
4226    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4229class JSONExtract(Binary, Func):
4230    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4233class JSONExtractScalar(JSONExtract):
4234    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4237class JSONBExtract(JSONExtract):
4238    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4241class JSONBExtractScalar(JSONExtract):
4242    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4245class JSONFormat(Func):
4246    arg_types = {"this": False, "options": False}
4247    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class Least(Func):
4250class Least(Func):
4251    arg_types = {"expressions": False}
4252    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4255class Left(Func):
4256    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4263class Length(Func):
4264    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4267class Levenshtein(Func):
4268    arg_types = {
4269        "this": True,
4270        "expression": False,
4271        "ins_cost": False,
4272        "del_cost": False,
4273        "sub_cost": False,
4274    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4277class Ln(Func):
4278    pass
key = 'ln'
class Log(Func):
4281class Log(Func):
4282    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4285class Log2(Func):
4286    pass
key = 'log2'
class Log10(Func):
4289class Log10(Func):
4290    pass
key = 'log10'
class LogicalOr(AggFunc):
4293class LogicalOr(AggFunc):
4294    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4297class LogicalAnd(AggFunc):
4298    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4301class Lower(Func):
4302    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4305class Map(Func):
4306    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4309class MapFromEntries(Func):
4310    pass
key = 'mapfromentries'
class StarMap(Func):
4313class StarMap(Func):
4314    pass
key = 'starmap'
class VarMap(Func):
4317class VarMap(Func):
4318    arg_types = {"keys": True, "values": True}
4319    is_var_len_args = True
4320
4321    @property
4322    def keys(self) -> t.List[Expression]:
4323        return self.args["keys"].expressions
4324
4325    @property
4326    def values(self) -> t.List[Expression]:
4327        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4331class MatchAgainst(Func):
4332    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4335class Max(AggFunc):
4336    arg_types = {"this": True, "expressions": False}
4337    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4340class MD5(Func):
4341    _sql_names = ["MD5"]
key = 'md5'
class Min(AggFunc):
4344class Min(AggFunc):
4345    arg_types = {"this": True, "expressions": False}
4346    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4349class Month(Func):
4350    pass
key = 'month'
class Nvl2(Func):
4353class Nvl2(Func):
4354    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4357class Posexplode(Func):
4358    pass
key = 'posexplode'
class Pow(Binary, Func):
4361class Pow(Binary, Func):
4362    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4365class PercentileCont(AggFunc):
4366    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4369class PercentileDisc(AggFunc):
4370    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4373class Quantile(AggFunc):
4374    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4377class ApproxQuantile(Quantile):
4378    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):
4381class RangeN(Func):
4382    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4385class ReadCSV(Func):
4386    _sql_names = ["READ_CSV"]
4387    is_var_len_args = True
4388    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4391class Reduce(Func):
4392    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):
4395class RegexpExtract(Func):
4396    arg_types = {
4397        "this": True,
4398        "expression": True,
4399        "position": False,
4400        "occurrence": False,
4401        "group": False,
4402    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'group': False}
key = 'regexpextract'
class RegexpLike(Func):
4405class RegexpLike(Func):
4406    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4409class RegexpILike(Func):
4410    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4415class RegexpSplit(Func):
4416    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4419class Repeat(Func):
4420    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4423class Round(Func):
4424    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4427class RowNumber(Func):
4428    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4431class SafeDivide(Func):
4432    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4435class SetAgg(AggFunc):
4436    pass
key = 'setagg'
class SHA(Func):
4439class SHA(Func):
4440    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4443class SHA2(Func):
4444    _sql_names = ["SHA2"]
4445    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4448class SortArray(Func):
4449    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4452class Split(Func):
4453    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4458class Substring(Func):
4459    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4462class StandardHash(Func):
4463    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4466class StrPosition(Func):
4467    arg_types = {
4468        "this": True,
4469        "substr": True,
4470        "position": False,
4471        "instance": False,
4472    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4475class StrToDate(Func):
4476    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4479class StrToTime(Func):
4480    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtotime'
class StrToUnix(Func):
4485class StrToUnix(Func):
4486    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4489class NumberToStr(Func):
4490    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4493class FromBase(Func):
4494    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4497class Struct(Func):
4498    arg_types = {"expressions": True}
4499    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4502class StructExtract(Func):
4503    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4506class Sum(AggFunc):
4507    pass
key = 'sum'
class Sqrt(Func):
4510class Sqrt(Func):
4511    pass
key = 'sqrt'
class Stddev(AggFunc):
4514class Stddev(AggFunc):
4515    pass
key = 'stddev'
class StddevPop(AggFunc):
4518class StddevPop(AggFunc):
4519    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4522class StddevSamp(AggFunc):
4523    pass
key = 'stddevsamp'
class TimeToStr(Func):
4526class TimeToStr(Func):
4527    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4530class TimeToTimeStr(Func):
4531    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4534class TimeToUnix(Func):
4535    pass
key = 'timetounix'
class TimeStrToDate(Func):
4538class TimeStrToDate(Func):
4539    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4542class TimeStrToTime(Func):
4543    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4546class TimeStrToUnix(Func):
4547    pass
key = 'timestrtounix'
class Trim(Func):
4550class Trim(Func):
4551    arg_types = {
4552        "this": True,
4553        "expression": False,
4554        "position": False,
4555        "collation": False,
4556    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4559class TsOrDsAdd(Func, TimeUnit):
4560    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4563class TsOrDsToDateStr(Func):
4564    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4567class TsOrDsToDate(Func):
4568    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4571class TsOrDiToDi(Func):
4572    pass
key = 'tsorditodi'
class Unhex(Func):
4575class Unhex(Func):
4576    pass
key = 'unhex'
class UnixToStr(Func):
4579class UnixToStr(Func):
4580    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4585class UnixToTime(Func):
4586    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4587
4588    SECONDS = Literal.string("seconds")
4589    MILLIS = Literal.string("millis")
4590    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):
4593class UnixToTimeStr(Func):
4594    pass
key = 'unixtotimestr'
class Upper(Func):
4597class Upper(Func):
4598    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4601class Variance(AggFunc):
4602    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4605class VariancePop(AggFunc):
4606    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4609class Week(Func):
4610    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4613class XMLTable(Func):
4614    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):
4617class Year(Func):
4618    pass
key = 'year'
class Use(Expression):
4621class Use(Expression):
4622    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4625class Merge(Expression):
4626    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):
4629class When(Func):
4630    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):
4635class NextValueFor(Func):
4636    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.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.Map'>, <class 'sqlglot.expressions.MapFromEntries'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <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.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.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.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.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:
4673def maybe_parse(
4674    sql_or_expression: ExpOrStr,
4675    *,
4676    into: t.Optional[IntoType] = None,
4677    dialect: DialectType = None,
4678    prefix: t.Optional[str] = None,
4679    copy: bool = False,
4680    **opts,
4681) -> Expression:
4682    """Gracefully handle a possible string or expression.
4683
4684    Example:
4685        >>> maybe_parse("1")
4686        (LITERAL this: 1, is_string: False)
4687        >>> maybe_parse(to_identifier("x"))
4688        (IDENTIFIER this: x, quoted: False)
4689
4690    Args:
4691        sql_or_expression: the SQL code string or an expression
4692        into: the SQLGlot Expression to parse into
4693        dialect: the dialect used to parse the input expressions (in the case that an
4694            input expression is a SQL string).
4695        prefix: a string to prefix the sql with before it gets parsed
4696            (automatically includes a space)
4697        copy: whether or not to copy the expression.
4698        **opts: other options to use to parse the input expressions (again, in the case
4699            that an input expression is a SQL string).
4700
4701    Returns:
4702        Expression: the parsed or given expression.
4703    """
4704    if isinstance(sql_or_expression, Expression):
4705        if copy:
4706            return sql_or_expression.copy()
4707        return sql_or_expression
4708
4709    if sql_or_expression is None:
4710        raise ParseError(f"SQL cannot be None")
4711
4712    import sqlglot
4713
4714    sql = str(sql_or_expression)
4715    if prefix:
4716        sql = f"{prefix} {sql}"
4717
4718    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 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:
4902def union(
4903    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4904) -> Union:
4905    """
4906    Initializes a syntax tree from one UNION expression.
4907
4908    Example:
4909        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4910        'SELECT * FROM foo UNION SELECT * FROM bla'
4911
4912    Args:
4913        left: the SQL code string corresponding to the left-hand side.
4914            If an `Expression` instance is passed, it will be used as-is.
4915        right: the SQL code string corresponding to the right-hand side.
4916            If an `Expression` instance is passed, it will be used as-is.
4917        distinct: set the DISTINCT flag if and only if this is true.
4918        dialect: the dialect used to parse the input expression.
4919        opts: other options to use to parse the input expressions.
4920
4921    Returns:
4922        The new Union instance.
4923    """
4924    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4925    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4926
4927    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:
4930def intersect(
4931    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4932) -> Intersect:
4933    """
4934    Initializes a syntax tree from one INTERSECT expression.
4935
4936    Example:
4937        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4938        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4939
4940    Args:
4941        left: the SQL code string corresponding to the left-hand side.
4942            If an `Expression` instance is passed, it will be used as-is.
4943        right: the SQL code string corresponding to the right-hand side.
4944            If an `Expression` instance is passed, it will be used as-is.
4945        distinct: set the DISTINCT flag if and only if this is true.
4946        dialect: the dialect used to parse the input expression.
4947        opts: other options to use to parse the input expressions.
4948
4949    Returns:
4950        The new Intersect instance.
4951    """
4952    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4953    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4954
4955    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:
4958def except_(
4959    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4960) -> Except:
4961    """
4962    Initializes a syntax tree from one EXCEPT expression.
4963
4964    Example:
4965        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4966        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4967
4968    Args:
4969        left: the SQL code string corresponding to the left-hand side.
4970            If an `Expression` instance is passed, it will be used as-is.
4971        right: the SQL code string corresponding to the right-hand side.
4972            If an `Expression` instance is passed, it will be used as-is.
4973        distinct: set the DISTINCT flag if and only if this is true.
4974        dialect: the dialect used to parse the input expression.
4975        opts: other options to use to parse the input expressions.
4976
4977    Returns:
4978        The new Except instance.
4979    """
4980    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4981    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4982
4983    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:
4986def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4987    """
4988    Initializes a syntax tree from one or multiple SELECT expressions.
4989
4990    Example:
4991        >>> select("col1", "col2").from_("tbl").sql()
4992        'SELECT col1, col2 FROM tbl'
4993
4994    Args:
4995        *expressions: the SQL code string to parse as the expressions of a
4996            SELECT statement. If an Expression instance is passed, this is used as-is.
4997        dialect: the dialect used to parse the input expressions (in the case that an
4998            input expression is a SQL string).
4999        **opts: other options to use to parse the input expressions (again, in the case
5000            that an input expression is a SQL string).
5001
5002    Returns:
5003        Select: the syntax tree for the SELECT statement.
5004    """
5005    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:
5008def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5009    """
5010    Initializes a syntax tree from a FROM expression.
5011
5012    Example:
5013        >>> from_("tbl").select("col1", "col2").sql()
5014        'SELECT col1, col2 FROM tbl'
5015
5016    Args:
5017        *expression: the SQL code string to parse as the FROM expressions of a
5018            SELECT statement. If an Expression instance is passed, this is used as-is.
5019        dialect: the dialect used to parse the input expression (in the case that the
5020            input expression is a SQL string).
5021        **opts: other options to use to parse the input expressions (again, in the case
5022            that the input expression is a SQL string).
5023
5024    Returns:
5025        Select: the syntax tree for the SELECT statement.
5026    """
5027    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:
5030def update(
5031    table: str | Table,
5032    properties: dict,
5033    where: t.Optional[ExpOrStr] = None,
5034    from_: t.Optional[ExpOrStr] = None,
5035    dialect: DialectType = None,
5036    **opts,
5037) -> Update:
5038    """
5039    Creates an update statement.
5040
5041    Example:
5042        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5043        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5044
5045    Args:
5046        *properties: dictionary of properties to set which are
5047            auto converted to sql objects eg None -> NULL
5048        where: sql conditional parsed into a WHERE statement
5049        from_: sql statement parsed into a FROM statement
5050        dialect: the dialect used to parse the input expressions.
5051        **opts: other options to use to parse the input expressions.
5052
5053    Returns:
5054        Update: the syntax tree for the UPDATE statement.
5055    """
5056    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5057    update_expr.set(
5058        "expressions",
5059        [
5060            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5061            for k, v in properties.items()
5062        ],
5063    )
5064    if from_:
5065        update_expr.set(
5066            "from",
5067            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5068        )
5069    if isinstance(where, Condition):
5070        where = Where(this=where)
5071    if where:
5072        update_expr.set(
5073            "where",
5074            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5075        )
5076    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:
5079def delete(
5080    table: ExpOrStr,
5081    where: t.Optional[ExpOrStr] = None,
5082    returning: t.Optional[ExpOrStr] = None,
5083    dialect: DialectType = None,
5084    **opts,
5085) -> Delete:
5086    """
5087    Builds a delete statement.
5088
5089    Example:
5090        >>> delete("my_table", where="id > 1").sql()
5091        'DELETE FROM my_table WHERE id > 1'
5092
5093    Args:
5094        where: sql conditional parsed into a WHERE statement
5095        returning: sql conditional parsed into a RETURNING statement
5096        dialect: the dialect used to parse the input expressions.
5097        **opts: other options to use to parse the input expressions.
5098
5099    Returns:
5100        Delete: the syntax tree for the DELETE statement.
5101    """
5102    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5103    if where:
5104        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5105    if returning:
5106        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5107    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:
5110def insert(
5111    expression: ExpOrStr,
5112    into: ExpOrStr,
5113    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5114    overwrite: t.Optional[bool] = None,
5115    dialect: DialectType = None,
5116    copy: bool = True,
5117    **opts,
5118) -> Insert:
5119    """
5120    Builds an INSERT statement.
5121
5122    Example:
5123        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5124        'INSERT INTO tbl VALUES (1, 2, 3)'
5125
5126    Args:
5127        expression: the sql string or expression of the INSERT statement
5128        into: the tbl to insert data to.
5129        columns: optionally the table's column names.
5130        overwrite: whether to INSERT OVERWRITE or not.
5131        dialect: the dialect used to parse the input expressions.
5132        copy: whether or not to copy the expression.
5133        **opts: other options to use to parse the input expressions.
5134
5135    Returns:
5136        Insert: the syntax tree for the INSERT statement.
5137    """
5138    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5139    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5140
5141    if columns:
5142        this = _apply_list_builder(
5143            *columns,
5144            instance=Schema(this=this),
5145            arg="expressions",
5146            into=Identifier,
5147            copy=False,
5148            dialect=dialect,
5149            **opts,
5150        )
5151
5152    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:
5155def condition(
5156    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5157) -> Condition:
5158    """
5159    Initialize a logical condition expression.
5160
5161    Example:
5162        >>> condition("x=1").sql()
5163        'x = 1'
5164
5165        This is helpful for composing larger logical syntax trees:
5166        >>> where = condition("x=1")
5167        >>> where = where.and_("y=1")
5168        >>> Select().from_("tbl").select("*").where(where).sql()
5169        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5170
5171    Args:
5172        *expression: the SQL code string to parse.
5173            If an Expression instance is passed, this is used as-is.
5174        dialect: the dialect used to parse the input expression (in the case that the
5175            input expression is a SQL string).
5176        copy: Whether or not to copy `expression` (only applies to expressions).
5177        **opts: other options to use to parse the input expressions (again, in the case
5178            that the input expression is a SQL string).
5179
5180    Returns:
5181        The new Condition instance
5182    """
5183    return maybe_parse(
5184        expression,
5185        into=Condition,
5186        dialect=dialect,
5187        copy=copy,
5188        **opts,
5189    )

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:
5192def and_(
5193    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5194) -> Condition:
5195    """
5196    Combine multiple conditions with an AND logical operator.
5197
5198    Example:
5199        >>> and_("x=1", and_("y=1", "z=1")).sql()
5200        'x = 1 AND (y = 1 AND z = 1)'
5201
5202    Args:
5203        *expressions: the SQL code strings to parse.
5204            If an Expression instance is passed, this is used as-is.
5205        dialect: the dialect used to parse the input expression.
5206        copy: whether or not to copy `expressions` (only applies to Expressions).
5207        **opts: other options to use to parse the input expressions.
5208
5209    Returns:
5210        And: the new condition
5211    """
5212    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:
5215def or_(
5216    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5217) -> Condition:
5218    """
5219    Combine multiple conditions with an OR logical operator.
5220
5221    Example:
5222        >>> or_("x=1", or_("y=1", "z=1")).sql()
5223        'x = 1 OR (y = 1 OR z = 1)'
5224
5225    Args:
5226        *expressions: the SQL code strings to parse.
5227            If an Expression instance is passed, this is used as-is.
5228        dialect: the dialect used to parse the input expression.
5229        copy: whether or not to copy `expressions` (only applies to Expressions).
5230        **opts: other options to use to parse the input expressions.
5231
5232    Returns:
5233        Or: the new condition
5234    """
5235    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:
5238def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5239    """
5240    Wrap a condition with a NOT operator.
5241
5242    Example:
5243        >>> not_("this_suit='black'").sql()
5244        "NOT this_suit = 'black'"
5245
5246    Args:
5247        expression: the SQL code string to parse.
5248            If an Expression instance is passed, this is used as-is.
5249        dialect: the dialect used to parse the input expression.
5250        copy: whether to copy the expression or not.
5251        **opts: other options to use to parse the input expressions.
5252
5253    Returns:
5254        The new condition.
5255    """
5256    this = condition(
5257        expression,
5258        dialect=dialect,
5259        copy=copy,
5260        **opts,
5261    )
5262    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:
5265def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5266    """
5267    Wrap an expression in parentheses.
5268
5269    Example:
5270        >>> paren("5 + 3").sql()
5271        '(5 + 3)'
5272
5273    Args:
5274        expression: the SQL code string to parse.
5275            If an Expression instance is passed, this is used as-is.
5276        copy: whether to copy the expression or not.
5277
5278    Returns:
5279        The wrapped expression.
5280    """
5281    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):
5299def to_identifier(name, quoted=None, copy=True):
5300    """Builds an identifier.
5301
5302    Args:
5303        name: The name to turn into an identifier.
5304        quoted: Whether or not force quote the identifier.
5305        copy: Whether or not to copy a passed in Identefier node.
5306
5307    Returns:
5308        The identifier ast node.
5309    """
5310
5311    if name is None:
5312        return None
5313
5314    if isinstance(name, Identifier):
5315        identifier = _maybe_copy(name, copy)
5316    elif isinstance(name, str):
5317        identifier = Identifier(
5318            this=name,
5319            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5320        )
5321    else:
5322        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5323    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:
5329def to_interval(interval: str | Literal) -> Interval:
5330    """Builds an interval expression from a string like '1 day' or '5 months'."""
5331    if isinstance(interval, Literal):
5332        if not interval.is_string:
5333            raise ValueError("Invalid interval string.")
5334
5335        interval = interval.this
5336
5337    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5338
5339    if not interval_parts:
5340        raise ValueError("Invalid interval string.")
5341
5342    return Interval(
5343        this=Literal.string(interval_parts.group(1)),
5344        unit=Var(this=interval_parts.group(2)),
5345    )

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]:
5358def to_table(
5359    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5360) -> t.Optional[Table]:
5361    """
5362    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5363    If a table is passed in then that table is returned.
5364
5365    Args:
5366        sql_path: a `[catalog].[schema].[table]` string.
5367        dialect: the source dialect according to which the table name will be parsed.
5368        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5369
5370    Returns:
5371        A table expression.
5372    """
5373    if sql_path is None or isinstance(sql_path, Table):
5374        return sql_path
5375    if not isinstance(sql_path, str):
5376        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5377
5378    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5379    if table:
5380        for k, v in kwargs.items():
5381            table.set(k, v)
5382
5383    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:
5386def to_column(sql_path: str | Column, **kwargs) -> Column:
5387    """
5388    Create a column from a `[table].[column]` sql path. Schema is optional.
5389
5390    If a column is passed in then that column is returned.
5391
5392    Args:
5393        sql_path: `[table].[column]` string
5394    Returns:
5395        Table: A column expression
5396    """
5397    if sql_path is None or isinstance(sql_path, Column):
5398        return sql_path
5399    if not isinstance(sql_path, str):
5400        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5401    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):
5404def alias_(
5405    expression: ExpOrStr,
5406    alias: str | Identifier,
5407    table: bool | t.Sequence[str | Identifier] = False,
5408    quoted: t.Optional[bool] = None,
5409    dialect: DialectType = None,
5410    copy: bool = True,
5411    **opts,
5412):
5413    """Create an Alias expression.
5414
5415    Example:
5416        >>> alias_('foo', 'bar').sql()
5417        'foo AS bar'
5418
5419        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5420        '(SELECT 1, 2) AS bar(a, b)'
5421
5422    Args:
5423        expression: the SQL code strings to parse.
5424            If an Expression instance is passed, this is used as-is.
5425        alias: the alias name to use. If the name has
5426            special characters it is quoted.
5427        table: Whether or not to create a table alias, can also be a list of columns.
5428        quoted: whether or not to quote the alias
5429        dialect: the dialect used to parse the input expression.
5430        copy: Whether or not to copy the expression.
5431        **opts: other options to use to parse the input expressions.
5432
5433    Returns:
5434        Alias: the aliased expression
5435    """
5436    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5437    alias = to_identifier(alias, quoted=quoted)
5438
5439    if table:
5440        table_alias = TableAlias(this=alias)
5441        exp.set("alias", table_alias)
5442
5443        if not isinstance(table, bool):
5444            for column in table:
5445                table_alias.append("columns", to_identifier(column, quoted=quoted))
5446
5447        return exp
5448
5449    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5450    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5451    # for the complete Window expression.
5452    #
5453    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5454
5455    if "alias" in exp.arg_types and not isinstance(exp, Window):
5456        exp.set("alias", alias)
5457        return exp
5458    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:
5461def subquery(
5462    expression: ExpOrStr,
5463    alias: t.Optional[Identifier | str] = None,
5464    dialect: DialectType = None,
5465    **opts,
5466) -> Select:
5467    """
5468    Build a subquery expression.
5469
5470    Example:
5471        >>> subquery('select x from tbl', 'bar').select('x').sql()
5472        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5473
5474    Args:
5475        expression: the SQL code strings to parse.
5476            If an Expression instance is passed, this is used as-is.
5477        alias: the alias name to use.
5478        dialect: the dialect used to parse the input expression.
5479        **opts: other options to use to parse the input expressions.
5480
5481    Returns:
5482        A new Select instance with the subquery expression included.
5483    """
5484
5485    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5486    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:
5489def column(
5490    col: str | Identifier,
5491    table: t.Optional[str | Identifier] = None,
5492    db: t.Optional[str | Identifier] = None,
5493    catalog: t.Optional[str | Identifier] = None,
5494    quoted: t.Optional[bool] = None,
5495) -> Column:
5496    """
5497    Build a Column.
5498
5499    Args:
5500        col: Column name.
5501        table: Table name.
5502        db: Database name.
5503        catalog: Catalog name.
5504        quoted: Whether to force quotes on the column's identifiers.
5505
5506    Returns:
5507        The new Column instance.
5508    """
5509    return Column(
5510        this=to_identifier(col, quoted=quoted),
5511        table=to_identifier(table, quoted=quoted),
5512        db=to_identifier(db, quoted=quoted),
5513        catalog=to_identifier(catalog, quoted=quoted),
5514    )

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:
5517def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5518    """Cast an expression to a data type.
5519
5520    Example:
5521        >>> cast('x + 1', 'int').sql()
5522        'CAST(x + 1 AS INT)'
5523
5524    Args:
5525        expression: The expression to cast.
5526        to: The datatype to cast to.
5527
5528    Returns:
5529        The new Cast instance.
5530    """
5531    expression = maybe_parse(expression, **opts)
5532    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:
5535def table_(
5536    table: Identifier | str,
5537    db: t.Optional[Identifier | str] = None,
5538    catalog: t.Optional[Identifier | str] = None,
5539    quoted: t.Optional[bool] = None,
5540    alias: t.Optional[Identifier | str] = None,
5541) -> Table:
5542    """Build a Table.
5543
5544    Args:
5545        table: Table name.
5546        db: Database name.
5547        catalog: Catalog name.
5548        quote: Whether to force quotes on the table's identifiers.
5549        alias: Table's alias.
5550
5551    Returns:
5552        The new Table instance.
5553    """
5554    return Table(
5555        this=to_identifier(table, quoted=quoted),
5556        db=to_identifier(db, quoted=quoted),
5557        catalog=to_identifier(catalog, quoted=quoted),
5558        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5559    )

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:
5562def values(
5563    values: t.Iterable[t.Tuple[t.Any, ...]],
5564    alias: t.Optional[str] = None,
5565    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5566) -> Values:
5567    """Build VALUES statement.
5568
5569    Example:
5570        >>> values([(1, '2')]).sql()
5571        "VALUES (1, '2')"
5572
5573    Args:
5574        values: values statements that will be converted to SQL
5575        alias: optional alias
5576        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5577         If either are provided then an alias is also required.
5578
5579    Returns:
5580        Values: the Values expression object
5581    """
5582    if columns and not alias:
5583        raise ValueError("Alias is required when providing columns")
5584
5585    return Values(
5586        expressions=[convert(tup) for tup in values],
5587        alias=(
5588            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5589            if columns
5590            else (TableAlias(this=to_identifier(alias)) if alias else None)
5591        ),
5592    )

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:
5595def var(name: t.Optional[ExpOrStr]) -> Var:
5596    """Build a SQL variable.
5597
5598    Example:
5599        >>> repr(var('x'))
5600        '(VAR this: x)'
5601
5602        >>> repr(var(column('x', table='y')))
5603        '(VAR this: x)'
5604
5605    Args:
5606        name: The name of the var or an expression who's name will become the var.
5607
5608    Returns:
5609        The new variable node.
5610    """
5611    if not name:
5612        raise ValueError("Cannot convert empty name into var.")
5613
5614    if isinstance(name, Expression):
5615        name = name.name
5616    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:
5619def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5620    """Build ALTER TABLE... RENAME... expression
5621
5622    Args:
5623        old_name: The old name of the table
5624        new_name: The new name of the table
5625
5626    Returns:
5627        Alter table expression
5628    """
5629    old_table = to_table(old_name)
5630    new_table = to_table(new_name)
5631    return AlterTable(
5632        this=old_table,
5633        actions=[
5634            RenameTable(this=new_table),
5635        ],
5636    )

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:
5639def convert(value: t.Any, copy: bool = False) -> Expression:
5640    """Convert a python value into an expression object.
5641
5642    Raises an error if a conversion is not possible.
5643
5644    Args:
5645        value: A python object.
5646        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5647
5648    Returns:
5649        Expression: the equivalent expression object.
5650    """
5651    if isinstance(value, Expression):
5652        return _maybe_copy(value, copy)
5653    if isinstance(value, str):
5654        return Literal.string(value)
5655    if isinstance(value, bool):
5656        return Boolean(this=value)
5657    if value is None or (isinstance(value, float) and math.isnan(value)):
5658        return NULL
5659    if isinstance(value, numbers.Number):
5660        return Literal.number(value)
5661    if isinstance(value, datetime.datetime):
5662        datetime_literal = Literal.string(
5663            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5664        )
5665        return TimeStrToTime(this=datetime_literal)
5666    if isinstance(value, datetime.date):
5667        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5668        return DateStrToDate(this=date_literal)
5669    if isinstance(value, tuple):
5670        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5671    if isinstance(value, list):
5672        return Array(expressions=[convert(v, copy=copy) for v in value])
5673    if isinstance(value, dict):
5674        return Map(
5675            keys=[convert(k, copy=copy) for k in value],
5676            values=[convert(v, copy=copy) for v in value.values()],
5677        )
5678    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:
5681def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5682    """
5683    Replace children of an expression with the result of a lambda fun(child) -> exp.
5684    """
5685    for k, v in expression.args.items():
5686        is_list_arg = type(v) is list
5687
5688        child_nodes = v if is_list_arg else [v]
5689        new_child_nodes = []
5690
5691        for cn in child_nodes:
5692            if isinstance(cn, Expression):
5693                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5694                    new_child_nodes.append(child_node)
5695                    child_node.parent = expression
5696                    child_node.arg_key = k
5697            else:
5698                new_child_nodes.append(cn)
5699
5700        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]:
5703def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5704    """
5705    Return all table names referenced through columns in an expression.
5706
5707    Example:
5708        >>> import sqlglot
5709        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5710        ['a', 'c']
5711
5712    Args:
5713        expression: expression to find table names.
5714        exclude: a table name to exclude
5715
5716    Returns:
5717        A list of unique names.
5718    """
5719    return {
5720        table
5721        for table in (column.table for column in expression.find_all(Column))
5722        if table and table != exclude
5723    }

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:
5726def table_name(table: Table | str, dialect: DialectType = None) -> str:
5727    """Get the full name of a table as a string.
5728
5729    Args:
5730        table: Table expression node or string.
5731        dialect: The dialect to generate the table name for.
5732
5733    Examples:
5734        >>> from sqlglot import exp, parse_one
5735        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5736        'a.b.c'
5737
5738    Returns:
5739        The table name.
5740    """
5741
5742    table = maybe_parse(table, into=Table)
5743
5744    if not table:
5745        raise ValueError(f"Cannot parse {table}")
5746
5747    return ".".join(
5748        part.sql(dialect=dialect) if not SAFE_IDENTIFIER_RE.match(part.name) else part.name
5749        for part in table.parts
5750    )

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:
5753def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5754    """Replace all tables in expression according to the mapping.
5755
5756    Args:
5757        expression: expression node to be transformed and replaced.
5758        mapping: mapping of table names.
5759        copy: whether or not to copy the expression.
5760
5761    Examples:
5762        >>> from sqlglot import exp, parse_one
5763        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5764        'SELECT * FROM c'
5765
5766    Returns:
5767        The mapped expression.
5768    """
5769
5770    def _replace_tables(node: Expression) -> Expression:
5771        if isinstance(node, Table):
5772            new_name = mapping.get(table_name(node))
5773            if new_name:
5774                return to_table(
5775                    new_name,
5776                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5777                )
5778        return node
5779
5780    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:
5783def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5784    """Replace placeholders in an expression.
5785
5786    Args:
5787        expression: expression node to be transformed and replaced.
5788        args: positional names that will substitute unnamed placeholders in the given order.
5789        kwargs: keyword arguments that will substitute named placeholders.
5790
5791    Examples:
5792        >>> from sqlglot import exp, parse_one
5793        >>> replace_placeholders(
5794        ...     parse_one("select * from :tbl where ? = ?"),
5795        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5796        ... ).sql()
5797        "SELECT * FROM foo WHERE str_col = 'b'"
5798
5799    Returns:
5800        The mapped expression.
5801    """
5802
5803    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5804        if isinstance(node, Placeholder):
5805            if node.name:
5806                new_name = kwargs.get(node.name)
5807                if new_name:
5808                    return convert(new_name)
5809            else:
5810                try:
5811                    return convert(next(args))
5812                except StopIteration:
5813                    pass
5814        return node
5815
5816    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:
5819def expand(
5820    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5821) -> Expression:
5822    """Transforms an expression by expanding all referenced sources into subqueries.
5823
5824    Examples:
5825        >>> from sqlglot import parse_one
5826        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5827        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5828
5829        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5830        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5831
5832    Args:
5833        expression: The expression to expand.
5834        sources: A dictionary of name to Subqueryables.
5835        copy: Whether or not to copy the expression during transformation. Defaults to True.
5836
5837    Returns:
5838        The transformed expression.
5839    """
5840
5841    def _expand(node: Expression):
5842        if isinstance(node, Table):
5843            name = table_name(node)
5844            source = sources.get(name)
5845            if source:
5846                subquery = source.subquery(node.alias or name)
5847                subquery.comments = [f"source: {name}"]
5848                return subquery.transform(_expand, copy=False)
5849        return node
5850
5851    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:
5854def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5855    """
5856    Returns a Func expression.
5857
5858    Examples:
5859        >>> func("abs", 5).sql()
5860        'ABS(5)'
5861
5862        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5863        'CAST(5 AS DOUBLE)'
5864
5865    Args:
5866        name: the name of the function to build.
5867        args: the args used to instantiate the function of interest.
5868        dialect: the source dialect.
5869        kwargs: the kwargs used to instantiate the function of interest.
5870
5871    Note:
5872        The arguments `args` and `kwargs` are mutually exclusive.
5873
5874    Returns:
5875        An instance of the function of interest, or an anonymous function, if `name` doesn't
5876        correspond to an existing `sqlglot.expressions.Func` class.
5877    """
5878    if args and kwargs:
5879        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5880
5881    from sqlglot.dialects.dialect import Dialect
5882
5883    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5884    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5885
5886    parser = Dialect.get_or_raise(dialect)().parser()
5887    from_args_list = parser.FUNCTIONS.get(name.upper())
5888
5889    if from_args_list:
5890        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5891    else:
5892        kwargs = kwargs or {"expressions": converted}
5893        function = Anonymous(this=name, **kwargs)
5894
5895    for error_message in function.error_messages(converted):
5896        raise ValueError(error_message)
5897
5898    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:
5901def true() -> Boolean:
5902    """
5903    Returns a true Boolean expression.
5904    """
5905    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5908def false() -> Boolean:
5909    """
5910    Returns a false Boolean expression.
5911    """
5912    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5915def null() -> Null:
5916    """
5917    Returns a Null expression.
5918    """
5919    return Null()

Returns a Null expression.

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