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    }
1624
1625
1626class Lambda(Expression):
1627    arg_types = {"this": True, "expressions": True}
1628
1629
1630class Limit(Expression):
1631    arg_types = {"this": False, "expression": True, "offset": False}
1632
1633
1634class Literal(Condition):
1635    arg_types = {"this": True, "is_string": True}
1636
1637    @property
1638    def hashable_args(self) -> t.Any:
1639        return (self.this, self.args.get("is_string"))
1640
1641    @classmethod
1642    def number(cls, number) -> Literal:
1643        return cls(this=str(number), is_string=False)
1644
1645    @classmethod
1646    def string(cls, string) -> Literal:
1647        return cls(this=str(string), is_string=True)
1648
1649    @property
1650    def output_name(self) -> str:
1651        return self.name
1652
1653
1654class Join(Expression):
1655    arg_types = {
1656        "this": True,
1657        "on": False,
1658        "side": False,
1659        "kind": False,
1660        "using": False,
1661        "method": False,
1662        "global": False,
1663        "hint": False,
1664    }
1665
1666    @property
1667    def method(self) -> str:
1668        return self.text("method").upper()
1669
1670    @property
1671    def kind(self) -> str:
1672        return self.text("kind").upper()
1673
1674    @property
1675    def side(self) -> str:
1676        return self.text("side").upper()
1677
1678    @property
1679    def hint(self) -> str:
1680        return self.text("hint").upper()
1681
1682    @property
1683    def alias_or_name(self) -> str:
1684        return self.this.alias_or_name
1685
1686    def on(
1687        self,
1688        *expressions: t.Optional[ExpOrStr],
1689        append: bool = True,
1690        dialect: DialectType = None,
1691        copy: bool = True,
1692        **opts,
1693    ) -> Join:
1694        """
1695        Append to or set the ON expressions.
1696
1697        Example:
1698            >>> import sqlglot
1699            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1700            'JOIN x ON y = 1'
1701
1702        Args:
1703            *expressions: the SQL code strings to parse.
1704                If an `Expression` instance is passed, it will be used as-is.
1705                Multiple expressions are combined with an AND operator.
1706            append: if `True`, AND the new expressions to any existing expression.
1707                Otherwise, this resets the expression.
1708            dialect: the dialect used to parse the input expressions.
1709            copy: if `False`, modify this expression instance in-place.
1710            opts: other options to use to parse the input expressions.
1711
1712        Returns:
1713            The modified Join expression.
1714        """
1715        join = _apply_conjunction_builder(
1716            *expressions,
1717            instance=self,
1718            arg="on",
1719            append=append,
1720            dialect=dialect,
1721            copy=copy,
1722            **opts,
1723        )
1724
1725        if join.kind == "CROSS":
1726            join.set("kind", None)
1727
1728        return join
1729
1730    def using(
1731        self,
1732        *expressions: t.Optional[ExpOrStr],
1733        append: bool = True,
1734        dialect: DialectType = None,
1735        copy: bool = True,
1736        **opts,
1737    ) -> Join:
1738        """
1739        Append to or set the USING expressions.
1740
1741        Example:
1742            >>> import sqlglot
1743            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1744            'JOIN x USING (foo, bla)'
1745
1746        Args:
1747            *expressions: the SQL code strings to parse.
1748                If an `Expression` instance is passed, it will be used as-is.
1749            append: if `True`, concatenate the new expressions to the existing "using" list.
1750                Otherwise, this resets the expression.
1751            dialect: the dialect used to parse the input expressions.
1752            copy: if `False`, modify this expression instance in-place.
1753            opts: other options to use to parse the input expressions.
1754
1755        Returns:
1756            The modified Join expression.
1757        """
1758        join = _apply_list_builder(
1759            *expressions,
1760            instance=self,
1761            arg="using",
1762            append=append,
1763            dialect=dialect,
1764            copy=copy,
1765            **opts,
1766        )
1767
1768        if join.kind == "CROSS":
1769            join.set("kind", None)
1770
1771        return join
1772
1773
1774class Lateral(UDTF):
1775    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1776
1777
1778class MatchRecognize(Expression):
1779    arg_types = {
1780        "partition_by": False,
1781        "order": False,
1782        "measures": False,
1783        "rows": False,
1784        "after": False,
1785        "pattern": False,
1786        "define": False,
1787        "alias": False,
1788    }
1789
1790
1791# Clickhouse FROM FINAL modifier
1792# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1793class Final(Expression):
1794    pass
1795
1796
1797class Offset(Expression):
1798    arg_types = {"this": False, "expression": True}
1799
1800
1801class Order(Expression):
1802    arg_types = {"this": False, "expressions": True}
1803
1804
1805# hive specific sorts
1806# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1807class Cluster(Order):
1808    pass
1809
1810
1811class Distribute(Order):
1812    pass
1813
1814
1815class Sort(Order):
1816    pass
1817
1818
1819class Ordered(Expression):
1820    arg_types = {"this": True, "desc": True, "nulls_first": True}
1821
1822
1823class Property(Expression):
1824    arg_types = {"this": True, "value": True}
1825
1826
1827class AlgorithmProperty(Property):
1828    arg_types = {"this": True}
1829
1830
1831class AutoIncrementProperty(Property):
1832    arg_types = {"this": True}
1833
1834
1835class BlockCompressionProperty(Property):
1836    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1837
1838
1839class CharacterSetProperty(Property):
1840    arg_types = {"this": True, "default": True}
1841
1842
1843class ChecksumProperty(Property):
1844    arg_types = {"on": False, "default": False}
1845
1846
1847class CollateProperty(Property):
1848    arg_types = {"this": True}
1849
1850
1851class CopyGrantsProperty(Property):
1852    arg_types = {}
1853
1854
1855class DataBlocksizeProperty(Property):
1856    arg_types = {
1857        "size": False,
1858        "units": False,
1859        "minimum": False,
1860        "maximum": False,
1861        "default": False,
1862    }
1863
1864
1865class DefinerProperty(Property):
1866    arg_types = {"this": True}
1867
1868
1869class DistKeyProperty(Property):
1870    arg_types = {"this": True}
1871
1872
1873class DistStyleProperty(Property):
1874    arg_types = {"this": True}
1875
1876
1877class EngineProperty(Property):
1878    arg_types = {"this": True}
1879
1880
1881class ToTableProperty(Property):
1882    arg_types = {"this": True}
1883
1884
1885class ExecuteAsProperty(Property):
1886    arg_types = {"this": True}
1887
1888
1889class ExternalProperty(Property):
1890    arg_types = {"this": False}
1891
1892
1893class FallbackProperty(Property):
1894    arg_types = {"no": True, "protection": False}
1895
1896
1897class FileFormatProperty(Property):
1898    arg_types = {"this": True}
1899
1900
1901class FreespaceProperty(Property):
1902    arg_types = {"this": True, "percent": False}
1903
1904
1905class InputOutputFormat(Expression):
1906    arg_types = {"input_format": False, "output_format": False}
1907
1908
1909class IsolatedLoadingProperty(Property):
1910    arg_types = {
1911        "no": True,
1912        "concurrent": True,
1913        "for_all": True,
1914        "for_insert": True,
1915        "for_none": True,
1916    }
1917
1918
1919class JournalProperty(Property):
1920    arg_types = {
1921        "no": False,
1922        "dual": False,
1923        "before": False,
1924        "local": False,
1925        "after": False,
1926    }
1927
1928
1929class LanguageProperty(Property):
1930    arg_types = {"this": True}
1931
1932
1933# spark ddl
1934class ClusteredByProperty(Property):
1935    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
1936
1937
1938class DictProperty(Property):
1939    arg_types = {"this": True, "kind": True, "settings": False}
1940
1941
1942class DictSubProperty(Property):
1943    pass
1944
1945
1946class DictRange(Property):
1947    arg_types = {"this": True, "min": True, "max": True}
1948
1949
1950# Clickhouse CREATE ... ON CLUSTER modifier
1951# https://clickhouse.com/docs/en/sql-reference/distributed-ddl
1952class OnCluster(Property):
1953    arg_types = {"this": True}
1954
1955
1956class LikeProperty(Property):
1957    arg_types = {"this": True, "expressions": False}
1958
1959
1960class LocationProperty(Property):
1961    arg_types = {"this": True}
1962
1963
1964class LockingProperty(Property):
1965    arg_types = {
1966        "this": False,
1967        "kind": True,
1968        "for_or_in": True,
1969        "lock_type": True,
1970        "override": False,
1971    }
1972
1973
1974class LogProperty(Property):
1975    arg_types = {"no": True}
1976
1977
1978class MaterializedProperty(Property):
1979    arg_types = {"this": False}
1980
1981
1982class MergeBlockRatioProperty(Property):
1983    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1984
1985
1986class NoPrimaryIndexProperty(Property):
1987    arg_types = {}
1988
1989
1990class OnCommitProperty(Property):
1991    arg_type = {"delete": False}
1992
1993
1994class PartitionedByProperty(Property):
1995    arg_types = {"this": True}
1996
1997
1998class ReturnsProperty(Property):
1999    arg_types = {"this": True, "is_table": False, "table": False}
2000
2001
2002class RowFormatProperty(Property):
2003    arg_types = {"this": True}
2004
2005
2006class RowFormatDelimitedProperty(Property):
2007    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2008    arg_types = {
2009        "fields": False,
2010        "escaped": False,
2011        "collection_items": False,
2012        "map_keys": False,
2013        "lines": False,
2014        "null": False,
2015        "serde": False,
2016    }
2017
2018
2019class RowFormatSerdeProperty(Property):
2020    arg_types = {"this": True}
2021
2022
2023class SchemaCommentProperty(Property):
2024    arg_types = {"this": True}
2025
2026
2027class SerdeProperties(Property):
2028    arg_types = {"expressions": True}
2029
2030
2031class SetProperty(Property):
2032    arg_types = {"multi": True}
2033
2034
2035class SettingsProperty(Property):
2036    arg_types = {"expressions": True}
2037
2038
2039class SortKeyProperty(Property):
2040    arg_types = {"this": True, "compound": False}
2041
2042
2043class SqlSecurityProperty(Property):
2044    arg_types = {"definer": True}
2045
2046
2047class StabilityProperty(Property):
2048    arg_types = {"this": True}
2049
2050
2051class TemporaryProperty(Property):
2052    arg_types = {}
2053
2054
2055class TransientProperty(Property):
2056    arg_types = {"this": False}
2057
2058
2059class VolatileProperty(Property):
2060    arg_types = {"this": False}
2061
2062
2063class WithDataProperty(Property):
2064    arg_types = {"no": True, "statistics": False}
2065
2066
2067class WithJournalTableProperty(Property):
2068    arg_types = {"this": True}
2069
2070
2071class Properties(Expression):
2072    arg_types = {"expressions": True}
2073
2074    NAME_TO_PROPERTY = {
2075        "ALGORITHM": AlgorithmProperty,
2076        "AUTO_INCREMENT": AutoIncrementProperty,
2077        "CHARACTER SET": CharacterSetProperty,
2078        "CLUSTERED_BY": ClusteredByProperty,
2079        "COLLATE": CollateProperty,
2080        "COMMENT": SchemaCommentProperty,
2081        "DEFINER": DefinerProperty,
2082        "DISTKEY": DistKeyProperty,
2083        "DISTSTYLE": DistStyleProperty,
2084        "ENGINE": EngineProperty,
2085        "EXECUTE AS": ExecuteAsProperty,
2086        "FORMAT": FileFormatProperty,
2087        "LANGUAGE": LanguageProperty,
2088        "LOCATION": LocationProperty,
2089        "PARTITIONED_BY": PartitionedByProperty,
2090        "RETURNS": ReturnsProperty,
2091        "ROW_FORMAT": RowFormatProperty,
2092        "SORTKEY": SortKeyProperty,
2093    }
2094
2095    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2096
2097    # CREATE property locations
2098    # Form: schema specified
2099    #   create [POST_CREATE]
2100    #     table a [POST_NAME]
2101    #     (b int) [POST_SCHEMA]
2102    #     with ([POST_WITH])
2103    #     index (b) [POST_INDEX]
2104    #
2105    # Form: alias selection
2106    #   create [POST_CREATE]
2107    #     table a [POST_NAME]
2108    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2109    #     index (c) [POST_INDEX]
2110    class Location(AutoName):
2111        POST_CREATE = auto()
2112        POST_NAME = auto()
2113        POST_SCHEMA = auto()
2114        POST_WITH = auto()
2115        POST_ALIAS = auto()
2116        POST_EXPRESSION = auto()
2117        POST_INDEX = auto()
2118        UNSUPPORTED = auto()
2119
2120    @classmethod
2121    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2122        expressions = []
2123        for key, value in properties_dict.items():
2124            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2125            if property_cls:
2126                expressions.append(property_cls(this=convert(value)))
2127            else:
2128                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2129
2130        return cls(expressions=expressions)
2131
2132
2133class Qualify(Expression):
2134    pass
2135
2136
2137# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
2138class Return(Expression):
2139    pass
2140
2141
2142class Reference(Expression):
2143    arg_types = {"this": True, "expressions": False, "options": False}
2144
2145
2146class Tuple(Expression):
2147    arg_types = {"expressions": False}
2148
2149    def isin(
2150        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2151    ) -> In:
2152        return In(
2153            this=_maybe_copy(self, copy),
2154            expressions=[convert(e, copy=copy) for e in expressions],
2155            query=maybe_parse(query, copy=copy, **opts) if query else None,
2156        )
2157
2158
2159class Subqueryable(Unionable):
2160    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2161        """
2162        Convert this expression to an aliased expression that can be used as a Subquery.
2163
2164        Example:
2165            >>> subquery = Select().select("x").from_("tbl").subquery()
2166            >>> Select().select("x").from_(subquery).sql()
2167            'SELECT x FROM (SELECT x FROM tbl)'
2168
2169        Args:
2170            alias (str | Identifier): an optional alias for the subquery
2171            copy (bool): if `False`, modify this expression instance in-place.
2172
2173        Returns:
2174            Alias: the subquery
2175        """
2176        instance = _maybe_copy(self, copy)
2177        if not isinstance(alias, Expression):
2178            alias = TableAlias(this=to_identifier(alias)) if alias else None
2179
2180        return Subquery(this=instance, alias=alias)
2181
2182    def limit(
2183        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2184    ) -> Select:
2185        raise NotImplementedError
2186
2187    @property
2188    def ctes(self):
2189        with_ = self.args.get("with")
2190        if not with_:
2191            return []
2192        return with_.expressions
2193
2194    @property
2195    def selects(self):
2196        raise NotImplementedError("Subqueryable objects must implement `selects`")
2197
2198    @property
2199    def named_selects(self):
2200        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2201
2202    def with_(
2203        self,
2204        alias: ExpOrStr,
2205        as_: ExpOrStr,
2206        recursive: t.Optional[bool] = None,
2207        append: bool = True,
2208        dialect: DialectType = None,
2209        copy: bool = True,
2210        **opts,
2211    ) -> Subqueryable:
2212        """
2213        Append to or set the common table expressions.
2214
2215        Example:
2216            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2217            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2218
2219        Args:
2220            alias: the SQL code string to parse as the table name.
2221                If an `Expression` instance is passed, this is used as-is.
2222            as_: the SQL code string to parse as the table expression.
2223                If an `Expression` instance is passed, it will be used as-is.
2224            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2225            append: if `True`, add to any existing expressions.
2226                Otherwise, this resets the expressions.
2227            dialect: the dialect used to parse the input expression.
2228            copy: if `False`, modify this expression instance in-place.
2229            opts: other options to use to parse the input expressions.
2230
2231        Returns:
2232            The modified expression.
2233        """
2234        return _apply_cte_builder(
2235            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2236        )
2237
2238
2239QUERY_MODIFIERS = {
2240    "match": False,
2241    "laterals": False,
2242    "joins": False,
2243    "pivots": False,
2244    "where": False,
2245    "group": False,
2246    "having": False,
2247    "qualify": False,
2248    "windows": False,
2249    "distribute": False,
2250    "sort": False,
2251    "cluster": False,
2252    "order": False,
2253    "limit": False,
2254    "offset": False,
2255    "locks": False,
2256    "sample": False,
2257    "settings": False,
2258    "format": False,
2259}
2260
2261
2262# https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table?view=sql-server-ver16
2263class WithTableHint(Expression):
2264    arg_types = {"expressions": True}
2265
2266
2267# https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
2268class IndexTableHint(Expression):
2269    arg_types = {"this": True, "expressions": False, "target": False}
2270
2271
2272class Table(Expression):
2273    arg_types = {
2274        "this": True,
2275        "alias": False,
2276        "db": False,
2277        "catalog": False,
2278        "laterals": False,
2279        "joins": False,
2280        "pivots": False,
2281        "hints": False,
2282        "system_time": False,
2283    }
2284
2285    @property
2286    def name(self) -> str:
2287        if isinstance(self.this, Func):
2288            return ""
2289        return self.this.name
2290
2291    @property
2292    def db(self) -> str:
2293        return self.text("db")
2294
2295    @property
2296    def catalog(self) -> str:
2297        return self.text("catalog")
2298
2299    @property
2300    def parts(self) -> t.List[Identifier]:
2301        """Return the parts of a table in order catalog, db, table."""
2302        return [
2303            t.cast(Identifier, self.args[part])
2304            for part in ("catalog", "db", "this")
2305            if self.args.get(part)
2306        ]
2307
2308
2309# See the TSQL "Querying data in a system-versioned temporal table" page
2310class SystemTime(Expression):
2311    arg_types = {
2312        "this": False,
2313        "expression": False,
2314        "kind": True,
2315    }
2316
2317
2318class Union(Subqueryable):
2319    arg_types = {
2320        "with": False,
2321        "this": True,
2322        "expression": True,
2323        "distinct": False,
2324        **QUERY_MODIFIERS,
2325    }
2326
2327    def limit(
2328        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2329    ) -> Select:
2330        """
2331        Set the LIMIT expression.
2332
2333        Example:
2334            >>> select("1").union(select("1")).limit(1).sql()
2335            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2336
2337        Args:
2338            expression: the SQL code string to parse.
2339                This can also be an integer.
2340                If a `Limit` instance is passed, this is used as-is.
2341                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2342            dialect: the dialect used to parse the input expression.
2343            copy: if `False`, modify this expression instance in-place.
2344            opts: other options to use to parse the input expressions.
2345
2346        Returns:
2347            The limited subqueryable.
2348        """
2349        return (
2350            select("*")
2351            .from_(self.subquery(alias="_l_0", copy=copy))
2352            .limit(expression, dialect=dialect, copy=False, **opts)
2353        )
2354
2355    def select(
2356        self,
2357        *expressions: t.Optional[ExpOrStr],
2358        append: bool = True,
2359        dialect: DialectType = None,
2360        copy: bool = True,
2361        **opts,
2362    ) -> Union:
2363        """Append to or set the SELECT of the union recursively.
2364
2365        Example:
2366            >>> from sqlglot import parse_one
2367            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2368            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2369
2370        Args:
2371            *expressions: the SQL code strings to parse.
2372                If an `Expression` instance is passed, it will be used as-is.
2373            append: if `True`, add to any existing expressions.
2374                Otherwise, this resets the expressions.
2375            dialect: the dialect used to parse the input expressions.
2376            copy: if `False`, modify this expression instance in-place.
2377            opts: other options to use to parse the input expressions.
2378
2379        Returns:
2380            Union: the modified expression.
2381        """
2382        this = self.copy() if copy else self
2383        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2384        this.expression.unnest().select(
2385            *expressions, append=append, dialect=dialect, copy=False, **opts
2386        )
2387        return this
2388
2389    @property
2390    def named_selects(self):
2391        return self.this.unnest().named_selects
2392
2393    @property
2394    def is_star(self) -> bool:
2395        return self.this.is_star or self.expression.is_star
2396
2397    @property
2398    def selects(self):
2399        return self.this.unnest().selects
2400
2401    @property
2402    def left(self):
2403        return self.this
2404
2405    @property
2406    def right(self):
2407        return self.expression
2408
2409
2410class Except(Union):
2411    pass
2412
2413
2414class Intersect(Union):
2415    pass
2416
2417
2418class Unnest(UDTF):
2419    arg_types = {
2420        "expressions": True,
2421        "ordinality": False,
2422        "alias": False,
2423        "offset": False,
2424    }
2425
2426
2427class Update(Expression):
2428    arg_types = {
2429        "with": False,
2430        "this": False,
2431        "expressions": True,
2432        "from": False,
2433        "where": False,
2434        "returning": False,
2435        "limit": False,
2436    }
2437
2438
2439class Values(UDTF):
2440    arg_types = {
2441        "expressions": True,
2442        "ordinality": False,
2443        "alias": False,
2444    }
2445
2446
2447class Var(Expression):
2448    pass
2449
2450
2451class Schema(Expression):
2452    arg_types = {"this": False, "expressions": False}
2453
2454
2455# https://dev.mysql.com/doc/refman/8.0/en/select.html
2456# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html
2457class Lock(Expression):
2458    arg_types = {"update": True, "expressions": False, "wait": False}
2459
2460
2461class Select(Subqueryable):
2462    arg_types = {
2463        "with": False,
2464        "kind": False,
2465        "expressions": False,
2466        "hint": False,
2467        "distinct": False,
2468        "into": False,
2469        "from": False,
2470        **QUERY_MODIFIERS,
2471    }
2472
2473    def from_(
2474        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2475    ) -> Select:
2476        """
2477        Set the FROM expression.
2478
2479        Example:
2480            >>> Select().from_("tbl").select("x").sql()
2481            'SELECT x FROM tbl'
2482
2483        Args:
2484            expression : the SQL code strings to parse.
2485                If a `From` instance is passed, this is used as-is.
2486                If another `Expression` instance is passed, it will be wrapped in a `From`.
2487            dialect: the dialect used to parse the input expression.
2488            copy: if `False`, modify this expression instance in-place.
2489            opts: other options to use to parse the input expressions.
2490
2491        Returns:
2492            The modified Select expression.
2493        """
2494        return _apply_builder(
2495            expression=expression,
2496            instance=self,
2497            arg="from",
2498            into=From,
2499            prefix="FROM",
2500            dialect=dialect,
2501            copy=copy,
2502            **opts,
2503        )
2504
2505    def group_by(
2506        self,
2507        *expressions: t.Optional[ExpOrStr],
2508        append: bool = True,
2509        dialect: DialectType = None,
2510        copy: bool = True,
2511        **opts,
2512    ) -> Select:
2513        """
2514        Set the GROUP BY expression.
2515
2516        Example:
2517            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2518            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2519
2520        Args:
2521            *expressions: the SQL code strings to parse.
2522                If a `Group` instance is passed, this is used as-is.
2523                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2524                If nothing is passed in then a group by is not applied to the expression
2525            append: if `True`, add to any existing expressions.
2526                Otherwise, this flattens all the `Group` expression into a single expression.
2527            dialect: the dialect used to parse the input expression.
2528            copy: if `False`, modify this expression instance in-place.
2529            opts: other options to use to parse the input expressions.
2530
2531        Returns:
2532            The modified Select expression.
2533        """
2534        if not expressions:
2535            return self if not copy else self.copy()
2536
2537        return _apply_child_list_builder(
2538            *expressions,
2539            instance=self,
2540            arg="group",
2541            append=append,
2542            copy=copy,
2543            prefix="GROUP BY",
2544            into=Group,
2545            dialect=dialect,
2546            **opts,
2547        )
2548
2549    def order_by(
2550        self,
2551        *expressions: t.Optional[ExpOrStr],
2552        append: bool = True,
2553        dialect: DialectType = None,
2554        copy: bool = True,
2555        **opts,
2556    ) -> Select:
2557        """
2558        Set the ORDER BY expression.
2559
2560        Example:
2561            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2562            'SELECT x FROM tbl ORDER BY x DESC'
2563
2564        Args:
2565            *expressions: the SQL code strings to parse.
2566                If a `Group` instance is passed, this is used as-is.
2567                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2568            append: if `True`, add to any existing expressions.
2569                Otherwise, this flattens all the `Order` expression into a single expression.
2570            dialect: the dialect used to parse the input expression.
2571            copy: if `False`, modify this expression instance in-place.
2572            opts: other options to use to parse the input expressions.
2573
2574        Returns:
2575            The modified Select expression.
2576        """
2577        return _apply_child_list_builder(
2578            *expressions,
2579            instance=self,
2580            arg="order",
2581            append=append,
2582            copy=copy,
2583            prefix="ORDER BY",
2584            into=Order,
2585            dialect=dialect,
2586            **opts,
2587        )
2588
2589    def sort_by(
2590        self,
2591        *expressions: t.Optional[ExpOrStr],
2592        append: bool = True,
2593        dialect: DialectType = None,
2594        copy: bool = True,
2595        **opts,
2596    ) -> Select:
2597        """
2598        Set the SORT BY expression.
2599
2600        Example:
2601            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2602            'SELECT x FROM tbl SORT BY x DESC'
2603
2604        Args:
2605            *expressions: the SQL code strings to parse.
2606                If a `Group` instance is passed, this is used as-is.
2607                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2608            append: if `True`, add to any existing expressions.
2609                Otherwise, this flattens all the `Order` expression into a single expression.
2610            dialect: the dialect used to parse the input expression.
2611            copy: if `False`, modify this expression instance in-place.
2612            opts: other options to use to parse the input expressions.
2613
2614        Returns:
2615            The modified Select expression.
2616        """
2617        return _apply_child_list_builder(
2618            *expressions,
2619            instance=self,
2620            arg="sort",
2621            append=append,
2622            copy=copy,
2623            prefix="SORT BY",
2624            into=Sort,
2625            dialect=dialect,
2626            **opts,
2627        )
2628
2629    def cluster_by(
2630        self,
2631        *expressions: t.Optional[ExpOrStr],
2632        append: bool = True,
2633        dialect: DialectType = None,
2634        copy: bool = True,
2635        **opts,
2636    ) -> Select:
2637        """
2638        Set the CLUSTER BY expression.
2639
2640        Example:
2641            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2642            'SELECT x FROM tbl CLUSTER BY x DESC'
2643
2644        Args:
2645            *expressions: the SQL code strings to parse.
2646                If a `Group` instance is passed, this is used as-is.
2647                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2648            append: if `True`, add to any existing expressions.
2649                Otherwise, this flattens all the `Order` expression into a single expression.
2650            dialect: the dialect used to parse the input expression.
2651            copy: if `False`, modify this expression instance in-place.
2652            opts: other options to use to parse the input expressions.
2653
2654        Returns:
2655            The modified Select expression.
2656        """
2657        return _apply_child_list_builder(
2658            *expressions,
2659            instance=self,
2660            arg="cluster",
2661            append=append,
2662            copy=copy,
2663            prefix="CLUSTER BY",
2664            into=Cluster,
2665            dialect=dialect,
2666            **opts,
2667        )
2668
2669    def limit(
2670        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2671    ) -> Select:
2672        """
2673        Set the LIMIT expression.
2674
2675        Example:
2676            >>> Select().from_("tbl").select("x").limit(10).sql()
2677            'SELECT x FROM tbl LIMIT 10'
2678
2679        Args:
2680            expression: the SQL code string to parse.
2681                This can also be an integer.
2682                If a `Limit` instance is passed, this is used as-is.
2683                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2684            dialect: the dialect used to parse the input expression.
2685            copy: if `False`, modify this expression instance in-place.
2686            opts: other options to use to parse the input expressions.
2687
2688        Returns:
2689            Select: the modified expression.
2690        """
2691        return _apply_builder(
2692            expression=expression,
2693            instance=self,
2694            arg="limit",
2695            into=Limit,
2696            prefix="LIMIT",
2697            dialect=dialect,
2698            copy=copy,
2699            **opts,
2700        )
2701
2702    def offset(
2703        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2704    ) -> Select:
2705        """
2706        Set the OFFSET expression.
2707
2708        Example:
2709            >>> Select().from_("tbl").select("x").offset(10).sql()
2710            'SELECT x FROM tbl OFFSET 10'
2711
2712        Args:
2713            expression: the SQL code string to parse.
2714                This can also be an integer.
2715                If a `Offset` instance is passed, this is used as-is.
2716                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2717            dialect: the dialect used to parse the input expression.
2718            copy: if `False`, modify this expression instance in-place.
2719            opts: other options to use to parse the input expressions.
2720
2721        Returns:
2722            The modified Select expression.
2723        """
2724        return _apply_builder(
2725            expression=expression,
2726            instance=self,
2727            arg="offset",
2728            into=Offset,
2729            prefix="OFFSET",
2730            dialect=dialect,
2731            copy=copy,
2732            **opts,
2733        )
2734
2735    def select(
2736        self,
2737        *expressions: t.Optional[ExpOrStr],
2738        append: bool = True,
2739        dialect: DialectType = None,
2740        copy: bool = True,
2741        **opts,
2742    ) -> Select:
2743        """
2744        Append to or set the SELECT expressions.
2745
2746        Example:
2747            >>> Select().select("x", "y").sql()
2748            'SELECT x, y'
2749
2750        Args:
2751            *expressions: the SQL code strings to parse.
2752                If an `Expression` instance is passed, it will be used as-is.
2753            append: if `True`, add to any existing expressions.
2754                Otherwise, this resets the expressions.
2755            dialect: the dialect used to parse the input expressions.
2756            copy: if `False`, modify this expression instance in-place.
2757            opts: other options to use to parse the input expressions.
2758
2759        Returns:
2760            The modified Select expression.
2761        """
2762        return _apply_list_builder(
2763            *expressions,
2764            instance=self,
2765            arg="expressions",
2766            append=append,
2767            dialect=dialect,
2768            copy=copy,
2769            **opts,
2770        )
2771
2772    def lateral(
2773        self,
2774        *expressions: t.Optional[ExpOrStr],
2775        append: bool = True,
2776        dialect: DialectType = None,
2777        copy: bool = True,
2778        **opts,
2779    ) -> Select:
2780        """
2781        Append to or set the LATERAL expressions.
2782
2783        Example:
2784            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2785            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2786
2787        Args:
2788            *expressions: the SQL code strings to parse.
2789                If an `Expression` instance is passed, it will be used as-is.
2790            append: if `True`, add to any existing expressions.
2791                Otherwise, this resets the expressions.
2792            dialect: the dialect used to parse the input expressions.
2793            copy: if `False`, modify this expression instance in-place.
2794            opts: other options to use to parse the input expressions.
2795
2796        Returns:
2797            The modified Select expression.
2798        """
2799        return _apply_list_builder(
2800            *expressions,
2801            instance=self,
2802            arg="laterals",
2803            append=append,
2804            into=Lateral,
2805            prefix="LATERAL VIEW",
2806            dialect=dialect,
2807            copy=copy,
2808            **opts,
2809        )
2810
2811    def join(
2812        self,
2813        expression: ExpOrStr,
2814        on: t.Optional[ExpOrStr] = None,
2815        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2816        append: bool = True,
2817        join_type: t.Optional[str] = None,
2818        join_alias: t.Optional[Identifier | str] = None,
2819        dialect: DialectType = None,
2820        copy: bool = True,
2821        **opts,
2822    ) -> Select:
2823        """
2824        Append to or set the JOIN expressions.
2825
2826        Example:
2827            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2828            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2829
2830            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2831            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2832
2833            Use `join_type` to change the type of join:
2834
2835            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2836            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2837
2838        Args:
2839            expression: the SQL code string to parse.
2840                If an `Expression` instance is passed, it will be used as-is.
2841            on: optionally specify the join "on" criteria as a SQL string.
2842                If an `Expression` instance is passed, it will be used as-is.
2843            using: optionally specify the join "using" criteria as a SQL string.
2844                If an `Expression` instance is passed, it will be used as-is.
2845            append: if `True`, add to any existing expressions.
2846                Otherwise, this resets the expressions.
2847            join_type: if set, alter the parsed join type.
2848            join_alias: an optional alias for the joined source.
2849            dialect: the dialect used to parse the input expressions.
2850            copy: if `False`, modify this expression instance in-place.
2851            opts: other options to use to parse the input expressions.
2852
2853        Returns:
2854            Select: the modified expression.
2855        """
2856        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2857
2858        try:
2859            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2860        except ParseError:
2861            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2862
2863        join = expression if isinstance(expression, Join) else Join(this=expression)
2864
2865        if isinstance(join.this, Select):
2866            join.this.replace(join.this.subquery())
2867
2868        if join_type:
2869            method: t.Optional[Token]
2870            side: t.Optional[Token]
2871            kind: t.Optional[Token]
2872
2873            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2874
2875            if method:
2876                join.set("method", method.text)
2877            if side:
2878                join.set("side", side.text)
2879            if kind:
2880                join.set("kind", kind.text)
2881
2882        if on:
2883            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2884            join.set("on", on)
2885
2886        if using:
2887            join = _apply_list_builder(
2888                *ensure_list(using),
2889                instance=join,
2890                arg="using",
2891                append=append,
2892                copy=copy,
2893                **opts,
2894            )
2895
2896        if join_alias:
2897            join.set("this", alias_(join.this, join_alias, table=True))
2898
2899        return _apply_list_builder(
2900            join,
2901            instance=self,
2902            arg="joins",
2903            append=append,
2904            copy=copy,
2905            **opts,
2906        )
2907
2908    def where(
2909        self,
2910        *expressions: t.Optional[ExpOrStr],
2911        append: bool = True,
2912        dialect: DialectType = None,
2913        copy: bool = True,
2914        **opts,
2915    ) -> Select:
2916        """
2917        Append to or set the WHERE expressions.
2918
2919        Example:
2920            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2921            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2922
2923        Args:
2924            *expressions: the SQL code strings to parse.
2925                If an `Expression` instance is passed, it will be used as-is.
2926                Multiple expressions are combined with an AND operator.
2927            append: if `True`, AND the new expressions to any existing expression.
2928                Otherwise, this resets the expression.
2929            dialect: the dialect used to parse the input expressions.
2930            copy: if `False`, modify this expression instance in-place.
2931            opts: other options to use to parse the input expressions.
2932
2933        Returns:
2934            Select: the modified expression.
2935        """
2936        return _apply_conjunction_builder(
2937            *expressions,
2938            instance=self,
2939            arg="where",
2940            append=append,
2941            into=Where,
2942            dialect=dialect,
2943            copy=copy,
2944            **opts,
2945        )
2946
2947    def having(
2948        self,
2949        *expressions: t.Optional[ExpOrStr],
2950        append: bool = True,
2951        dialect: DialectType = None,
2952        copy: bool = True,
2953        **opts,
2954    ) -> Select:
2955        """
2956        Append to or set the HAVING expressions.
2957
2958        Example:
2959            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2960            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2961
2962        Args:
2963            *expressions: the SQL code strings to parse.
2964                If an `Expression` instance is passed, it will be used as-is.
2965                Multiple expressions are combined with an AND operator.
2966            append: if `True`, AND the new expressions to any existing expression.
2967                Otherwise, this resets the expression.
2968            dialect: the dialect used to parse the input expressions.
2969            copy: if `False`, modify this expression instance in-place.
2970            opts: other options to use to parse the input expressions.
2971
2972        Returns:
2973            The modified Select expression.
2974        """
2975        return _apply_conjunction_builder(
2976            *expressions,
2977            instance=self,
2978            arg="having",
2979            append=append,
2980            into=Having,
2981            dialect=dialect,
2982            copy=copy,
2983            **opts,
2984        )
2985
2986    def window(
2987        self,
2988        *expressions: t.Optional[ExpOrStr],
2989        append: bool = True,
2990        dialect: DialectType = None,
2991        copy: bool = True,
2992        **opts,
2993    ) -> Select:
2994        return _apply_list_builder(
2995            *expressions,
2996            instance=self,
2997            arg="windows",
2998            append=append,
2999            into=Window,
3000            dialect=dialect,
3001            copy=copy,
3002            **opts,
3003        )
3004
3005    def qualify(
3006        self,
3007        *expressions: t.Optional[ExpOrStr],
3008        append: bool = True,
3009        dialect: DialectType = None,
3010        copy: bool = True,
3011        **opts,
3012    ) -> Select:
3013        return _apply_conjunction_builder(
3014            *expressions,
3015            instance=self,
3016            arg="qualify",
3017            append=append,
3018            into=Qualify,
3019            dialect=dialect,
3020            copy=copy,
3021            **opts,
3022        )
3023
3024    def distinct(
3025        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3026    ) -> Select:
3027        """
3028        Set the OFFSET expression.
3029
3030        Example:
3031            >>> Select().from_("tbl").select("x").distinct().sql()
3032            'SELECT DISTINCT x FROM tbl'
3033
3034        Args:
3035            ons: the expressions to distinct on
3036            distinct: whether the Select should be distinct
3037            copy: if `False`, modify this expression instance in-place.
3038
3039        Returns:
3040            Select: the modified expression.
3041        """
3042        instance = _maybe_copy(self, copy)
3043        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3044        instance.set("distinct", Distinct(on=on) if distinct else None)
3045        return instance
3046
3047    def ctas(
3048        self,
3049        table: ExpOrStr,
3050        properties: t.Optional[t.Dict] = None,
3051        dialect: DialectType = None,
3052        copy: bool = True,
3053        **opts,
3054    ) -> Create:
3055        """
3056        Convert this expression to a CREATE TABLE AS statement.
3057
3058        Example:
3059            >>> Select().select("*").from_("tbl").ctas("x").sql()
3060            'CREATE TABLE x AS SELECT * FROM tbl'
3061
3062        Args:
3063            table: the SQL code string to parse as the table name.
3064                If another `Expression` instance is passed, it will be used as-is.
3065            properties: an optional mapping of table properties
3066            dialect: the dialect used to parse the input table.
3067            copy: if `False`, modify this expression instance in-place.
3068            opts: other options to use to parse the input table.
3069
3070        Returns:
3071            The new Create expression.
3072        """
3073        instance = _maybe_copy(self, copy)
3074        table_expression = maybe_parse(
3075            table,
3076            into=Table,
3077            dialect=dialect,
3078            **opts,
3079        )
3080        properties_expression = None
3081        if properties:
3082            properties_expression = Properties.from_dict(properties)
3083
3084        return Create(
3085            this=table_expression,
3086            kind="table",
3087            expression=instance,
3088            properties=properties_expression,
3089        )
3090
3091    def lock(self, update: bool = True, copy: bool = True) -> Select:
3092        """
3093        Set the locking read mode for this expression.
3094
3095        Examples:
3096            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3097            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3098
3099            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3100            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3101
3102        Args:
3103            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3104            copy: if `False`, modify this expression instance in-place.
3105
3106        Returns:
3107            The modified expression.
3108        """
3109        inst = _maybe_copy(self, copy)
3110        inst.set("locks", [Lock(update=update)])
3111
3112        return inst
3113
3114    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3115        """
3116        Set hints for this expression.
3117
3118        Examples:
3119            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3120            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3121
3122        Args:
3123            hints: The SQL code strings to parse as the hints.
3124                If an `Expression` instance is passed, it will be used as-is.
3125            dialect: The dialect used to parse the hints.
3126            copy: If `False`, modify this expression instance in-place.
3127
3128        Returns:
3129            The modified expression.
3130        """
3131        inst = _maybe_copy(self, copy)
3132        inst.set(
3133            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3134        )
3135
3136        return inst
3137
3138    @property
3139    def named_selects(self) -> t.List[str]:
3140        return [e.output_name for e in self.expressions if e.alias_or_name]
3141
3142    @property
3143    def is_star(self) -> bool:
3144        return any(expression.is_star for expression in self.expressions)
3145
3146    @property
3147    def selects(self) -> t.List[Expression]:
3148        return self.expressions
3149
3150
3151class Subquery(DerivedTable, Unionable):
3152    arg_types = {
3153        "this": True,
3154        "alias": False,
3155        "with": False,
3156        **QUERY_MODIFIERS,
3157    }
3158
3159    def unnest(self):
3160        """
3161        Returns the first non subquery.
3162        """
3163        expression = self
3164        while isinstance(expression, Subquery):
3165            expression = expression.this
3166        return expression
3167
3168    @property
3169    def is_star(self) -> bool:
3170        return self.this.is_star
3171
3172    @property
3173    def output_name(self) -> str:
3174        return self.alias
3175
3176
3177class TableSample(Expression):
3178    arg_types = {
3179        "this": False,
3180        "method": False,
3181        "bucket_numerator": False,
3182        "bucket_denominator": False,
3183        "bucket_field": False,
3184        "percent": False,
3185        "rows": False,
3186        "size": False,
3187        "seed": False,
3188        "kind": False,
3189    }
3190
3191
3192class Tag(Expression):
3193    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3194
3195    arg_types = {
3196        "this": False,
3197        "prefix": False,
3198        "postfix": False,
3199    }
3200
3201
3202# Represents both the standard SQL PIVOT operator and DuckDB's "simplified" PIVOT syntax
3203# https://duckdb.org/docs/sql/statements/pivot
3204class Pivot(Expression):
3205    arg_types = {
3206        "this": False,
3207        "alias": False,
3208        "expressions": True,
3209        "field": False,
3210        "unpivot": False,
3211        "using": False,
3212        "group": False,
3213        "columns": False,
3214    }
3215
3216
3217class Window(Expression):
3218    arg_types = {
3219        "this": True,
3220        "partition_by": False,
3221        "order": False,
3222        "spec": False,
3223        "alias": False,
3224        "over": False,
3225        "first": False,
3226    }
3227
3228
3229class WindowSpec(Expression):
3230    arg_types = {
3231        "kind": False,
3232        "start": False,
3233        "start_side": False,
3234        "end": False,
3235        "end_side": False,
3236    }
3237
3238
3239class Where(Expression):
3240    pass
3241
3242
3243class Star(Expression):
3244    arg_types = {"except": False, "replace": False}
3245
3246    @property
3247    def name(self) -> str:
3248        return "*"
3249
3250    @property
3251    def output_name(self) -> str:
3252        return self.name
3253
3254
3255class Parameter(Condition):
3256    arg_types = {"this": True, "wrapped": False}
3257
3258
3259class SessionParameter(Condition):
3260    arg_types = {"this": True, "kind": False}
3261
3262
3263class Placeholder(Condition):
3264    arg_types = {"this": False, "kind": False}
3265
3266
3267class Null(Condition):
3268    arg_types: t.Dict[str, t.Any] = {}
3269
3270    @property
3271    def name(self) -> str:
3272        return "NULL"
3273
3274
3275class Boolean(Condition):
3276    pass
3277
3278
3279class DataTypeSize(Expression):
3280    arg_types = {"this": True, "expression": False}
3281
3282
3283class DataType(Expression):
3284    arg_types = {
3285        "this": True,
3286        "expressions": False,
3287        "nested": False,
3288        "values": False,
3289        "prefix": False,
3290    }
3291
3292    class Type(AutoName):
3293        ARRAY = auto()
3294        BIGDECIMAL = auto()
3295        BIGINT = auto()
3296        BIGSERIAL = auto()
3297        BINARY = auto()
3298        BIT = auto()
3299        BOOLEAN = auto()
3300        CHAR = auto()
3301        DATE = auto()
3302        DATETIME = auto()
3303        DATETIME64 = auto()
3304        ENUM = auto()
3305        INT4RANGE = auto()
3306        INT4MULTIRANGE = auto()
3307        INT8RANGE = auto()
3308        INT8MULTIRANGE = auto()
3309        NUMRANGE = auto()
3310        NUMMULTIRANGE = auto()
3311        TSRANGE = auto()
3312        TSMULTIRANGE = auto()
3313        TSTZRANGE = auto()
3314        TSTZMULTIRANGE = auto()
3315        DATERANGE = auto()
3316        DATEMULTIRANGE = auto()
3317        DECIMAL = auto()
3318        DOUBLE = auto()
3319        FLOAT = auto()
3320        GEOGRAPHY = auto()
3321        GEOMETRY = auto()
3322        HLLSKETCH = auto()
3323        HSTORE = auto()
3324        IMAGE = auto()
3325        INET = auto()
3326        INT = auto()
3327        INT128 = auto()
3328        INT256 = auto()
3329        INTERVAL = auto()
3330        JSON = auto()
3331        JSONB = auto()
3332        LONGBLOB = auto()
3333        LONGTEXT = auto()
3334        MAP = auto()
3335        MEDIUMBLOB = auto()
3336        MEDIUMTEXT = auto()
3337        MONEY = auto()
3338        NCHAR = auto()
3339        NULL = auto()
3340        NULLABLE = auto()
3341        NVARCHAR = auto()
3342        OBJECT = auto()
3343        ROWVERSION = auto()
3344        SERIAL = auto()
3345        SET = auto()
3346        SMALLINT = auto()
3347        SMALLMONEY = auto()
3348        SMALLSERIAL = auto()
3349        STRUCT = auto()
3350        SUPER = auto()
3351        TEXT = auto()
3352        TIME = auto()
3353        TIMESTAMP = auto()
3354        TIMESTAMPTZ = auto()
3355        TIMESTAMPLTZ = auto()
3356        TINYINT = auto()
3357        UBIGINT = auto()
3358        UINT = auto()
3359        USMALLINT = auto()
3360        UTINYINT = auto()
3361        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3362        UINT128 = auto()
3363        UINT256 = auto()
3364        UNIQUEIDENTIFIER = auto()
3365        USERDEFINED = "USER-DEFINED"
3366        UUID = auto()
3367        VARBINARY = auto()
3368        VARCHAR = auto()
3369        VARIANT = auto()
3370        XML = auto()
3371
3372    TEXT_TYPES = {
3373        Type.CHAR,
3374        Type.NCHAR,
3375        Type.VARCHAR,
3376        Type.NVARCHAR,
3377        Type.TEXT,
3378    }
3379
3380    INTEGER_TYPES = {
3381        Type.INT,
3382        Type.TINYINT,
3383        Type.SMALLINT,
3384        Type.BIGINT,
3385        Type.INT128,
3386        Type.INT256,
3387    }
3388
3389    FLOAT_TYPES = {
3390        Type.FLOAT,
3391        Type.DOUBLE,
3392    }
3393
3394    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3395
3396    TEMPORAL_TYPES = {
3397        Type.TIME,
3398        Type.TIMESTAMP,
3399        Type.TIMESTAMPTZ,
3400        Type.TIMESTAMPLTZ,
3401        Type.DATE,
3402        Type.DATETIME,
3403        Type.DATETIME64,
3404    }
3405
3406    META_TYPES = {"UNKNOWN", "NULL"}
3407
3408    @classmethod
3409    def build(
3410        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3411    ) -> DataType:
3412        from sqlglot import parse_one
3413
3414        if isinstance(dtype, str):
3415            upper = dtype.upper()
3416            if upper in DataType.META_TYPES:
3417                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3418            else:
3419                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3420
3421            if data_type_exp is None:
3422                raise ValueError(f"Unparsable data type value: {dtype}")
3423        elif isinstance(dtype, DataType.Type):
3424            data_type_exp = DataType(this=dtype)
3425        elif isinstance(dtype, DataType):
3426            return dtype
3427        else:
3428            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3429
3430        return DataType(**{**data_type_exp.args, **kwargs})
3431
3432    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3433        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
3434
3435
3436# https://www.postgresql.org/docs/15/datatype-pseudo.html
3437class PseudoType(Expression):
3438    pass
3439
3440
3441# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
3442class SubqueryPredicate(Predicate):
3443    pass
3444
3445
3446class All(SubqueryPredicate):
3447    pass
3448
3449
3450class Any(SubqueryPredicate):
3451    pass
3452
3453
3454class Exists(SubqueryPredicate):
3455    pass
3456
3457
3458# Commands to interact with the databases or engines. For most of the command
3459# expressions we parse whatever comes after the command's name as a string.
3460class Command(Expression):
3461    arg_types = {"this": True, "expression": False}
3462
3463
3464class Transaction(Expression):
3465    arg_types = {"this": False, "modes": False}
3466
3467
3468class Commit(Expression):
3469    arg_types = {"chain": False}
3470
3471
3472class Rollback(Expression):
3473    arg_types = {"savepoint": False}
3474
3475
3476class AlterTable(Expression):
3477    arg_types = {"this": True, "actions": True, "exists": False}
3478
3479
3480class AddConstraint(Expression):
3481    arg_types = {"this": False, "expression": False, "enforced": False}
3482
3483
3484class DropPartition(Expression):
3485    arg_types = {"expressions": True, "exists": False}
3486
3487
3488# Binary expressions like (ADD a b)
3489class Binary(Condition):
3490    arg_types = {"this": True, "expression": True}
3491
3492    @property
3493    def left(self):
3494        return self.this
3495
3496    @property
3497    def right(self):
3498        return self.expression
3499
3500
3501class Add(Binary):
3502    pass
3503
3504
3505class Connector(Binary):
3506    pass
3507
3508
3509class And(Connector):
3510    pass
3511
3512
3513class Or(Connector):
3514    pass
3515
3516
3517class BitwiseAnd(Binary):
3518    pass
3519
3520
3521class BitwiseLeftShift(Binary):
3522    pass
3523
3524
3525class BitwiseOr(Binary):
3526    pass
3527
3528
3529class BitwiseRightShift(Binary):
3530    pass
3531
3532
3533class BitwiseXor(Binary):
3534    pass
3535
3536
3537class Div(Binary):
3538    pass
3539
3540
3541class Overlaps(Binary):
3542    pass
3543
3544
3545class Dot(Binary):
3546    @property
3547    def name(self) -> str:
3548        return self.expression.name
3549
3550    @property
3551    def output_name(self) -> str:
3552        return self.name
3553
3554    @classmethod
3555    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3556        """Build a Dot object with a sequence of expressions."""
3557        if len(expressions) < 2:
3558            raise ValueError(f"Dot requires >= 2 expressions.")
3559
3560        a, b, *expressions = expressions
3561        dot = Dot(this=a, expression=b)
3562
3563        for expression in expressions:
3564            dot = Dot(this=dot, expression=expression)
3565
3566        return dot
3567
3568
3569class DPipe(Binary):
3570    pass
3571
3572
3573class SafeDPipe(DPipe):
3574    pass
3575
3576
3577class EQ(Binary, Predicate):
3578    pass
3579
3580
3581class NullSafeEQ(Binary, Predicate):
3582    pass
3583
3584
3585class NullSafeNEQ(Binary, Predicate):
3586    pass
3587
3588
3589class Distance(Binary):
3590    pass
3591
3592
3593class Escape(Binary):
3594    pass
3595
3596
3597class Glob(Binary, Predicate):
3598    pass
3599
3600
3601class GT(Binary, Predicate):
3602    pass
3603
3604
3605class GTE(Binary, Predicate):
3606    pass
3607
3608
3609class ILike(Binary, Predicate):
3610    pass
3611
3612
3613class ILikeAny(Binary, Predicate):
3614    pass
3615
3616
3617class IntDiv(Binary):
3618    pass
3619
3620
3621class Is(Binary, Predicate):
3622    pass
3623
3624
3625class Kwarg(Binary):
3626    """Kwarg in special functions like func(kwarg => y)."""
3627
3628
3629class Like(Binary, Predicate):
3630    pass
3631
3632
3633class LikeAny(Binary, Predicate):
3634    pass
3635
3636
3637class LT(Binary, Predicate):
3638    pass
3639
3640
3641class LTE(Binary, Predicate):
3642    pass
3643
3644
3645class Mod(Binary):
3646    pass
3647
3648
3649class Mul(Binary):
3650    pass
3651
3652
3653class NEQ(Binary, Predicate):
3654    pass
3655
3656
3657class SimilarTo(Binary, Predicate):
3658    pass
3659
3660
3661class Slice(Binary):
3662    arg_types = {"this": False, "expression": False}
3663
3664
3665class Sub(Binary):
3666    pass
3667
3668
3669class ArrayOverlaps(Binary):
3670    pass
3671
3672
3673# Unary Expressions
3674# (NOT a)
3675class Unary(Condition):
3676    pass
3677
3678
3679class BitwiseNot(Unary):
3680    pass
3681
3682
3683class Not(Unary):
3684    pass
3685
3686
3687class Paren(Unary):
3688    arg_types = {"this": True, "with": False}
3689
3690    @property
3691    def output_name(self) -> str:
3692        return self.this.name
3693
3694
3695class Neg(Unary):
3696    pass
3697
3698
3699class Alias(Expression):
3700    arg_types = {"this": True, "alias": False}
3701
3702    @property
3703    def output_name(self) -> str:
3704        return self.alias
3705
3706
3707class Aliases(Expression):
3708    arg_types = {"this": True, "expressions": True}
3709
3710    @property
3711    def aliases(self):
3712        return self.expressions
3713
3714
3715class AtTimeZone(Expression):
3716    arg_types = {"this": True, "zone": True}
3717
3718
3719class Between(Predicate):
3720    arg_types = {"this": True, "low": True, "high": True}
3721
3722
3723class Bracket(Condition):
3724    arg_types = {"this": True, "expressions": True}
3725
3726
3727class SafeBracket(Bracket):
3728    """Represents array lookup where OOB index yields NULL instead of causing a failure."""
3729
3730
3731class Distinct(Expression):
3732    arg_types = {"expressions": False, "on": False}
3733
3734
3735class In(Predicate):
3736    arg_types = {
3737        "this": True,
3738        "expressions": False,
3739        "query": False,
3740        "unnest": False,
3741        "field": False,
3742        "is_global": False,
3743    }
3744
3745
3746class TimeUnit(Expression):
3747    """Automatically converts unit arg into a var."""
3748
3749    arg_types = {"unit": False}
3750
3751    def __init__(self, **args):
3752        unit = args.get("unit")
3753        if isinstance(unit, (Column, Literal)):
3754            args["unit"] = Var(this=unit.name)
3755        elif isinstance(unit, Week):
3756            unit.set("this", Var(this=unit.this.name))
3757
3758        super().__init__(**args)
3759
3760
3761class Interval(TimeUnit):
3762    arg_types = {"this": False, "unit": False}
3763
3764    @property
3765    def unit(self) -> t.Optional[Var]:
3766        return self.args.get("unit")
3767
3768
3769class IgnoreNulls(Expression):
3770    pass
3771
3772
3773class RespectNulls(Expression):
3774    pass
3775
3776
3777# Functions
3778class Func(Condition):
3779    """
3780    The base class for all function expressions.
3781
3782    Attributes:
3783        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3784            treated as a variable length argument and the argument's value will be stored as a list.
3785        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3786            for this function expression. These values are used to map this node to a name during parsing
3787            as well as to provide the function's name during SQL string generation. By default the SQL
3788            name is set to the expression's class name transformed to snake case.
3789    """
3790
3791    is_var_len_args = False
3792
3793    @classmethod
3794    def from_arg_list(cls, args):
3795        if cls.is_var_len_args:
3796            all_arg_keys = list(cls.arg_types)
3797            # If this function supports variable length argument treat the last argument as such.
3798            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3799            num_non_var = len(non_var_len_arg_keys)
3800
3801            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3802            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3803        else:
3804            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3805
3806        return cls(**args_dict)
3807
3808    @classmethod
3809    def sql_names(cls):
3810        if cls is Func:
3811            raise NotImplementedError(
3812                "SQL name is only supported by concrete function implementations"
3813            )
3814        if "_sql_names" not in cls.__dict__:
3815            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3816        return cls._sql_names
3817
3818    @classmethod
3819    def sql_name(cls):
3820        return cls.sql_names()[0]
3821
3822    @classmethod
3823    def default_parser_mappings(cls):
3824        return {name: cls.from_arg_list for name in cls.sql_names()}
3825
3826
3827class AggFunc(Func):
3828    pass
3829
3830
3831class ParameterizedAgg(AggFunc):
3832    arg_types = {"this": True, "expressions": True, "params": True}
3833
3834
3835class Abs(Func):
3836    pass
3837
3838
3839class Anonymous(Func):
3840    arg_types = {"this": True, "expressions": False}
3841    is_var_len_args = True
3842
3843
3844# https://docs.snowflake.com/en/sql-reference/functions/hll
3845# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3846class Hll(AggFunc):
3847    arg_types = {"this": True, "expressions": False}
3848    is_var_len_args = True
3849
3850
3851class ApproxDistinct(AggFunc):
3852    arg_types = {"this": True, "accuracy": False}
3853    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
3854
3855
3856class Array(Func):
3857    arg_types = {"expressions": False}
3858    is_var_len_args = True
3859
3860
3861# https://docs.snowflake.com/en/sql-reference/functions/to_char
3862class ToChar(Func):
3863    arg_types = {"this": True, "format": False}
3864
3865
3866class GenerateSeries(Func):
3867    arg_types = {"start": True, "end": True, "step": False}
3868
3869
3870class ArrayAgg(AggFunc):
3871    pass
3872
3873
3874class ArrayAll(Func):
3875    arg_types = {"this": True, "expression": True}
3876
3877
3878class ArrayAny(Func):
3879    arg_types = {"this": True, "expression": True}
3880
3881
3882class ArrayConcat(Func):
3883    arg_types = {"this": True, "expressions": False}
3884    is_var_len_args = True
3885
3886
3887class ArrayContains(Binary, Func):
3888    pass
3889
3890
3891class ArrayContained(Binary):
3892    pass
3893
3894
3895class ArrayFilter(Func):
3896    arg_types = {"this": True, "expression": True}
3897    _sql_names = ["FILTER", "ARRAY_FILTER"]
3898
3899
3900class ArrayJoin(Func):
3901    arg_types = {"this": True, "expression": True, "null": False}
3902
3903
3904class ArraySize(Func):
3905    arg_types = {"this": True, "expression": False}
3906
3907
3908class ArraySort(Func):
3909    arg_types = {"this": True, "expression": False}
3910
3911
3912class ArraySum(Func):
3913    pass
3914
3915
3916class ArrayUnionAgg(AggFunc):
3917    pass
3918
3919
3920class Avg(AggFunc):
3921    pass
3922
3923
3924class AnyValue(AggFunc):
3925    arg_types = {"this": True, "having": False, "max": False}
3926
3927
3928class Case(Func):
3929    arg_types = {"this": False, "ifs": True, "default": False}
3930
3931    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3932        instance = _maybe_copy(self, copy)
3933        instance.append(
3934            "ifs",
3935            If(
3936                this=maybe_parse(condition, copy=copy, **opts),
3937                true=maybe_parse(then, copy=copy, **opts),
3938            ),
3939        )
3940        return instance
3941
3942    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3943        instance = _maybe_copy(self, copy)
3944        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3945        return instance
3946
3947
3948class Cast(Func):
3949    arg_types = {"this": True, "to": True, "format": False}
3950
3951    @property
3952    def name(self) -> str:
3953        return self.this.name
3954
3955    @property
3956    def to(self) -> DataType:
3957        return self.args["to"]
3958
3959    @property
3960    def output_name(self) -> str:
3961        return self.name
3962
3963    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3964        return self.to.is_type(*dtypes)
3965
3966
3967class CastToStrType(Func):
3968    arg_types = {"this": True, "expression": True}
3969
3970
3971class Collate(Binary):
3972    pass
3973
3974
3975class TryCast(Cast):
3976    pass
3977
3978
3979class Ceil(Func):
3980    arg_types = {"this": True, "decimals": False}
3981    _sql_names = ["CEIL", "CEILING"]
3982
3983
3984class Coalesce(Func):
3985    arg_types = {"this": True, "expressions": False}
3986    is_var_len_args = True
3987    _sql_names = ["COALESCE", "IFNULL", "NVL"]
3988
3989
3990class Concat(Func):
3991    arg_types = {"expressions": True}
3992    is_var_len_args = True
3993
3994
3995class SafeConcat(Concat):
3996    pass
3997
3998
3999class ConcatWs(Concat):
4000    _sql_names = ["CONCAT_WS"]
4001
4002
4003class Count(AggFunc):
4004    arg_types = {"this": False, "expressions": False}
4005    is_var_len_args = True
4006
4007
4008class CountIf(AggFunc):
4009    pass
4010
4011
4012class CurrentDate(Func):
4013    arg_types = {"this": False}
4014
4015
4016class CurrentDatetime(Func):
4017    arg_types = {"this": False}
4018
4019
4020class CurrentTime(Func):
4021    arg_types = {"this": False}
4022
4023
4024class CurrentTimestamp(Func):
4025    arg_types = {"this": False}
4026
4027
4028class CurrentUser(Func):
4029    arg_types = {"this": False}
4030
4031
4032class DateAdd(Func, TimeUnit):
4033    arg_types = {"this": True, "expression": True, "unit": False}
4034
4035
4036class DateSub(Func, TimeUnit):
4037    arg_types = {"this": True, "expression": True, "unit": False}
4038
4039
4040class DateDiff(Func, TimeUnit):
4041    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4042    arg_types = {"this": True, "expression": True, "unit": False}
4043
4044
4045class DateTrunc(Func):
4046    arg_types = {"unit": True, "this": True, "zone": False}
4047
4048
4049class DatetimeAdd(Func, TimeUnit):
4050    arg_types = {"this": True, "expression": True, "unit": False}
4051
4052
4053class DatetimeSub(Func, TimeUnit):
4054    arg_types = {"this": True, "expression": True, "unit": False}
4055
4056
4057class DatetimeDiff(Func, TimeUnit):
4058    arg_types = {"this": True, "expression": True, "unit": False}
4059
4060
4061class DatetimeTrunc(Func, TimeUnit):
4062    arg_types = {"this": True, "unit": True, "zone": False}
4063
4064
4065class DayOfWeek(Func):
4066    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
4067
4068
4069class DayOfMonth(Func):
4070    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
4071
4072
4073class DayOfYear(Func):
4074    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
4075
4076
4077class WeekOfYear(Func):
4078    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
4079
4080
4081class LastDateOfMonth(Func):
4082    pass
4083
4084
4085class Extract(Func):
4086    arg_types = {"this": True, "expression": True}
4087
4088
4089class TimestampAdd(Func, TimeUnit):
4090    arg_types = {"this": True, "expression": True, "unit": False}
4091
4092
4093class TimestampSub(Func, TimeUnit):
4094    arg_types = {"this": True, "expression": True, "unit": False}
4095
4096
4097class TimestampDiff(Func, TimeUnit):
4098    arg_types = {"this": True, "expression": True, "unit": False}
4099
4100
4101class TimestampTrunc(Func, TimeUnit):
4102    arg_types = {"this": True, "unit": True, "zone": False}
4103
4104
4105class TimeAdd(Func, TimeUnit):
4106    arg_types = {"this": True, "expression": True, "unit": False}
4107
4108
4109class TimeSub(Func, TimeUnit):
4110    arg_types = {"this": True, "expression": True, "unit": False}
4111
4112
4113class TimeDiff(Func, TimeUnit):
4114    arg_types = {"this": True, "expression": True, "unit": False}
4115
4116
4117class TimeTrunc(Func, TimeUnit):
4118    arg_types = {"this": True, "unit": True, "zone": False}
4119
4120
4121class DateFromParts(Func):
4122    _sql_names = ["DATEFROMPARTS"]
4123    arg_types = {"year": True, "month": True, "day": True}
4124
4125
4126class DateStrToDate(Func):
4127    pass
4128
4129
4130class DateToDateStr(Func):
4131    pass
4132
4133
4134class DateToDi(Func):
4135    pass
4136
4137
4138class Date(Func):
4139    arg_types = {"expressions": True}
4140    is_var_len_args = True
4141
4142
4143class Day(Func):
4144    pass
4145
4146
4147class Decode(Func):
4148    arg_types = {"this": True, "charset": True, "replace": False}
4149
4150
4151class DiToDate(Func):
4152    pass
4153
4154
4155class Encode(Func):
4156    arg_types = {"this": True, "charset": True}
4157
4158
4159class Exp(Func):
4160    pass
4161
4162
4163class Explode(Func):
4164    pass
4165
4166
4167class Floor(Func):
4168    arg_types = {"this": True, "decimals": False}
4169
4170
4171class FromBase64(Func):
4172    pass
4173
4174
4175class ToBase64(Func):
4176    pass
4177
4178
4179class Greatest(Func):
4180    arg_types = {"this": True, "expressions": False}
4181    is_var_len_args = True
4182
4183
4184class GroupConcat(Func):
4185    arg_types = {"this": True, "separator": False}
4186
4187
4188class Hex(Func):
4189    pass
4190
4191
4192class If(Func):
4193    arg_types = {"this": True, "true": True, "false": False}
4194
4195
4196class Initcap(Func):
4197    arg_types = {"this": True, "expression": False}
4198
4199
4200class JSONKeyValue(Expression):
4201    arg_types = {"this": True, "expression": True}
4202
4203
4204class JSONObject(Func):
4205    arg_types = {
4206        "expressions": False,
4207        "null_handling": False,
4208        "unique_keys": False,
4209        "return_type": False,
4210        "format_json": False,
4211        "encoding": False,
4212    }
4213
4214
4215class OpenJSONColumnDef(Expression):
4216    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
4217
4218
4219class OpenJSON(Func):
4220    arg_types = {"this": True, "path": False, "expressions": False}
4221
4222
4223class JSONBContains(Binary):
4224    _sql_names = ["JSONB_CONTAINS"]
4225
4226
4227class JSONExtract(Binary, Func):
4228    _sql_names = ["JSON_EXTRACT"]
4229
4230
4231class JSONExtractScalar(JSONExtract):
4232    _sql_names = ["JSON_EXTRACT_SCALAR"]
4233
4234
4235class JSONBExtract(JSONExtract):
4236    _sql_names = ["JSONB_EXTRACT"]
4237
4238
4239class JSONBExtractScalar(JSONExtract):
4240    _sql_names = ["JSONB_EXTRACT_SCALAR"]
4241
4242
4243class JSONFormat(Func):
4244    arg_types = {"this": False, "options": False}
4245    _sql_names = ["JSON_FORMAT"]
4246
4247
4248class Least(Func):
4249    arg_types = {"expressions": False}
4250    is_var_len_args = True
4251
4252
4253class Left(Func):
4254    arg_types = {"this": True, "expression": True}
4255
4256
4257class Right(Func):
4258    arg_types = {"this": True, "expression": True}
4259
4260
4261class Length(Func):
4262    _sql_names = ["LENGTH", "LEN"]
4263
4264
4265class Levenshtein(Func):
4266    arg_types = {
4267        "this": True,
4268        "expression": False,
4269        "ins_cost": False,
4270        "del_cost": False,
4271        "sub_cost": False,
4272    }
4273
4274
4275class Ln(Func):
4276    pass
4277
4278
4279class Log(Func):
4280    arg_types = {"this": True, "expression": False}
4281
4282
4283class Log2(Func):
4284    pass
4285
4286
4287class Log10(Func):
4288    pass
4289
4290
4291class LogicalOr(AggFunc):
4292    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
4293
4294
4295class LogicalAnd(AggFunc):
4296    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
4297
4298
4299class Lower(Func):
4300    _sql_names = ["LOWER", "LCASE"]
4301
4302
4303class Map(Func):
4304    arg_types = {"keys": False, "values": False}
4305
4306
4307class MapFromEntries(Func):
4308    pass
4309
4310
4311class StarMap(Func):
4312    pass
4313
4314
4315class VarMap(Func):
4316    arg_types = {"keys": True, "values": True}
4317    is_var_len_args = True
4318
4319    @property
4320    def keys(self) -> t.List[Expression]:
4321        return self.args["keys"].expressions
4322
4323    @property
4324    def values(self) -> t.List[Expression]:
4325        return self.args["values"].expressions
4326
4327
4328# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
4329class MatchAgainst(Func):
4330    arg_types = {"this": True, "expressions": True, "modifier": False}
4331
4332
4333class Max(AggFunc):
4334    arg_types = {"this": True, "expressions": False}
4335    is_var_len_args = True
4336
4337
4338class MD5(Func):
4339    _sql_names = ["MD5"]
4340
4341
4342class Min(AggFunc):
4343    arg_types = {"this": True, "expressions": False}
4344    is_var_len_args = True
4345
4346
4347class Month(Func):
4348    pass
4349
4350
4351class Nvl2(Func):
4352    arg_types = {"this": True, "true": True, "false": False}
4353
4354
4355class Posexplode(Func):
4356    pass
4357
4358
4359class Pow(Binary, Func):
4360    _sql_names = ["POWER", "POW"]
4361
4362
4363class PercentileCont(AggFunc):
4364    arg_types = {"this": True, "expression": False}
4365
4366
4367class PercentileDisc(AggFunc):
4368    arg_types = {"this": True, "expression": False}
4369
4370
4371class Quantile(AggFunc):
4372    arg_types = {"this": True, "quantile": True}
4373
4374
4375class ApproxQuantile(Quantile):
4376    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
4377
4378
4379class RangeN(Func):
4380    arg_types = {"this": True, "expressions": True, "each": False}
4381
4382
4383class ReadCSV(Func):
4384    _sql_names = ["READ_CSV"]
4385    is_var_len_args = True
4386    arg_types = {"this": True, "expressions": False}
4387
4388
4389class Reduce(Func):
4390    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
4391
4392
4393class RegexpExtract(Func):
4394    arg_types = {
4395        "this": True,
4396        "expression": True,
4397        "position": False,
4398        "occurrence": False,
4399        "group": False,
4400    }
4401
4402
4403class RegexpLike(Func):
4404    arg_types = {"this": True, "expression": True, "flag": False}
4405
4406
4407class RegexpILike(Func):
4408    arg_types = {"this": True, "expression": True, "flag": False}
4409
4410
4411# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
4412# limit is the number of times a pattern is applied
4413class RegexpSplit(Func):
4414    arg_types = {"this": True, "expression": True, "limit": False}
4415
4416
4417class Repeat(Func):
4418    arg_types = {"this": True, "times": True}
4419
4420
4421class Round(Func):
4422    arg_types = {"this": True, "decimals": False}
4423
4424
4425class RowNumber(Func):
4426    arg_types: t.Dict[str, t.Any] = {}
4427
4428
4429class SafeDivide(Func):
4430    arg_types = {"this": True, "expression": True}
4431
4432
4433class SetAgg(AggFunc):
4434    pass
4435
4436
4437class SHA(Func):
4438    _sql_names = ["SHA", "SHA1"]
4439
4440
4441class SHA2(Func):
4442    _sql_names = ["SHA2"]
4443    arg_types = {"this": True, "length": False}
4444
4445
4446class SortArray(Func):
4447    arg_types = {"this": True, "asc": False}
4448
4449
4450class Split(Func):
4451    arg_types = {"this": True, "expression": True, "limit": False}
4452
4453
4454# Start may be omitted in the case of postgres
4455# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
4456class Substring(Func):
4457    arg_types = {"this": True, "start": False, "length": False}
4458
4459
4460class StandardHash(Func):
4461    arg_types = {"this": True, "expression": False}
4462
4463
4464class StrPosition(Func):
4465    arg_types = {
4466        "this": True,
4467        "substr": True,
4468        "position": False,
4469        "instance": False,
4470    }
4471
4472
4473class StrToDate(Func):
4474    arg_types = {"this": True, "format": True}
4475
4476
4477class StrToTime(Func):
4478    arg_types = {"this": True, "format": True}
4479
4480
4481# Spark allows unix_timestamp()
4482# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
4483class StrToUnix(Func):
4484    arg_types = {"this": False, "format": False}
4485
4486
4487class NumberToStr(Func):
4488    arg_types = {"this": True, "format": True}
4489
4490
4491class FromBase(Func):
4492    arg_types = {"this": True, "expression": True}
4493
4494
4495class Struct(Func):
4496    arg_types = {"expressions": True}
4497    is_var_len_args = True
4498
4499
4500class StructExtract(Func):
4501    arg_types = {"this": True, "expression": True}
4502
4503
4504class Sum(AggFunc):
4505    pass
4506
4507
4508class Sqrt(Func):
4509    pass
4510
4511
4512class Stddev(AggFunc):
4513    pass
4514
4515
4516class StddevPop(AggFunc):
4517    pass
4518
4519
4520class StddevSamp(AggFunc):
4521    pass
4522
4523
4524class TimeToStr(Func):
4525    arg_types = {"this": True, "format": True}
4526
4527
4528class TimeToTimeStr(Func):
4529    pass
4530
4531
4532class TimeToUnix(Func):
4533    pass
4534
4535
4536class TimeStrToDate(Func):
4537    pass
4538
4539
4540class TimeStrToTime(Func):
4541    pass
4542
4543
4544class TimeStrToUnix(Func):
4545    pass
4546
4547
4548class Trim(Func):
4549    arg_types = {
4550        "this": True,
4551        "expression": False,
4552        "position": False,
4553        "collation": False,
4554    }
4555
4556
4557class TsOrDsAdd(Func, TimeUnit):
4558    arg_types = {"this": True, "expression": True, "unit": False}
4559
4560
4561class TsOrDsToDateStr(Func):
4562    pass
4563
4564
4565class TsOrDsToDate(Func):
4566    arg_types = {"this": True, "format": False}
4567
4568
4569class TsOrDiToDi(Func):
4570    pass
4571
4572
4573class Unhex(Func):
4574    pass
4575
4576
4577class UnixToStr(Func):
4578    arg_types = {"this": True, "format": False}
4579
4580
4581# https://prestodb.io/docs/current/functions/datetime.html
4582# presto has weird zone/hours/minutes
4583class UnixToTime(Func):
4584    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4585
4586    SECONDS = Literal.string("seconds")
4587    MILLIS = Literal.string("millis")
4588    MICROS = Literal.string("micros")
4589
4590
4591class UnixToTimeStr(Func):
4592    pass
4593
4594
4595class Upper(Func):
4596    _sql_names = ["UPPER", "UCASE"]
4597
4598
4599class Variance(AggFunc):
4600    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
4601
4602
4603class VariancePop(AggFunc):
4604    _sql_names = ["VARIANCE_POP", "VAR_POP"]
4605
4606
4607class Week(Func):
4608    arg_types = {"this": True, "mode": False}
4609
4610
4611class XMLTable(Func):
4612    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4613
4614
4615class Year(Func):
4616    pass
4617
4618
4619class Use(Expression):
4620    arg_types = {"this": True, "kind": False}
4621
4622
4623class Merge(Expression):
4624    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4625
4626
4627class When(Func):
4628    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4629
4630
4631# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html
4632# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16
4633class NextValueFor(Func):
4634    arg_types = {"this": True, "order": False}
4635
4636
4637def _norm_arg(arg):
4638    return arg.lower() if type(arg) is str else arg
4639
4640
4641ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4642
4643
4644# Helpers
4645@t.overload
4646def maybe_parse(
4647    sql_or_expression: ExpOrStr,
4648    *,
4649    into: t.Type[E],
4650    dialect: DialectType = None,
4651    prefix: t.Optional[str] = None,
4652    copy: bool = False,
4653    **opts,
4654) -> E:
4655    ...
4656
4657
4658@t.overload
4659def maybe_parse(
4660    sql_or_expression: str | E,
4661    *,
4662    into: t.Optional[IntoType] = None,
4663    dialect: DialectType = None,
4664    prefix: t.Optional[str] = None,
4665    copy: bool = False,
4666    **opts,
4667) -> E:
4668    ...
4669
4670
4671def maybe_parse(
4672    sql_or_expression: ExpOrStr,
4673    *,
4674    into: t.Optional[IntoType] = None,
4675    dialect: DialectType = None,
4676    prefix: t.Optional[str] = None,
4677    copy: bool = False,
4678    **opts,
4679) -> Expression:
4680    """Gracefully handle a possible string or expression.
4681
4682    Example:
4683        >>> maybe_parse("1")
4684        (LITERAL this: 1, is_string: False)
4685        >>> maybe_parse(to_identifier("x"))
4686        (IDENTIFIER this: x, quoted: False)
4687
4688    Args:
4689        sql_or_expression: the SQL code string or an expression
4690        into: the SQLGlot Expression to parse into
4691        dialect: the dialect used to parse the input expressions (in the case that an
4692            input expression is a SQL string).
4693        prefix: a string to prefix the sql with before it gets parsed
4694            (automatically includes a space)
4695        copy: whether or not to copy the expression.
4696        **opts: other options to use to parse the input expressions (again, in the case
4697            that an input expression is a SQL string).
4698
4699    Returns:
4700        Expression: the parsed or given expression.
4701    """
4702    if isinstance(sql_or_expression, Expression):
4703        if copy:
4704            return sql_or_expression.copy()
4705        return sql_or_expression
4706
4707    if sql_or_expression is None:
4708        raise ParseError(f"SQL cannot be None")
4709
4710    import sqlglot
4711
4712    sql = str(sql_or_expression)
4713    if prefix:
4714        sql = f"{prefix} {sql}"
4715
4716    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4717
4718
4719def _maybe_copy(instance: E, copy: bool = True) -> E:
4720    return instance.copy() if copy else instance
4721
4722
4723def _is_wrong_expression(expression, into):
4724    return isinstance(expression, Expression) and not isinstance(expression, into)
4725
4726
4727def _apply_builder(
4728    expression,
4729    instance,
4730    arg,
4731    copy=True,
4732    prefix=None,
4733    into=None,
4734    dialect=None,
4735    **opts,
4736):
4737    if _is_wrong_expression(expression, into):
4738        expression = into(this=expression)
4739    instance = _maybe_copy(instance, copy)
4740    expression = maybe_parse(
4741        sql_or_expression=expression,
4742        prefix=prefix,
4743        into=into,
4744        dialect=dialect,
4745        **opts,
4746    )
4747    instance.set(arg, expression)
4748    return instance
4749
4750
4751def _apply_child_list_builder(
4752    *expressions,
4753    instance,
4754    arg,
4755    append=True,
4756    copy=True,
4757    prefix=None,
4758    into=None,
4759    dialect=None,
4760    properties=None,
4761    **opts,
4762):
4763    instance = _maybe_copy(instance, copy)
4764    parsed = []
4765    for expression in expressions:
4766        if expression is not None:
4767            if _is_wrong_expression(expression, into):
4768                expression = into(expressions=[expression])
4769
4770            expression = maybe_parse(
4771                expression,
4772                into=into,
4773                dialect=dialect,
4774                prefix=prefix,
4775                **opts,
4776            )
4777            parsed.extend(expression.expressions)
4778
4779    existing = instance.args.get(arg)
4780    if append and existing:
4781        parsed = existing.expressions + parsed
4782
4783    child = into(expressions=parsed)
4784    for k, v in (properties or {}).items():
4785        child.set(k, v)
4786    instance.set(arg, child)
4787
4788    return instance
4789
4790
4791def _apply_list_builder(
4792    *expressions,
4793    instance,
4794    arg,
4795    append=True,
4796    copy=True,
4797    prefix=None,
4798    into=None,
4799    dialect=None,
4800    **opts,
4801):
4802    inst = _maybe_copy(instance, copy)
4803
4804    expressions = [
4805        maybe_parse(
4806            sql_or_expression=expression,
4807            into=into,
4808            prefix=prefix,
4809            dialect=dialect,
4810            **opts,
4811        )
4812        for expression in expressions
4813        if expression is not None
4814    ]
4815
4816    existing_expressions = inst.args.get(arg)
4817    if append and existing_expressions:
4818        expressions = existing_expressions + expressions
4819
4820    inst.set(arg, expressions)
4821    return inst
4822
4823
4824def _apply_conjunction_builder(
4825    *expressions,
4826    instance,
4827    arg,
4828    into=None,
4829    append=True,
4830    copy=True,
4831    dialect=None,
4832    **opts,
4833):
4834    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4835    if not expressions:
4836        return instance
4837
4838    inst = _maybe_copy(instance, copy)
4839
4840    existing = inst.args.get(arg)
4841    if append and existing is not None:
4842        expressions = [existing.this if into else existing] + list(expressions)
4843
4844    node = and_(*expressions, dialect=dialect, copy=copy, **opts)
4845
4846    inst.set(arg, into(this=node) if into else node)
4847    return inst
4848
4849
4850def _apply_cte_builder(
4851    instance: E,
4852    alias: ExpOrStr,
4853    as_: ExpOrStr,
4854    recursive: t.Optional[bool] = None,
4855    append: bool = True,
4856    dialect: DialectType = None,
4857    copy: bool = True,
4858    **opts,
4859) -> E:
4860    alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts)
4861    as_expression = maybe_parse(as_, dialect=dialect, **opts)
4862    cte = CTE(this=as_expression, alias=alias_expression)
4863    return _apply_child_list_builder(
4864        cte,
4865        instance=instance,
4866        arg="with",
4867        append=append,
4868        copy=copy,
4869        into=With,
4870        properties={"recursive": recursive or False},
4871    )
4872
4873
4874def _combine(
4875    expressions: t.Sequence[t.Optional[ExpOrStr]],
4876    operator: t.Type[Connector],
4877    dialect: DialectType = None,
4878    copy: bool = True,
4879    **opts,
4880) -> Expression:
4881    conditions = [
4882        condition(expression, dialect=dialect, copy=copy, **opts)
4883        for expression in expressions
4884        if expression is not None
4885    ]
4886
4887    this, *rest = conditions
4888    if rest:
4889        this = _wrap(this, Connector)
4890    for expression in rest:
4891        this = operator(this=this, expression=_wrap(expression, Connector))
4892
4893    return this
4894
4895
4896def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:
4897    return Paren(this=expression) if isinstance(expression, kind) else expression
4898
4899
4900def union(
4901    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4902) -> Union:
4903    """
4904    Initializes a syntax tree from one UNION expression.
4905
4906    Example:
4907        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4908        'SELECT * FROM foo UNION SELECT * FROM bla'
4909
4910    Args:
4911        left: the SQL code string corresponding to the left-hand side.
4912            If an `Expression` instance is passed, it will be used as-is.
4913        right: the SQL code string corresponding to the right-hand side.
4914            If an `Expression` instance is passed, it will be used as-is.
4915        distinct: set the DISTINCT flag if and only if this is true.
4916        dialect: the dialect used to parse the input expression.
4917        opts: other options to use to parse the input expressions.
4918
4919    Returns:
4920        The new Union instance.
4921    """
4922    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4923    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4924
4925    return Union(this=left, expression=right, distinct=distinct)
4926
4927
4928def intersect(
4929    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4930) -> Intersect:
4931    """
4932    Initializes a syntax tree from one INTERSECT expression.
4933
4934    Example:
4935        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4936        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4937
4938    Args:
4939        left: the SQL code string corresponding to the left-hand side.
4940            If an `Expression` instance is passed, it will be used as-is.
4941        right: the SQL code string corresponding to the right-hand side.
4942            If an `Expression` instance is passed, it will be used as-is.
4943        distinct: set the DISTINCT flag if and only if this is true.
4944        dialect: the dialect used to parse the input expression.
4945        opts: other options to use to parse the input expressions.
4946
4947    Returns:
4948        The new Intersect instance.
4949    """
4950    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4951    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4952
4953    return Intersect(this=left, expression=right, distinct=distinct)
4954
4955
4956def except_(
4957    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4958) -> Except:
4959    """
4960    Initializes a syntax tree from one EXCEPT expression.
4961
4962    Example:
4963        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4964        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4965
4966    Args:
4967        left: the SQL code string corresponding to the left-hand side.
4968            If an `Expression` instance is passed, it will be used as-is.
4969        right: the SQL code string corresponding to the right-hand side.
4970            If an `Expression` instance is passed, it will be used as-is.
4971        distinct: set the DISTINCT flag if and only if this is true.
4972        dialect: the dialect used to parse the input expression.
4973        opts: other options to use to parse the input expressions.
4974
4975    Returns:
4976        The new Except instance.
4977    """
4978    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4979    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4980
4981    return Except(this=left, expression=right, distinct=distinct)
4982
4983
4984def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4985    """
4986    Initializes a syntax tree from one or multiple SELECT expressions.
4987
4988    Example:
4989        >>> select("col1", "col2").from_("tbl").sql()
4990        'SELECT col1, col2 FROM tbl'
4991
4992    Args:
4993        *expressions: the SQL code string to parse as the expressions of a
4994            SELECT statement. If an Expression instance is passed, this is used as-is.
4995        dialect: the dialect used to parse the input expressions (in the case that an
4996            input expression is a SQL string).
4997        **opts: other options to use to parse the input expressions (again, in the case
4998            that an input expression is a SQL string).
4999
5000    Returns:
5001        Select: the syntax tree for the SELECT statement.
5002    """
5003    return Select().select(*expressions, dialect=dialect, **opts)
5004
5005
5006def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5007    """
5008    Initializes a syntax tree from a FROM expression.
5009
5010    Example:
5011        >>> from_("tbl").select("col1", "col2").sql()
5012        'SELECT col1, col2 FROM tbl'
5013
5014    Args:
5015        *expression: the SQL code string to parse as the FROM expressions of a
5016            SELECT statement. If an Expression instance is passed, this is used as-is.
5017        dialect: the dialect used to parse the input expression (in the case that the
5018            input expression is a SQL string).
5019        **opts: other options to use to parse the input expressions (again, in the case
5020            that the input expression is a SQL string).
5021
5022    Returns:
5023        Select: the syntax tree for the SELECT statement.
5024    """
5025    return Select().from_(expression, dialect=dialect, **opts)
5026
5027
5028def update(
5029    table: str | Table,
5030    properties: dict,
5031    where: t.Optional[ExpOrStr] = None,
5032    from_: t.Optional[ExpOrStr] = None,
5033    dialect: DialectType = None,
5034    **opts,
5035) -> Update:
5036    """
5037    Creates an update statement.
5038
5039    Example:
5040        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5041        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5042
5043    Args:
5044        *properties: dictionary of properties to set which are
5045            auto converted to sql objects eg None -> NULL
5046        where: sql conditional parsed into a WHERE statement
5047        from_: sql statement parsed into a FROM statement
5048        dialect: the dialect used to parse the input expressions.
5049        **opts: other options to use to parse the input expressions.
5050
5051    Returns:
5052        Update: the syntax tree for the UPDATE statement.
5053    """
5054    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5055    update_expr.set(
5056        "expressions",
5057        [
5058            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5059            for k, v in properties.items()
5060        ],
5061    )
5062    if from_:
5063        update_expr.set(
5064            "from",
5065            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5066        )
5067    if isinstance(where, Condition):
5068        where = Where(this=where)
5069    if where:
5070        update_expr.set(
5071            "where",
5072            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5073        )
5074    return update_expr
5075
5076
5077def delete(
5078    table: ExpOrStr,
5079    where: t.Optional[ExpOrStr] = None,
5080    returning: t.Optional[ExpOrStr] = None,
5081    dialect: DialectType = None,
5082    **opts,
5083) -> Delete:
5084    """
5085    Builds a delete statement.
5086
5087    Example:
5088        >>> delete("my_table", where="id > 1").sql()
5089        'DELETE FROM my_table WHERE id > 1'
5090
5091    Args:
5092        where: sql conditional parsed into a WHERE statement
5093        returning: sql conditional parsed into a RETURNING statement
5094        dialect: the dialect used to parse the input expressions.
5095        **opts: other options to use to parse the input expressions.
5096
5097    Returns:
5098        Delete: the syntax tree for the DELETE statement.
5099    """
5100    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5101    if where:
5102        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5103    if returning:
5104        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5105    return delete_expr
5106
5107
5108def insert(
5109    expression: ExpOrStr,
5110    into: ExpOrStr,
5111    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5112    overwrite: t.Optional[bool] = None,
5113    dialect: DialectType = None,
5114    copy: bool = True,
5115    **opts,
5116) -> Insert:
5117    """
5118    Builds an INSERT statement.
5119
5120    Example:
5121        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5122        'INSERT INTO tbl VALUES (1, 2, 3)'
5123
5124    Args:
5125        expression: the sql string or expression of the INSERT statement
5126        into: the tbl to insert data to.
5127        columns: optionally the table's column names.
5128        overwrite: whether to INSERT OVERWRITE or not.
5129        dialect: the dialect used to parse the input expressions.
5130        copy: whether or not to copy the expression.
5131        **opts: other options to use to parse the input expressions.
5132
5133    Returns:
5134        Insert: the syntax tree for the INSERT statement.
5135    """
5136    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5137    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5138
5139    if columns:
5140        this = _apply_list_builder(
5141            *columns,
5142            instance=Schema(this=this),
5143            arg="expressions",
5144            into=Identifier,
5145            copy=False,
5146            dialect=dialect,
5147            **opts,
5148        )
5149
5150    return Insert(this=this, expression=expr, overwrite=overwrite)
5151
5152
5153def condition(
5154    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5155) -> Condition:
5156    """
5157    Initialize a logical condition expression.
5158
5159    Example:
5160        >>> condition("x=1").sql()
5161        'x = 1'
5162
5163        This is helpful for composing larger logical syntax trees:
5164        >>> where = condition("x=1")
5165        >>> where = where.and_("y=1")
5166        >>> Select().from_("tbl").select("*").where(where).sql()
5167        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5168
5169    Args:
5170        *expression: the SQL code string to parse.
5171            If an Expression instance is passed, this is used as-is.
5172        dialect: the dialect used to parse the input expression (in the case that the
5173            input expression is a SQL string).
5174        copy: Whether or not to copy `expression` (only applies to expressions).
5175        **opts: other options to use to parse the input expressions (again, in the case
5176            that the input expression is a SQL string).
5177
5178    Returns:
5179        The new Condition instance
5180    """
5181    return maybe_parse(
5182        expression,
5183        into=Condition,
5184        dialect=dialect,
5185        copy=copy,
5186        **opts,
5187    )
5188
5189
5190def and_(
5191    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5192) -> Condition:
5193    """
5194    Combine multiple conditions with an AND logical operator.
5195
5196    Example:
5197        >>> and_("x=1", and_("y=1", "z=1")).sql()
5198        'x = 1 AND (y = 1 AND z = 1)'
5199
5200    Args:
5201        *expressions: the SQL code strings to parse.
5202            If an Expression instance is passed, this is used as-is.
5203        dialect: the dialect used to parse the input expression.
5204        copy: whether or not to copy `expressions` (only applies to Expressions).
5205        **opts: other options to use to parse the input expressions.
5206
5207    Returns:
5208        And: the new condition
5209    """
5210    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))
5211
5212
5213def or_(
5214    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5215) -> Condition:
5216    """
5217    Combine multiple conditions with an OR logical operator.
5218
5219    Example:
5220        >>> or_("x=1", or_("y=1", "z=1")).sql()
5221        'x = 1 OR (y = 1 OR z = 1)'
5222
5223    Args:
5224        *expressions: the SQL code strings to parse.
5225            If an Expression instance is passed, this is used as-is.
5226        dialect: the dialect used to parse the input expression.
5227        copy: whether or not to copy `expressions` (only applies to Expressions).
5228        **opts: other options to use to parse the input expressions.
5229
5230    Returns:
5231        Or: the new condition
5232    """
5233    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))
5234
5235
5236def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5237    """
5238    Wrap a condition with a NOT operator.
5239
5240    Example:
5241        >>> not_("this_suit='black'").sql()
5242        "NOT this_suit = 'black'"
5243
5244    Args:
5245        expression: the SQL code string to parse.
5246            If an Expression instance is passed, this is used as-is.
5247        dialect: the dialect used to parse the input expression.
5248        copy: whether to copy the expression or not.
5249        **opts: other options to use to parse the input expressions.
5250
5251    Returns:
5252        The new condition.
5253    """
5254    this = condition(
5255        expression,
5256        dialect=dialect,
5257        copy=copy,
5258        **opts,
5259    )
5260    return Not(this=_wrap(this, Connector))
5261
5262
5263def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5264    """
5265    Wrap an expression in parentheses.
5266
5267    Example:
5268        >>> paren("5 + 3").sql()
5269        '(5 + 3)'
5270
5271    Args:
5272        expression: the SQL code string to parse.
5273            If an Expression instance is passed, this is used as-is.
5274        copy: whether to copy the expression or not.
5275
5276    Returns:
5277        The wrapped expression.
5278    """
5279    return Paren(this=maybe_parse(expression, copy=copy))
5280
5281
5282SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
5283
5284
5285@t.overload
5286def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None:
5287    ...
5288
5289
5290@t.overload
5291def to_identifier(
5292    name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True
5293) -> Identifier:
5294    ...
5295
5296
5297def to_identifier(name, quoted=None, copy=True):
5298    """Builds an identifier.
5299
5300    Args:
5301        name: The name to turn into an identifier.
5302        quoted: Whether or not force quote the identifier.
5303        copy: Whether or not to copy a passed in Identefier node.
5304
5305    Returns:
5306        The identifier ast node.
5307    """
5308
5309    if name is None:
5310        return None
5311
5312    if isinstance(name, Identifier):
5313        identifier = _maybe_copy(name, copy)
5314    elif isinstance(name, str):
5315        identifier = Identifier(
5316            this=name,
5317            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5318        )
5319    else:
5320        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5321    return identifier
5322
5323
5324INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
5325
5326
5327def to_interval(interval: str | Literal) -> Interval:
5328    """Builds an interval expression from a string like '1 day' or '5 months'."""
5329    if isinstance(interval, Literal):
5330        if not interval.is_string:
5331            raise ValueError("Invalid interval string.")
5332
5333        interval = interval.this
5334
5335    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5336
5337    if not interval_parts:
5338        raise ValueError("Invalid interval string.")
5339
5340    return Interval(
5341        this=Literal.string(interval_parts.group(1)),
5342        unit=Var(this=interval_parts.group(2)),
5343    )
5344
5345
5346@t.overload
5347def to_table(sql_path: str | Table, **kwargs) -> Table:
5348    ...
5349
5350
5351@t.overload
5352def to_table(sql_path: None, **kwargs) -> None:
5353    ...
5354
5355
5356def to_table(
5357    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5358) -> t.Optional[Table]:
5359    """
5360    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5361    If a table is passed in then that table is returned.
5362
5363    Args:
5364        sql_path: a `[catalog].[schema].[table]` string.
5365        dialect: the source dialect according to which the table name will be parsed.
5366        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5367
5368    Returns:
5369        A table expression.
5370    """
5371    if sql_path is None or isinstance(sql_path, Table):
5372        return sql_path
5373    if not isinstance(sql_path, str):
5374        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5375
5376    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5377    if table:
5378        for k, v in kwargs.items():
5379            table.set(k, v)
5380
5381    return table
5382
5383
5384def to_column(sql_path: str | Column, **kwargs) -> Column:
5385    """
5386    Create a column from a `[table].[column]` sql path. Schema is optional.
5387
5388    If a column is passed in then that column is returned.
5389
5390    Args:
5391        sql_path: `[table].[column]` string
5392    Returns:
5393        Table: A column expression
5394    """
5395    if sql_path is None or isinstance(sql_path, Column):
5396        return sql_path
5397    if not isinstance(sql_path, str):
5398        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5399    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
5400
5401
5402def alias_(
5403    expression: ExpOrStr,
5404    alias: str | Identifier,
5405    table: bool | t.Sequence[str | Identifier] = False,
5406    quoted: t.Optional[bool] = None,
5407    dialect: DialectType = None,
5408    copy: bool = True,
5409    **opts,
5410):
5411    """Create an Alias expression.
5412
5413    Example:
5414        >>> alias_('foo', 'bar').sql()
5415        'foo AS bar'
5416
5417        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5418        '(SELECT 1, 2) AS bar(a, b)'
5419
5420    Args:
5421        expression: the SQL code strings to parse.
5422            If an Expression instance is passed, this is used as-is.
5423        alias: the alias name to use. If the name has
5424            special characters it is quoted.
5425        table: Whether or not to create a table alias, can also be a list of columns.
5426        quoted: whether or not to quote the alias
5427        dialect: the dialect used to parse the input expression.
5428        copy: Whether or not to copy the expression.
5429        **opts: other options to use to parse the input expressions.
5430
5431    Returns:
5432        Alias: the aliased expression
5433    """
5434    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5435    alias = to_identifier(alias, quoted=quoted)
5436
5437    if table:
5438        table_alias = TableAlias(this=alias)
5439        exp.set("alias", table_alias)
5440
5441        if not isinstance(table, bool):
5442            for column in table:
5443                table_alias.append("columns", to_identifier(column, quoted=quoted))
5444
5445        return exp
5446
5447    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5448    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5449    # for the complete Window expression.
5450    #
5451    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5452
5453    if "alias" in exp.arg_types and not isinstance(exp, Window):
5454        exp.set("alias", alias)
5455        return exp
5456    return Alias(this=exp, alias=alias)
5457
5458
5459def subquery(
5460    expression: ExpOrStr,
5461    alias: t.Optional[Identifier | str] = None,
5462    dialect: DialectType = None,
5463    **opts,
5464) -> Select:
5465    """
5466    Build a subquery expression.
5467
5468    Example:
5469        >>> subquery('select x from tbl', 'bar').select('x').sql()
5470        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5471
5472    Args:
5473        expression: the SQL code strings to parse.
5474            If an Expression instance is passed, this is used as-is.
5475        alias: the alias name to use.
5476        dialect: the dialect used to parse the input expression.
5477        **opts: other options to use to parse the input expressions.
5478
5479    Returns:
5480        A new Select instance with the subquery expression included.
5481    """
5482
5483    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5484    return Select().from_(expression, dialect=dialect, **opts)
5485
5486
5487def column(
5488    col: str | Identifier,
5489    table: t.Optional[str | Identifier] = None,
5490    db: t.Optional[str | Identifier] = None,
5491    catalog: t.Optional[str | Identifier] = None,
5492    quoted: t.Optional[bool] = None,
5493) -> Column:
5494    """
5495    Build a Column.
5496
5497    Args:
5498        col: Column name.
5499        table: Table name.
5500        db: Database name.
5501        catalog: Catalog name.
5502        quoted: Whether to force quotes on the column's identifiers.
5503
5504    Returns:
5505        The new Column instance.
5506    """
5507    return Column(
5508        this=to_identifier(col, quoted=quoted),
5509        table=to_identifier(table, quoted=quoted),
5510        db=to_identifier(db, quoted=quoted),
5511        catalog=to_identifier(catalog, quoted=quoted),
5512    )
5513
5514
5515def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5516    """Cast an expression to a data type.
5517
5518    Example:
5519        >>> cast('x + 1', 'int').sql()
5520        'CAST(x + 1 AS INT)'
5521
5522    Args:
5523        expression: The expression to cast.
5524        to: The datatype to cast to.
5525
5526    Returns:
5527        The new Cast instance.
5528    """
5529    expression = maybe_parse(expression, **opts)
5530    return Cast(this=expression, to=DataType.build(to, **opts))
5531
5532
5533def table_(
5534    table: Identifier | str,
5535    db: t.Optional[Identifier | str] = None,
5536    catalog: t.Optional[Identifier | str] = None,
5537    quoted: t.Optional[bool] = None,
5538    alias: t.Optional[Identifier | str] = None,
5539) -> Table:
5540    """Build a Table.
5541
5542    Args:
5543        table: Table name.
5544        db: Database name.
5545        catalog: Catalog name.
5546        quote: Whether to force quotes on the table's identifiers.
5547        alias: Table's alias.
5548
5549    Returns:
5550        The new Table instance.
5551    """
5552    return Table(
5553        this=to_identifier(table, quoted=quoted),
5554        db=to_identifier(db, quoted=quoted),
5555        catalog=to_identifier(catalog, quoted=quoted),
5556        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5557    )
5558
5559
5560def values(
5561    values: t.Iterable[t.Tuple[t.Any, ...]],
5562    alias: t.Optional[str] = None,
5563    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5564) -> Values:
5565    """Build VALUES statement.
5566
5567    Example:
5568        >>> values([(1, '2')]).sql()
5569        "VALUES (1, '2')"
5570
5571    Args:
5572        values: values statements that will be converted to SQL
5573        alias: optional alias
5574        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5575         If either are provided then an alias is also required.
5576
5577    Returns:
5578        Values: the Values expression object
5579    """
5580    if columns and not alias:
5581        raise ValueError("Alias is required when providing columns")
5582
5583    return Values(
5584        expressions=[convert(tup) for tup in values],
5585        alias=(
5586            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5587            if columns
5588            else (TableAlias(this=to_identifier(alias)) if alias else None)
5589        ),
5590    )
5591
5592
5593def var(name: t.Optional[ExpOrStr]) -> Var:
5594    """Build a SQL variable.
5595
5596    Example:
5597        >>> repr(var('x'))
5598        '(VAR this: x)'
5599
5600        >>> repr(var(column('x', table='y')))
5601        '(VAR this: x)'
5602
5603    Args:
5604        name: The name of the var or an expression who's name will become the var.
5605
5606    Returns:
5607        The new variable node.
5608    """
5609    if not name:
5610        raise ValueError("Cannot convert empty name into var.")
5611
5612    if isinstance(name, Expression):
5613        name = name.name
5614    return Var(this=name)
5615
5616
5617def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5618    """Build ALTER TABLE... RENAME... expression
5619
5620    Args:
5621        old_name: The old name of the table
5622        new_name: The new name of the table
5623
5624    Returns:
5625        Alter table expression
5626    """
5627    old_table = to_table(old_name)
5628    new_table = to_table(new_name)
5629    return AlterTable(
5630        this=old_table,
5631        actions=[
5632            RenameTable(this=new_table),
5633        ],
5634    )
5635
5636
5637def convert(value: t.Any, copy: bool = False) -> Expression:
5638    """Convert a python value into an expression object.
5639
5640    Raises an error if a conversion is not possible.
5641
5642    Args:
5643        value: A python object.
5644        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5645
5646    Returns:
5647        Expression: the equivalent expression object.
5648    """
5649    if isinstance(value, Expression):
5650        return _maybe_copy(value, copy)
5651    if isinstance(value, str):
5652        return Literal.string(value)
5653    if isinstance(value, bool):
5654        return Boolean(this=value)
5655    if value is None or (isinstance(value, float) and math.isnan(value)):
5656        return NULL
5657    if isinstance(value, numbers.Number):
5658        return Literal.number(value)
5659    if isinstance(value, datetime.datetime):
5660        datetime_literal = Literal.string(
5661            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5662        )
5663        return TimeStrToTime(this=datetime_literal)
5664    if isinstance(value, datetime.date):
5665        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5666        return DateStrToDate(this=date_literal)
5667    if isinstance(value, tuple):
5668        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5669    if isinstance(value, list):
5670        return Array(expressions=[convert(v, copy=copy) for v in value])
5671    if isinstance(value, dict):
5672        return Map(
5673            keys=[convert(k, copy=copy) for k in value],
5674            values=[convert(v, copy=copy) for v in value.values()],
5675        )
5676    raise ValueError(f"Cannot convert {value}")
5677
5678
5679def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5680    """
5681    Replace children of an expression with the result of a lambda fun(child) -> exp.
5682    """
5683    for k, v in expression.args.items():
5684        is_list_arg = type(v) is list
5685
5686        child_nodes = v if is_list_arg else [v]
5687        new_child_nodes = []
5688
5689        for cn in child_nodes:
5690            if isinstance(cn, Expression):
5691                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5692                    new_child_nodes.append(child_node)
5693                    child_node.parent = expression
5694                    child_node.arg_key = k
5695            else:
5696                new_child_nodes.append(cn)
5697
5698        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
5699
5700
5701def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5702    """
5703    Return all table names referenced through columns in an expression.
5704
5705    Example:
5706        >>> import sqlglot
5707        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5708        ['a', 'c']
5709
5710    Args:
5711        expression: expression to find table names.
5712        exclude: a table name to exclude
5713
5714    Returns:
5715        A list of unique names.
5716    """
5717    return {
5718        table
5719        for table in (column.table for column in expression.find_all(Column))
5720        if table and table != exclude
5721    }
5722
5723
5724def table_name(table: Table | str, dialect: DialectType = None) -> str:
5725    """Get the full name of a table as a string.
5726
5727    Args:
5728        table: Table expression node or string.
5729        dialect: The dialect to generate the table name for.
5730
5731    Examples:
5732        >>> from sqlglot import exp, parse_one
5733        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5734        'a.b.c'
5735
5736    Returns:
5737        The table name.
5738    """
5739
5740    table = maybe_parse(table, into=Table)
5741
5742    if not table:
5743        raise ValueError(f"Cannot parse {table}")
5744
5745    return ".".join(
5746        part.sql(dialect=dialect) if not SAFE_IDENTIFIER_RE.match(part.name) else part.name
5747        for part in table.parts
5748    )
5749
5750
5751def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5752    """Replace all tables in expression according to the mapping.
5753
5754    Args:
5755        expression: expression node to be transformed and replaced.
5756        mapping: mapping of table names.
5757        copy: whether or not to copy the expression.
5758
5759    Examples:
5760        >>> from sqlglot import exp, parse_one
5761        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5762        'SELECT * FROM c'
5763
5764    Returns:
5765        The mapped expression.
5766    """
5767
5768    def _replace_tables(node: Expression) -> Expression:
5769        if isinstance(node, Table):
5770            new_name = mapping.get(table_name(node))
5771            if new_name:
5772                return to_table(
5773                    new_name,
5774                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5775                )
5776        return node
5777
5778    return expression.transform(_replace_tables, copy=copy)
5779
5780
5781def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5782    """Replace placeholders in an expression.
5783
5784    Args:
5785        expression: expression node to be transformed and replaced.
5786        args: positional names that will substitute unnamed placeholders in the given order.
5787        kwargs: keyword arguments that will substitute named placeholders.
5788
5789    Examples:
5790        >>> from sqlglot import exp, parse_one
5791        >>> replace_placeholders(
5792        ...     parse_one("select * from :tbl where ? = ?"),
5793        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5794        ... ).sql()
5795        "SELECT * FROM foo WHERE str_col = 'b'"
5796
5797    Returns:
5798        The mapped expression.
5799    """
5800
5801    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5802        if isinstance(node, Placeholder):
5803            if node.name:
5804                new_name = kwargs.get(node.name)
5805                if new_name:
5806                    return convert(new_name)
5807            else:
5808                try:
5809                    return convert(next(args))
5810                except StopIteration:
5811                    pass
5812        return node
5813
5814    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5815
5816
5817def expand(
5818    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5819) -> Expression:
5820    """Transforms an expression by expanding all referenced sources into subqueries.
5821
5822    Examples:
5823        >>> from sqlglot import parse_one
5824        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5825        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5826
5827        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5828        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5829
5830    Args:
5831        expression: The expression to expand.
5832        sources: A dictionary of name to Subqueryables.
5833        copy: Whether or not to copy the expression during transformation. Defaults to True.
5834
5835    Returns:
5836        The transformed expression.
5837    """
5838
5839    def _expand(node: Expression):
5840        if isinstance(node, Table):
5841            name = table_name(node)
5842            source = sources.get(name)
5843            if source:
5844                subquery = source.subquery(node.alias or name)
5845                subquery.comments = [f"source: {name}"]
5846                return subquery.transform(_expand, copy=False)
5847        return node
5848
5849    return expression.transform(_expand, copy=copy)
5850
5851
5852def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5853    """
5854    Returns a Func expression.
5855
5856    Examples:
5857        >>> func("abs", 5).sql()
5858        'ABS(5)'
5859
5860        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5861        'CAST(5 AS DOUBLE)'
5862
5863    Args:
5864        name: the name of the function to build.
5865        args: the args used to instantiate the function of interest.
5866        dialect: the source dialect.
5867        kwargs: the kwargs used to instantiate the function of interest.
5868
5869    Note:
5870        The arguments `args` and `kwargs` are mutually exclusive.
5871
5872    Returns:
5873        An instance of the function of interest, or an anonymous function, if `name` doesn't
5874        correspond to an existing `sqlglot.expressions.Func` class.
5875    """
5876    if args and kwargs:
5877        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5878
5879    from sqlglot.dialects.dialect import Dialect
5880
5881    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5882    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5883
5884    parser = Dialect.get_or_raise(dialect)().parser()
5885    from_args_list = parser.FUNCTIONS.get(name.upper())
5886
5887    if from_args_list:
5888        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5889    else:
5890        kwargs = kwargs or {"expressions": converted}
5891        function = Anonymous(this=name, **kwargs)
5892
5893    for error_message in function.error_messages(converted):
5894        raise ValueError(error_message)
5895
5896    return function
5897
5898
5899def true() -> Boolean:
5900    """
5901    Returns a true Boolean expression.
5902    """
5903    return Boolean(this=True)
5904
5905
5906def false() -> Boolean:
5907    """
5908    Returns a false Boolean expression.
5909    """
5910    return Boolean(this=False)
5911
5912
5913def null() -> Null:
5914    """
5915    Returns a Null expression.
5916    """
5917    return Null()
5918
5919
5920# TODO: deprecate this
5921TRUE = Boolean(this=True)
5922FALSE = Boolean(this=False)
5923NULL = 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    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False}
key = 'group'
class Lambda(Expression):
1627class Lambda(Expression):
1628    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1631class Limit(Expression):
1632    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
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
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1642    @classmethod
1643    def number(cls, number) -> Literal:
1644        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1646    @classmethod
1647    def string(cls, string) -> Literal:
1648        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):
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
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:
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

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:
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

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):
1775class Lateral(UDTF):
1776    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):
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    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1794class Final(Expression):
1795    pass
key = 'final'
class Offset(Expression):
1798class Offset(Expression):
1799    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1802class Order(Expression):
1803    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1808class Cluster(Order):
1809    pass
key = 'cluster'
class Distribute(Order):
1812class Distribute(Order):
1813    pass
key = 'distribute'
class Sort(Order):
1816class Sort(Order):
1817    pass
key = 'sort'
class Ordered(Expression):
1820class Ordered(Expression):
1821    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1824class Property(Expression):
1825    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1828class AlgorithmProperty(Property):
1829    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1832class AutoIncrementProperty(Property):
1833    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1836class BlockCompressionProperty(Property):
1837    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):
1840class CharacterSetProperty(Property):
1841    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1844class ChecksumProperty(Property):
1845    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1848class CollateProperty(Property):
1849    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1852class CopyGrantsProperty(Property):
1853    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1856class DataBlocksizeProperty(Property):
1857    arg_types = {
1858        "size": False,
1859        "units": False,
1860        "minimum": False,
1861        "maximum": False,
1862        "default": False,
1863    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1866class DefinerProperty(Property):
1867    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1870class DistKeyProperty(Property):
1871    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1874class DistStyleProperty(Property):
1875    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1878class EngineProperty(Property):
1879    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1882class ToTableProperty(Property):
1883    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1886class ExecuteAsProperty(Property):
1887    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1890class ExternalProperty(Property):
1891    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1894class FallbackProperty(Property):
1895    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1898class FileFormatProperty(Property):
1899    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1902class FreespaceProperty(Property):
1903    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1906class InputOutputFormat(Expression):
1907    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
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    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1920class JournalProperty(Property):
1921    arg_types = {
1922        "no": False,
1923        "dual": False,
1924        "before": False,
1925        "local": False,
1926        "after": False,
1927    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1930class LanguageProperty(Property):
1931    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1935class ClusteredByProperty(Property):
1936    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1939class DictProperty(Property):
1940    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1943class DictSubProperty(Property):
1944    pass
key = 'dictsubproperty'
class DictRange(Property):
1947class DictRange(Property):
1948    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1953class OnCluster(Property):
1954    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1957class LikeProperty(Property):
1958    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1961class LocationProperty(Property):
1962    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
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    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
1975class LogProperty(Property):
1976    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
1979class MaterializedProperty(Property):
1980    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
1983class MergeBlockRatioProperty(Property):
1984    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):
1987class NoPrimaryIndexProperty(Property):
1988    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
1991class OnCommitProperty(Property):
1992    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
1995class PartitionedByProperty(Property):
1996    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
1999class ReturnsProperty(Property):
2000    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2003class RowFormatProperty(Property):
2004    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
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    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2020class RowFormatSerdeProperty(Property):
2021    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatserdeproperty'
class SchemaCommentProperty(Property):
2024class SchemaCommentProperty(Property):
2025    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2028class SerdeProperties(Property):
2029    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2032class SetProperty(Property):
2033    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2036class SettingsProperty(Property):
2037    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2040class SortKeyProperty(Property):
2041    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2044class SqlSecurityProperty(Property):
2045    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2048class StabilityProperty(Property):
2049    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2052class TemporaryProperty(Property):
2053    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2056class TransientProperty(Property):
2057    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2060class VolatileProperty(Property):
2061    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2064class WithDataProperty(Property):
2065    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2068class WithJournalTableProperty(Property):
2069    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
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)
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:
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)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
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()

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):
2134class Qualify(Expression):
2135    pass
key = 'qualify'
class Return(Expression):
2139class Return(Expression):
2140    pass
key = 'return'
class Reference(Expression):
2143class Reference(Expression):
2144    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
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        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
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        )
key = 'tuple'
class Subqueryable(Unionable):
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        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
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)

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:
2183    def limit(
2184        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2185    ) -> Select:
2186        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:
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        )

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):
2264class WithTableHint(Expression):
2265    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2269class IndexTableHint(Expression):
2270    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
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        ]
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):
2311class SystemTime(Expression):
2312    arg_types = {
2313        "this": False,
2314        "expression": False,
2315        "kind": True,
2316    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
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
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:
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        )

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:
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

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):
2411class Except(Union):
2412    pass
key = 'except'
class Intersect(Union):
2415class Intersect(Union):
2416    pass
key = 'intersect'
class Unnest(UDTF):
2419class Unnest(UDTF):
2420    arg_types = {
2421        "expressions": True,
2422        "ordinality": False,
2423        "alias": False,
2424        "offset": False,
2425    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False, 'offset': False}
key = 'unnest'
class Update(Expression):
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    }
arg_types = {'with': False, 'this': False, 'expressions': True, 'from': False, 'where': False, 'returning': False, 'limit': False}
key = 'update'
class Values(UDTF):
2440class Values(UDTF):
2441    arg_types = {
2442        "expressions": True,
2443        "ordinality": False,
2444        "alias": False,
2445    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False}
key = 'values'
class Var(Expression):
2448class Var(Expression):
2449    pass
key = 'var'
class Schema(Expression):
2452class Schema(Expression):
2453    arg_types = {"this": False, "expressions": False}
arg_types = {'this': False, 'expressions': False}
key = 'schema'
class Lock(Expression):
2458class Lock(Expression):
2459    arg_types = {"update": True, "expressions": False, "wait": False}
arg_types = {'update': True, 'expressions': False, 'wait': False}
key = 'lock'
class Select(Subqueryable):
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
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:
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        )

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:
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        )

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:
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        )

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:
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        )

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:
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        )

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:
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        )

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:
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        )

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:
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        )

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:
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        )

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:
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        )

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:
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        )

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:
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        )

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:
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        )
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:
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        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
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

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:
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        )

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:
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

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:
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

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):
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
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):
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

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):
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    }
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):
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    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
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    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
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    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3230class WindowSpec(Expression):
3231    arg_types = {
3232        "kind": False,
3233        "start": False,
3234        "start_side": False,
3235        "end": False,
3236        "end_side": False,
3237    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3240class Where(Expression):
3241    pass
key = 'where'
class Star(Expression):
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
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):
3256class Parameter(Condition):
3257    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3260class SessionParameter(Condition):
3261    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3264class Placeholder(Condition):
3265    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3268class Null(Condition):
3269    arg_types: t.Dict[str, t.Any] = {}
3270
3271    @property
3272    def name(self) -> str:
3273        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3276class Boolean(Condition):
3277    pass
key = 'boolean'
class DataTypeSize(Expression):
3280class DataTypeSize(Expression):
3281    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
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)
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False}
TEXT_TYPES = {<Type.NVARCHAR: 'NVARCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.TEXT: 'TEXT'>, <Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>}
INTEGER_TYPES = {<Type.INT: 'INT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.TINYINT: 'TINYINT'>, <Type.INT256: 'INT256'>, <Type.BIGINT: 'BIGINT'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.INT: 'INT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.TINYINT: 'TINYINT'>, <Type.FLOAT: 'FLOAT'>, <Type.INT256: 'INT256'>, <Type.BIGINT: 'BIGINT'>, <Type.DOUBLE: 'DOUBLE'>}
TEMPORAL_TYPES = {<Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATETIME64: 'DATETIME64'>, <Type.DATE: 'DATE'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIME: 'TIME'>, <Type.DATETIME: 'DATETIME'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>}
META_TYPES = {'NULL', 'UNKNOWN'}
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
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})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3433    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3434        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
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()

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):
3438class PseudoType(Expression):
3439    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3443class SubqueryPredicate(Predicate):
3444    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3447class All(SubqueryPredicate):
3448    pass
key = 'all'
class Any(SubqueryPredicate):
3451class Any(SubqueryPredicate):
3452    pass
key = 'any'
class Exists(SubqueryPredicate):
3455class Exists(SubqueryPredicate):
3456    pass
key = 'exists'
class Command(Expression):
3461class Command(Expression):
3462    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3465class Transaction(Expression):
3466    arg_types = {"this": False, "modes": False}
arg_types = {'this': False, 'modes': False}
key = 'transaction'
class Commit(Expression):
3469class Commit(Expression):
3470    arg_types = {"chain": False}
arg_types = {'chain': False}
key = 'commit'
class Rollback(Expression):
3473class Rollback(Expression):
3474    arg_types = {"savepoint": False}
arg_types = {'savepoint': False}
key = 'rollback'
class AlterTable(Expression):
3477class AlterTable(Expression):
3478    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3481class AddConstraint(Expression):
3482    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3485class DropPartition(Expression):
3486    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
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
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3502class Add(Binary):
3503    pass
key = 'add'
class Connector(Binary):
3506class Connector(Binary):
3507    pass
key = 'connector'
class And(Connector):
3510class And(Connector):
3511    pass
key = 'and'
class Or(Connector):
3514class Or(Connector):
3515    pass
key = 'or'
class BitwiseAnd(Binary):
3518class BitwiseAnd(Binary):
3519    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3522class BitwiseLeftShift(Binary):
3523    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3526class BitwiseOr(Binary):
3527    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3530class BitwiseRightShift(Binary):
3531    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3534class BitwiseXor(Binary):
3535    pass
key = 'bitwisexor'
class Div(Binary):
3538class Div(Binary):
3539    pass
key = 'div'
class Overlaps(Binary):
3542class Overlaps(Binary):
3543    pass
key = 'overlaps'
class Dot(Binary):
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
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:
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

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3570class DPipe(Binary):
3571    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3574class SafeDPipe(DPipe):
3575    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3578class EQ(Binary, Predicate):
3579    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3582class NullSafeEQ(Binary, Predicate):
3583    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3586class NullSafeNEQ(Binary, Predicate):
3587    pass
key = 'nullsafeneq'
class Distance(Binary):
3590class Distance(Binary):
3591    pass
key = 'distance'
class Escape(Binary):
3594class Escape(Binary):
3595    pass
key = 'escape'
class Glob(Binary, Predicate):
3598class Glob(Binary, Predicate):
3599    pass
key = 'glob'
class GT(Binary, Predicate):
3602class GT(Binary, Predicate):
3603    pass
key = 'gt'
class GTE(Binary, Predicate):
3606class GTE(Binary, Predicate):
3607    pass
key = 'gte'
class ILike(Binary, Predicate):
3610class ILike(Binary, Predicate):
3611    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3614class ILikeAny(Binary, Predicate):
3615    pass
key = 'ilikeany'
class IntDiv(Binary):
3618class IntDiv(Binary):
3619    pass
key = 'intdiv'
class Is(Binary, Predicate):
3622class Is(Binary, Predicate):
3623    pass
key = 'is'
class Kwarg(Binary):
3626class Kwarg(Binary):
3627    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3630class Like(Binary, Predicate):
3631    pass
key = 'like'
class LikeAny(Binary, Predicate):
3634class LikeAny(Binary, Predicate):
3635    pass
key = 'likeany'
class LT(Binary, Predicate):
3638class LT(Binary, Predicate):
3639    pass
key = 'lt'
class LTE(Binary, Predicate):
3642class LTE(Binary, Predicate):
3643    pass
key = 'lte'
class Mod(Binary):
3646class Mod(Binary):
3647    pass
key = 'mod'
class Mul(Binary):
3650class Mul(Binary):
3651    pass
key = 'mul'
class NEQ(Binary, Predicate):
3654class NEQ(Binary, Predicate):
3655    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3658class SimilarTo(Binary, Predicate):
3659    pass
key = 'similarto'
class Slice(Binary):
3662class Slice(Binary):
3663    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3666class Sub(Binary):
3667    pass
key = 'sub'
class ArrayOverlaps(Binary):
3670class ArrayOverlaps(Binary):
3671    pass
key = 'arrayoverlaps'
class Unary(Condition):
3676class Unary(Condition):
3677    pass
key = 'unary'
class BitwiseNot(Unary):
3680class BitwiseNot(Unary):
3681    pass
key = 'bitwisenot'
class Not(Unary):
3684class Not(Unary):
3685    pass
key = 'not'
class Paren(Unary):
3688class Paren(Unary):
3689    arg_types = {"this": True, "with": False}
3690
3691    @property
3692    def output_name(self) -> str:
3693        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):
3696class Neg(Unary):
3697    pass
key = 'neg'
class Alias(Expression):
3700class Alias(Expression):
3701    arg_types = {"this": True, "alias": False}
3702
3703    @property
3704    def output_name(self) -> str:
3705        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):
3708class Aliases(Expression):
3709    arg_types = {"this": True, "expressions": True}
3710
3711    @property
3712    def aliases(self):
3713        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3716class AtTimeZone(Expression):
3717    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3720class Between(Predicate):
3721    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3724class Bracket(Condition):
3725    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3728class SafeBracket(Bracket):
3729    """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):
3732class Distinct(Expression):
3733    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
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    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
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)

Automatically converts unit arg into a var.

TimeUnit(**args)
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)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
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")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3770class IgnoreNulls(Expression):
3771    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3774class RespectNulls(Expression):
3775    pass
key = 'respectnulls'
class Func(Condition):
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()}

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):
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)
@classmethod
def sql_names(cls):
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
@classmethod
def sql_name(cls):
3819    @classmethod
3820    def sql_name(cls):
3821        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3823    @classmethod
3824    def default_parser_mappings(cls):
3825        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3828class AggFunc(Func):
3829    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3832class ParameterizedAgg(AggFunc):
3833    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3836class Abs(Func):
3837    pass
key = 'abs'
class Anonymous(Func):
3840class Anonymous(Func):
3841    arg_types = {"this": True, "expressions": False}
3842    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3847class Hll(AggFunc):
3848    arg_types = {"this": True, "expressions": False}
3849    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3852class ApproxDistinct(AggFunc):
3853    arg_types = {"this": True, "accuracy": False}
3854    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3857class Array(Func):
3858    arg_types = {"expressions": False}
3859    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3863class ToChar(Func):
3864    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3867class GenerateSeries(Func):
3868    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3871class ArrayAgg(AggFunc):
3872    pass
key = 'arrayagg'
class ArrayAll(Func):
3875class ArrayAll(Func):
3876    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3879class ArrayAny(Func):
3880    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3883class ArrayConcat(Func):
3884    arg_types = {"this": True, "expressions": False}
3885    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3888class ArrayContains(Binary, Func):
3889    pass
key = 'arraycontains'
class ArrayContained(Binary):
3892class ArrayContained(Binary):
3893    pass
key = 'arraycontained'
class ArrayFilter(Func):
3896class ArrayFilter(Func):
3897    arg_types = {"this": True, "expression": True}
3898    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3901class ArrayJoin(Func):
3902    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3905class ArraySize(Func):
3906    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3909class ArraySort(Func):
3910    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3913class ArraySum(Func):
3914    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3917class ArrayUnionAgg(AggFunc):
3918    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3921class Avg(AggFunc):
3922    pass
key = 'avg'
class AnyValue(AggFunc):
3925class AnyValue(AggFunc):
3926    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
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
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:
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
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
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
key = 'case'
class Cast(Func):
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)
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:
3964    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3965        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
3968class CastToStrType(Func):
3969    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
3972class Collate(Binary):
3973    pass
key = 'collate'
class TryCast(Cast):
3976class TryCast(Cast):
3977    pass
key = 'trycast'
class Ceil(Func):
3980class Ceil(Func):
3981    arg_types = {"this": True, "decimals": False}
3982    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
3985class Coalesce(Func):
3986    arg_types = {"this": True, "expressions": False}
3987    is_var_len_args = True
3988    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
3991class Concat(Func):
3992    arg_types = {"expressions": True}
3993    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
3996class SafeConcat(Concat):
3997    pass
key = 'safeconcat'
class ConcatWs(Concat):
4000class ConcatWs(Concat):
4001    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4004class Count(AggFunc):
4005    arg_types = {"this": False, "expressions": False}
4006    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4009class CountIf(AggFunc):
4010    pass
key = 'countif'
class CurrentDate(Func):
4013class CurrentDate(Func):
4014    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4017class CurrentDatetime(Func):
4018    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4021class CurrentTime(Func):
4022    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4025class CurrentTimestamp(Func):
4026    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4029class CurrentUser(Func):
4030    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4033class DateAdd(Func, TimeUnit):
4034    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4037class DateSub(Func, TimeUnit):
4038    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4041class DateDiff(Func, TimeUnit):
4042    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4043    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4046class DateTrunc(Func):
4047    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4050class DatetimeAdd(Func, TimeUnit):
4051    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4054class DatetimeSub(Func, TimeUnit):
4055    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4058class DatetimeDiff(Func, TimeUnit):
4059    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4062class DatetimeTrunc(Func, TimeUnit):
4063    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4066class DayOfWeek(Func):
4067    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4070class DayOfMonth(Func):
4071    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4074class DayOfYear(Func):
4075    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4078class WeekOfYear(Func):
4079    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class LastDateOfMonth(Func):
4082class LastDateOfMonth(Func):
4083    pass
key = 'lastdateofmonth'
class Extract(Func):
4086class Extract(Func):
4087    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4090class TimestampAdd(Func, TimeUnit):
4091    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4094class TimestampSub(Func, TimeUnit):
4095    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4098class TimestampDiff(Func, TimeUnit):
4099    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4102class TimestampTrunc(Func, TimeUnit):
4103    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4106class TimeAdd(Func, TimeUnit):
4107    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4110class TimeSub(Func, TimeUnit):
4111    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4114class TimeDiff(Func, TimeUnit):
4115    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4118class TimeTrunc(Func, TimeUnit):
4119    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4122class DateFromParts(Func):
4123    _sql_names = ["DATEFROMPARTS"]
4124    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4127class DateStrToDate(Func):
4128    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4131class DateToDateStr(Func):
4132    pass
key = 'datetodatestr'
class DateToDi(Func):
4135class DateToDi(Func):
4136    pass
key = 'datetodi'
class Date(Func):
4139class Date(Func):
4140    arg_types = {"expressions": True}
4141    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'date'
class Day(Func):
4144class Day(Func):
4145    pass
key = 'day'
class Decode(Func):
4148class Decode(Func):
4149    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4152class DiToDate(Func):
4153    pass
key = 'ditodate'
class Encode(Func):
4156class Encode(Func):
4157    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4160class Exp(Func):
4161    pass
key = 'exp'
class Explode(Func):
4164class Explode(Func):
4165    pass
key = 'explode'
class Floor(Func):
4168class Floor(Func):
4169    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4172class FromBase64(Func):
4173    pass
key = 'frombase64'
class ToBase64(Func):
4176class ToBase64(Func):
4177    pass
key = 'tobase64'
class Greatest(Func):
4180class Greatest(Func):
4181    arg_types = {"this": True, "expressions": False}
4182    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4185class GroupConcat(Func):
4186    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4189class Hex(Func):
4190    pass
key = 'hex'
class If(Func):
4193class If(Func):
4194    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4197class Initcap(Func):
4198    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4201class JSONKeyValue(Expression):
4202    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
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    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4216class OpenJSONColumnDef(Expression):
4217    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):
4220class OpenJSON(Func):
4221    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4224class JSONBContains(Binary):
4225    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4228class JSONExtract(Binary, Func):
4229    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4232class JSONExtractScalar(JSONExtract):
4233    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4236class JSONBExtract(JSONExtract):
4237    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4240class JSONBExtractScalar(JSONExtract):
4241    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4244class JSONFormat(Func):
4245    arg_types = {"this": False, "options": False}
4246    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class Least(Func):
4249class Least(Func):
4250    arg_types = {"expressions": False}
4251    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4254class Left(Func):
4255    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4262class Length(Func):
4263    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
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    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4276class Ln(Func):
4277    pass
key = 'ln'
class Log(Func):
4280class Log(Func):
4281    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4284class Log2(Func):
4285    pass
key = 'log2'
class Log10(Func):
4288class Log10(Func):
4289    pass
key = 'log10'
class LogicalOr(AggFunc):
4292class LogicalOr(AggFunc):
4293    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4296class LogicalAnd(AggFunc):
4297    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4300class Lower(Func):
4301    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4304class Map(Func):
4305    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4308class MapFromEntries(Func):
4309    pass
key = 'mapfromentries'
class StarMap(Func):
4312class StarMap(Func):
4313    pass
key = 'starmap'
class VarMap(Func):
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
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4330class MatchAgainst(Func):
4331    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4334class Max(AggFunc):
4335    arg_types = {"this": True, "expressions": False}
4336    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4339class MD5(Func):
4340    _sql_names = ["MD5"]
key = 'md5'
class Min(AggFunc):
4343class Min(AggFunc):
4344    arg_types = {"this": True, "expressions": False}
4345    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4348class Month(Func):
4349    pass
key = 'month'
class Nvl2(Func):
4352class Nvl2(Func):
4353    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4356class Posexplode(Func):
4357    pass
key = 'posexplode'
class Pow(Binary, Func):
4360class Pow(Binary, Func):
4361    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4364class PercentileCont(AggFunc):
4365    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4368class PercentileDisc(AggFunc):
4369    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4372class Quantile(AggFunc):
4373    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4376class ApproxQuantile(Quantile):
4377    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):
4380class RangeN(Func):
4381    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4384class ReadCSV(Func):
4385    _sql_names = ["READ_CSV"]
4386    is_var_len_args = True
4387    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4390class Reduce(Func):
4391    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):
4394class RegexpExtract(Func):
4395    arg_types = {
4396        "this": True,
4397        "expression": True,
4398        "position": False,
4399        "occurrence": False,
4400        "group": False,
4401    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'group': False}
key = 'regexpextract'
class RegexpLike(Func):
4404class RegexpLike(Func):
4405    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4408class RegexpILike(Func):
4409    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4414class RegexpSplit(Func):
4415    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4418class Repeat(Func):
4419    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4422class Round(Func):
4423    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4426class RowNumber(Func):
4427    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4430class SafeDivide(Func):
4431    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4434class SetAgg(AggFunc):
4435    pass
key = 'setagg'
class SHA(Func):
4438class SHA(Func):
4439    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4442class SHA2(Func):
4443    _sql_names = ["SHA2"]
4444    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4447class SortArray(Func):
4448    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4451class Split(Func):
4452    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4457class Substring(Func):
4458    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4461class StandardHash(Func):
4462    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4465class StrPosition(Func):
4466    arg_types = {
4467        "this": True,
4468        "substr": True,
4469        "position": False,
4470        "instance": False,
4471    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4474class StrToDate(Func):
4475    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4478class StrToTime(Func):
4479    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtotime'
class StrToUnix(Func):
4484class StrToUnix(Func):
4485    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4488class NumberToStr(Func):
4489    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4492class FromBase(Func):
4493    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4496class Struct(Func):
4497    arg_types = {"expressions": True}
4498    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4501class StructExtract(Func):
4502    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4505class Sum(AggFunc):
4506    pass
key = 'sum'
class Sqrt(Func):
4509class Sqrt(Func):
4510    pass
key = 'sqrt'
class Stddev(AggFunc):
4513class Stddev(AggFunc):
4514    pass
key = 'stddev'
class StddevPop(AggFunc):
4517class StddevPop(AggFunc):
4518    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4521class StddevSamp(AggFunc):
4522    pass
key = 'stddevsamp'
class TimeToStr(Func):
4525class TimeToStr(Func):
4526    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4529class TimeToTimeStr(Func):
4530    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4533class TimeToUnix(Func):
4534    pass
key = 'timetounix'
class TimeStrToDate(Func):
4537class TimeStrToDate(Func):
4538    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4541class TimeStrToTime(Func):
4542    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4545class TimeStrToUnix(Func):
4546    pass
key = 'timestrtounix'
class Trim(Func):
4549class Trim(Func):
4550    arg_types = {
4551        "this": True,
4552        "expression": False,
4553        "position": False,
4554        "collation": False,
4555    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4558class TsOrDsAdd(Func, TimeUnit):
4559    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4562class TsOrDsToDateStr(Func):
4563    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4566class TsOrDsToDate(Func):
4567    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4570class TsOrDiToDi(Func):
4571    pass
key = 'tsorditodi'
class Unhex(Func):
4574class Unhex(Func):
4575    pass
key = 'unhex'
class UnixToStr(Func):
4578class UnixToStr(Func):
4579    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
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")
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):
4592class UnixToTimeStr(Func):
4593    pass
key = 'unixtotimestr'
class Upper(Func):
4596class Upper(Func):
4597    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4600class Variance(AggFunc):
4601    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4604class VariancePop(AggFunc):
4605    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4608class Week(Func):
4609    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4612class XMLTable(Func):
4613    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):
4616class Year(Func):
4617    pass
key = 'year'
class Use(Expression):
4620class Use(Expression):
4621    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4624class Merge(Expression):
4625    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):
4628class When(Func):
4629    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):
4634class NextValueFor(Func):
4635    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:
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)

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:
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)

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:
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)

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:
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)

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:
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)

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:
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)

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:
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

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:
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

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:
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)

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:
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    )

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:
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))

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:
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))

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:
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))

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:
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))

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):
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

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:
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    )

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]:
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

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:
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

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):
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)

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:
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)

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:
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    )

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:
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))

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:
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    )

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:
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    )

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:
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)

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:
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    )

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:
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}")

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:
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)

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]:
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    }

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:
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    )

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:
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)

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:
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)

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:
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)

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:
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

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:
5900def true() -> Boolean:
5901    """
5902    Returns a true Boolean expression.
5903    """
5904    return Boolean(this=True)

Returns a true Boolean expression.

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

Returns a false Boolean expression.

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

Returns a Null expression.

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