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

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

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

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

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):
1572class OnConflict(Expression):
1573    arg_types = {
1574        "duplicate": False,
1575        "expressions": False,
1576        "nothing": False,
1577        "key": False,
1578        "constraint": False,
1579    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1582class Returning(Expression):
1583    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'returning'
class Introducer(Expression):
1587class Introducer(Expression):
1588    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1592class National(Expression):
1593    pass
key = 'national'
class LoadData(Expression):
1596class LoadData(Expression):
1597    arg_types = {
1598        "this": True,
1599        "local": False,
1600        "overwrite": False,
1601        "inpath": True,
1602        "partition": False,
1603        "input_format": False,
1604        "serde": False,
1605    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1608class Partition(Expression):
1609    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1612class Fetch(Expression):
1613    arg_types = {
1614        "direction": False,
1615        "count": False,
1616        "percent": False,
1617        "with_ties": False,
1618    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1621class Group(Expression):
1622    arg_types = {
1623        "expressions": False,
1624        "grouping_sets": False,
1625        "cube": False,
1626        "rollup": False,
1627        "totals": False,
1628    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False}
key = 'group'
class Lambda(Expression):
1631class Lambda(Expression):
1632    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1635class Limit(Expression):
1636    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1639class Literal(Condition):
1640    arg_types = {"this": True, "is_string": True}
1641
1642    @property
1643    def hashable_args(self) -> t.Any:
1644        return (self.this, self.args.get("is_string"))
1645
1646    @classmethod
1647    def number(cls, number) -> Literal:
1648        return cls(this=str(number), is_string=False)
1649
1650    @classmethod
1651    def string(cls, string) -> Literal:
1652        return cls(this=str(string), is_string=True)
1653
1654    @property
1655    def output_name(self) -> str:
1656        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1646    @classmethod
1647    def number(cls, number) -> Literal:
1648        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1650    @classmethod
1651    def string(cls, string) -> Literal:
1652        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):
1659class Join(Expression):
1660    arg_types = {
1661        "this": True,
1662        "on": False,
1663        "side": False,
1664        "kind": False,
1665        "using": False,
1666        "method": False,
1667        "global": False,
1668        "hint": False,
1669    }
1670
1671    @property
1672    def method(self) -> str:
1673        return self.text("method").upper()
1674
1675    @property
1676    def kind(self) -> str:
1677        return self.text("kind").upper()
1678
1679    @property
1680    def side(self) -> str:
1681        return self.text("side").upper()
1682
1683    @property
1684    def hint(self) -> str:
1685        return self.text("hint").upper()
1686
1687    @property
1688    def alias_or_name(self) -> str:
1689        return self.this.alias_or_name
1690
1691    def on(
1692        self,
1693        *expressions: t.Optional[ExpOrStr],
1694        append: bool = True,
1695        dialect: DialectType = None,
1696        copy: bool = True,
1697        **opts,
1698    ) -> Join:
1699        """
1700        Append to or set the ON expressions.
1701
1702        Example:
1703            >>> import sqlglot
1704            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1705            'JOIN x ON y = 1'
1706
1707        Args:
1708            *expressions: the SQL code strings to parse.
1709                If an `Expression` instance is passed, it will be used as-is.
1710                Multiple expressions are combined with an AND operator.
1711            append: if `True`, AND the new expressions to any existing expression.
1712                Otherwise, this resets the expression.
1713            dialect: the dialect used to parse the input expressions.
1714            copy: if `False`, modify this expression instance in-place.
1715            opts: other options to use to parse the input expressions.
1716
1717        Returns:
1718            The modified Join expression.
1719        """
1720        join = _apply_conjunction_builder(
1721            *expressions,
1722            instance=self,
1723            arg="on",
1724            append=append,
1725            dialect=dialect,
1726            copy=copy,
1727            **opts,
1728        )
1729
1730        if join.kind == "CROSS":
1731            join.set("kind", None)
1732
1733        return join
1734
1735    def using(
1736        self,
1737        *expressions: t.Optional[ExpOrStr],
1738        append: bool = True,
1739        dialect: DialectType = None,
1740        copy: bool = True,
1741        **opts,
1742    ) -> Join:
1743        """
1744        Append to or set the USING expressions.
1745
1746        Example:
1747            >>> import sqlglot
1748            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1749            'JOIN x USING (foo, bla)'
1750
1751        Args:
1752            *expressions: the SQL code strings to parse.
1753                If an `Expression` instance is passed, it will be used as-is.
1754            append: if `True`, concatenate the new expressions to the existing "using" list.
1755                Otherwise, this resets the expression.
1756            dialect: the dialect used to parse the input expressions.
1757            copy: if `False`, modify this expression instance in-place.
1758            opts: other options to use to parse the input expressions.
1759
1760        Returns:
1761            The modified Join expression.
1762        """
1763        join = _apply_list_builder(
1764            *expressions,
1765            instance=self,
1766            arg="using",
1767            append=append,
1768            dialect=dialect,
1769            copy=copy,
1770            **opts,
1771        )
1772
1773        if join.kind == "CROSS":
1774            join.set("kind", None)
1775
1776        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:
1691    def on(
1692        self,
1693        *expressions: t.Optional[ExpOrStr],
1694        append: bool = True,
1695        dialect: DialectType = None,
1696        copy: bool = True,
1697        **opts,
1698    ) -> Join:
1699        """
1700        Append to or set the ON expressions.
1701
1702        Example:
1703            >>> import sqlglot
1704            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1705            'JOIN x ON y = 1'
1706
1707        Args:
1708            *expressions: the SQL code strings to parse.
1709                If an `Expression` instance is passed, it will be used as-is.
1710                Multiple expressions are combined with an AND operator.
1711            append: if `True`, AND the new expressions to any existing expression.
1712                Otherwise, this resets the expression.
1713            dialect: the dialect used to parse the input expressions.
1714            copy: if `False`, modify this expression instance in-place.
1715            opts: other options to use to parse the input expressions.
1716
1717        Returns:
1718            The modified Join expression.
1719        """
1720        join = _apply_conjunction_builder(
1721            *expressions,
1722            instance=self,
1723            arg="on",
1724            append=append,
1725            dialect=dialect,
1726            copy=copy,
1727            **opts,
1728        )
1729
1730        if join.kind == "CROSS":
1731            join.set("kind", None)
1732
1733        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:
1735    def using(
1736        self,
1737        *expressions: t.Optional[ExpOrStr],
1738        append: bool = True,
1739        dialect: DialectType = None,
1740        copy: bool = True,
1741        **opts,
1742    ) -> Join:
1743        """
1744        Append to or set the USING expressions.
1745
1746        Example:
1747            >>> import sqlglot
1748            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1749            'JOIN x USING (foo, bla)'
1750
1751        Args:
1752            *expressions: the SQL code strings to parse.
1753                If an `Expression` instance is passed, it will be used as-is.
1754            append: if `True`, concatenate the new expressions to the existing "using" list.
1755                Otherwise, this resets the expression.
1756            dialect: the dialect used to parse the input expressions.
1757            copy: if `False`, modify this expression instance in-place.
1758            opts: other options to use to parse the input expressions.
1759
1760        Returns:
1761            The modified Join expression.
1762        """
1763        join = _apply_list_builder(
1764            *expressions,
1765            instance=self,
1766            arg="using",
1767            append=append,
1768            dialect=dialect,
1769            copy=copy,
1770            **opts,
1771        )
1772
1773        if join.kind == "CROSS":
1774            join.set("kind", None)
1775
1776        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):
1779class Lateral(UDTF):
1780    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):
1783class MatchRecognize(Expression):
1784    arg_types = {
1785        "partition_by": False,
1786        "order": False,
1787        "measures": False,
1788        "rows": False,
1789        "after": False,
1790        "pattern": False,
1791        "define": False,
1792        "alias": False,
1793    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1798class Final(Expression):
1799    pass
key = 'final'
class Offset(Expression):
1802class Offset(Expression):
1803    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1806class Order(Expression):
1807    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1812class Cluster(Order):
1813    pass
key = 'cluster'
class Distribute(Order):
1816class Distribute(Order):
1817    pass
key = 'distribute'
class Sort(Order):
1820class Sort(Order):
1821    pass
key = 'sort'
class Ordered(Expression):
1824class Ordered(Expression):
1825    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1828class Property(Expression):
1829    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1832class AlgorithmProperty(Property):
1833    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1836class AutoIncrementProperty(Property):
1837    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1840class BlockCompressionProperty(Property):
1841    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):
1844class CharacterSetProperty(Property):
1845    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1848class ChecksumProperty(Property):
1849    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1852class CollateProperty(Property):
1853    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1856class CopyGrantsProperty(Property):
1857    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1860class DataBlocksizeProperty(Property):
1861    arg_types = {
1862        "size": False,
1863        "units": False,
1864        "minimum": False,
1865        "maximum": False,
1866        "default": False,
1867    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1870class DefinerProperty(Property):
1871    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1874class DistKeyProperty(Property):
1875    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1878class DistStyleProperty(Property):
1879    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1882class EngineProperty(Property):
1883    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1886class ToTableProperty(Property):
1887    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1890class ExecuteAsProperty(Property):
1891    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1894class ExternalProperty(Property):
1895    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1898class FallbackProperty(Property):
1899    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1902class FileFormatProperty(Property):
1903    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1906class FreespaceProperty(Property):
1907    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1910class InputOutputFormat(Expression):
1911    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1914class IsolatedLoadingProperty(Property):
1915    arg_types = {
1916        "no": True,
1917        "concurrent": True,
1918        "for_all": True,
1919        "for_insert": True,
1920        "for_none": True,
1921    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1924class JournalProperty(Property):
1925    arg_types = {
1926        "no": False,
1927        "dual": False,
1928        "before": False,
1929        "local": False,
1930        "after": False,
1931    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1934class LanguageProperty(Property):
1935    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class DictProperty(Property):
1938class DictProperty(Property):
1939    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1942class DictSubProperty(Property):
1943    pass
key = 'dictsubproperty'
class DictRange(Property):
1946class DictRange(Property):
1947    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1952class OnCluster(Property):
1953    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1956class LikeProperty(Property):
1957    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1960class LocationProperty(Property):
1961    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
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    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
1974class LogProperty(Property):
1975    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
1978class MaterializedProperty(Property):
1979    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
1982class MergeBlockRatioProperty(Property):
1983    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):
1986class NoPrimaryIndexProperty(Property):
1987    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
1990class OnCommitProperty(Property):
1991    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
1994class PartitionedByProperty(Property):
1995    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
1998class ReturnsProperty(Property):
1999    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2002class RowFormatProperty(Property):
2003    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
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    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2019class RowFormatSerdeProperty(Property):
2020    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatserdeproperty'
class SchemaCommentProperty(Property):
2023class SchemaCommentProperty(Property):
2024    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2027class SerdeProperties(Property):
2028    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2031class SetProperty(Property):
2032    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2035class SettingsProperty(Property):
2036    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2039class SortKeyProperty(Property):
2040    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2043class SqlSecurityProperty(Property):
2044    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2047class StabilityProperty(Property):
2048    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2051class TemporaryProperty(Property):
2052    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2055class TransientProperty(Property):
2056    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2059class VolatileProperty(Property):
2060    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2063class WithDataProperty(Property):
2064    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2067class WithJournalTableProperty(Property):
2068    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
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        "COLLATE": CollateProperty,
2079        "COMMENT": SchemaCommentProperty,
2080        "DEFINER": DefinerProperty,
2081        "DISTKEY": DistKeyProperty,
2082        "DISTSTYLE": DistStyleProperty,
2083        "ENGINE": EngineProperty,
2084        "EXECUTE AS": ExecuteAsProperty,
2085        "FORMAT": FileFormatProperty,
2086        "LANGUAGE": LanguageProperty,
2087        "LOCATION": LocationProperty,
2088        "PARTITIONED_BY": PartitionedByProperty,
2089        "RETURNS": ReturnsProperty,
2090        "ROW_FORMAT": RowFormatProperty,
2091        "SORTKEY": SortKeyProperty,
2092    }
2093
2094    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2095
2096    # CREATE property locations
2097    # Form: schema specified
2098    #   create [POST_CREATE]
2099    #     table a [POST_NAME]
2100    #     (b int) [POST_SCHEMA]
2101    #     with ([POST_WITH])
2102    #     index (b) [POST_INDEX]
2103    #
2104    # Form: alias selection
2105    #   create [POST_CREATE]
2106    #     table a [POST_NAME]
2107    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2108    #     index (c) [POST_INDEX]
2109    class Location(AutoName):
2110        POST_CREATE = auto()
2111        POST_NAME = auto()
2112        POST_SCHEMA = auto()
2113        POST_WITH = auto()
2114        POST_ALIAS = auto()
2115        POST_EXPRESSION = auto()
2116        POST_INDEX = auto()
2117        UNSUPPORTED = auto()
2118
2119    @classmethod
2120    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2121        expressions = []
2122        for key, value in properties_dict.items():
2123            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2124            if property_cls:
2125                expressions.append(property_cls(this=convert(value)))
2126            else:
2127                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2128
2129        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'>, '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.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:
2119    @classmethod
2120    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2121        expressions = []
2122        for key, value in properties_dict.items():
2123            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2124            if property_cls:
2125                expressions.append(property_cls(this=convert(value)))
2126            else:
2127                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2128
2129        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2109    class Location(AutoName):
2110        POST_CREATE = auto()
2111        POST_NAME = auto()
2112        POST_SCHEMA = auto()
2113        POST_WITH = auto()
2114        POST_ALIAS = auto()
2115        POST_EXPRESSION = auto()
2116        POST_INDEX = auto()
2117        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):
2132class Qualify(Expression):
2133    pass
key = 'qualify'
class Return(Expression):
2137class Return(Expression):
2138    pass
key = 'return'
class Reference(Expression):
2141class Reference(Expression):
2142    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2145class Tuple(Expression):
2146    arg_types = {"expressions": False}
2147
2148    def isin(
2149        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2150    ) -> In:
2151        return In(
2152            this=_maybe_copy(self, copy),
2153            expressions=[convert(e, copy=copy) for e in expressions],
2154            query=maybe_parse(query, copy=copy, **opts) if query else None,
2155        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2148    def isin(
2149        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2150    ) -> In:
2151        return In(
2152            this=_maybe_copy(self, copy),
2153            expressions=[convert(e, copy=copy) for e in expressions],
2154            query=maybe_parse(query, copy=copy, **opts) if query else None,
2155        )
key = 'tuple'
class Subqueryable(Unionable):
2158class Subqueryable(Unionable):
2159    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2160        """
2161        Convert this expression to an aliased expression that can be used as a Subquery.
2162
2163        Example:
2164            >>> subquery = Select().select("x").from_("tbl").subquery()
2165            >>> Select().select("x").from_(subquery).sql()
2166            'SELECT x FROM (SELECT x FROM tbl)'
2167
2168        Args:
2169            alias (str | Identifier): an optional alias for the subquery
2170            copy (bool): if `False`, modify this expression instance in-place.
2171
2172        Returns:
2173            Alias: the subquery
2174        """
2175        instance = _maybe_copy(self, copy)
2176        if not isinstance(alias, Expression):
2177            alias = TableAlias(this=to_identifier(alias)) if alias else None
2178
2179        return Subquery(this=instance, alias=alias)
2180
2181    def limit(
2182        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2183    ) -> Select:
2184        raise NotImplementedError
2185
2186    @property
2187    def ctes(self):
2188        with_ = self.args.get("with")
2189        if not with_:
2190            return []
2191        return with_.expressions
2192
2193    @property
2194    def selects(self):
2195        raise NotImplementedError("Subqueryable objects must implement `selects`")
2196
2197    @property
2198    def named_selects(self):
2199        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2200
2201    def with_(
2202        self,
2203        alias: ExpOrStr,
2204        as_: ExpOrStr,
2205        recursive: t.Optional[bool] = None,
2206        append: bool = True,
2207        dialect: DialectType = None,
2208        copy: bool = True,
2209        **opts,
2210    ) -> Subqueryable:
2211        """
2212        Append to or set the common table expressions.
2213
2214        Example:
2215            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2216            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2217
2218        Args:
2219            alias: the SQL code string to parse as the table name.
2220                If an `Expression` instance is passed, this is used as-is.
2221            as_: the SQL code string to parse as the table expression.
2222                If an `Expression` instance is passed, it will be used as-is.
2223            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2224            append: if `True`, add to any existing expressions.
2225                Otherwise, this resets the expressions.
2226            dialect: the dialect used to parse the input expression.
2227            copy: if `False`, modify this expression instance in-place.
2228            opts: other options to use to parse the input expressions.
2229
2230        Returns:
2231            The modified expression.
2232        """
2233        return _apply_cte_builder(
2234            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2235        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2159    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2160        """
2161        Convert this expression to an aliased expression that can be used as a Subquery.
2162
2163        Example:
2164            >>> subquery = Select().select("x").from_("tbl").subquery()
2165            >>> Select().select("x").from_(subquery).sql()
2166            'SELECT x FROM (SELECT x FROM tbl)'
2167
2168        Args:
2169            alias (str | Identifier): an optional alias for the subquery
2170            copy (bool): if `False`, modify this expression instance in-place.
2171
2172        Returns:
2173            Alias: the subquery
2174        """
2175        instance = _maybe_copy(self, copy)
2176        if not isinstance(alias, Expression):
2177            alias = TableAlias(this=to_identifier(alias)) if alias else None
2178
2179        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:
2181    def limit(
2182        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2183    ) -> Select:
2184        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:
2201    def with_(
2202        self,
2203        alias: ExpOrStr,
2204        as_: ExpOrStr,
2205        recursive: t.Optional[bool] = None,
2206        append: bool = True,
2207        dialect: DialectType = None,
2208        copy: bool = True,
2209        **opts,
2210    ) -> Subqueryable:
2211        """
2212        Append to or set the common table expressions.
2213
2214        Example:
2215            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2216            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2217
2218        Args:
2219            alias: the SQL code string to parse as the table name.
2220                If an `Expression` instance is passed, this is used as-is.
2221            as_: the SQL code string to parse as the table expression.
2222                If an `Expression` instance is passed, it will be used as-is.
2223            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2224            append: if `True`, add to any existing expressions.
2225                Otherwise, this resets the expressions.
2226            dialect: the dialect used to parse the input expression.
2227            copy: if `False`, modify this expression instance in-place.
2228            opts: other options to use to parse the input expressions.
2229
2230        Returns:
2231            The modified expression.
2232        """
2233        return _apply_cte_builder(
2234            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2235        )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Tags are used for generating arbitrary sql like SELECT x.

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

Build a Dot object with a sequence of expressions.

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

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

key = 'kwarg'
class Like(Binary, Predicate):
3622class Like(Binary, Predicate):
3623    pass
key = 'like'
class LikeAny(Binary, Predicate):
3626class LikeAny(Binary, Predicate):
3627    pass
key = 'likeany'
class LT(Binary, Predicate):
3630class LT(Binary, Predicate):
3631    pass
key = 'lt'
class LTE(Binary, Predicate):
3634class LTE(Binary, Predicate):
3635    pass
key = 'lte'
class Mod(Binary):
3638class Mod(Binary):
3639    pass
key = 'mod'
class Mul(Binary):
3642class Mul(Binary):
3643    pass
key = 'mul'
class NEQ(Binary, Predicate):
3646class NEQ(Binary, Predicate):
3647    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3650class SimilarTo(Binary, Predicate):
3651    pass
key = 'similarto'
class Slice(Binary):
3654class Slice(Binary):
3655    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3658class Sub(Binary):
3659    pass
key = 'sub'
class ArrayOverlaps(Binary):
3662class ArrayOverlaps(Binary):
3663    pass
key = 'arrayoverlaps'
class Unary(Condition):
3668class Unary(Condition):
3669    pass
key = 'unary'
class BitwiseNot(Unary):
3672class BitwiseNot(Unary):
3673    pass
key = 'bitwisenot'
class Not(Unary):
3676class Not(Unary):
3677    pass
key = 'not'
class Paren(Unary):
3680class Paren(Unary):
3681    arg_types = {"this": True, "with": False}
3682
3683    @property
3684    def output_name(self) -> str:
3685        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):
3688class Neg(Unary):
3689    pass
key = 'neg'
class Alias(Expression):
3692class Alias(Expression):
3693    arg_types = {"this": True, "alias": False}
3694
3695    @property
3696    def output_name(self) -> str:
3697        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):
3700class Aliases(Expression):
3701    arg_types = {"this": True, "expressions": True}
3702
3703    @property
3704    def aliases(self):
3705        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3708class AtTimeZone(Expression):
3709    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3712class Between(Predicate):
3713    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3716class Bracket(Condition):
3717    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class Distinct(Expression):
3720class Distinct(Expression):
3721    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3724class In(Predicate):
3725    arg_types = {
3726        "this": True,
3727        "expressions": False,
3728        "query": False,
3729        "unnest": False,
3730        "field": False,
3731        "is_global": False,
3732    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3735class TimeUnit(Expression):
3736    """Automatically converts unit arg into a var."""
3737
3738    arg_types = {"unit": False}
3739
3740    def __init__(self, **args):
3741        unit = args.get("unit")
3742        if isinstance(unit, (Column, Literal)):
3743            args["unit"] = Var(this=unit.name)
3744        elif isinstance(unit, Week):
3745            unit.set("this", Var(this=unit.this.name))
3746
3747        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3740    def __init__(self, **args):
3741        unit = args.get("unit")
3742        if isinstance(unit, (Column, Literal)):
3743            args["unit"] = Var(this=unit.name)
3744        elif isinstance(unit, Week):
3745            unit.set("this", Var(this=unit.this.name))
3746
3747        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3750class Interval(TimeUnit):
3751    arg_types = {"this": False, "unit": False}
3752
3753    @property
3754    def unit(self) -> t.Optional[Var]:
3755        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3758class IgnoreNulls(Expression):
3759    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3762class RespectNulls(Expression):
3763    pass
key = 'respectnulls'
class Func(Condition):
3767class Func(Condition):
3768    """
3769    The base class for all function expressions.
3770
3771    Attributes:
3772        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3773            treated as a variable length argument and the argument's value will be stored as a list.
3774        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3775            for this function expression. These values are used to map this node to a name during parsing
3776            as well as to provide the function's name during SQL string generation. By default the SQL
3777            name is set to the expression's class name transformed to snake case.
3778    """
3779
3780    is_var_len_args = False
3781
3782    @classmethod
3783    def from_arg_list(cls, args):
3784        if cls.is_var_len_args:
3785            all_arg_keys = list(cls.arg_types)
3786            # If this function supports variable length argument treat the last argument as such.
3787            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3788            num_non_var = len(non_var_len_arg_keys)
3789
3790            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3791            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3792        else:
3793            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3794
3795        return cls(**args_dict)
3796
3797    @classmethod
3798    def sql_names(cls):
3799        if cls is Func:
3800            raise NotImplementedError(
3801                "SQL name is only supported by concrete function implementations"
3802            )
3803        if "_sql_names" not in cls.__dict__:
3804            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3805        return cls._sql_names
3806
3807    @classmethod
3808    def sql_name(cls):
3809        return cls.sql_names()[0]
3810
3811    @classmethod
3812    def default_parser_mappings(cls):
3813        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):
3782    @classmethod
3783    def from_arg_list(cls, args):
3784        if cls.is_var_len_args:
3785            all_arg_keys = list(cls.arg_types)
3786            # If this function supports variable length argument treat the last argument as such.
3787            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3788            num_non_var = len(non_var_len_arg_keys)
3789
3790            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3791            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3792        else:
3793            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3794
3795        return cls(**args_dict)
@classmethod
def sql_names(cls):
3797    @classmethod
3798    def sql_names(cls):
3799        if cls is Func:
3800            raise NotImplementedError(
3801                "SQL name is only supported by concrete function implementations"
3802            )
3803        if "_sql_names" not in cls.__dict__:
3804            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3805        return cls._sql_names
@classmethod
def sql_name(cls):
3807    @classmethod
3808    def sql_name(cls):
3809        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3811    @classmethod
3812    def default_parser_mappings(cls):
3813        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3816class AggFunc(Func):
3817    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3820class ParameterizedAgg(AggFunc):
3821    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3824class Abs(Func):
3825    pass
key = 'abs'
class Anonymous(Func):
3828class Anonymous(Func):
3829    arg_types = {"this": True, "expressions": False}
3830    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3835class Hll(AggFunc):
3836    arg_types = {"this": True, "expressions": False}
3837    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3840class ApproxDistinct(AggFunc):
3841    arg_types = {"this": True, "accuracy": False}
3842    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3845class Array(Func):
3846    arg_types = {"expressions": False}
3847    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3851class ToChar(Func):
3852    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3855class GenerateSeries(Func):
3856    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3859class ArrayAgg(AggFunc):
3860    pass
key = 'arrayagg'
class ArrayAll(Func):
3863class ArrayAll(Func):
3864    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3867class ArrayAny(Func):
3868    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3871class ArrayConcat(Func):
3872    arg_types = {"this": True, "expressions": False}
3873    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3876class ArrayContains(Binary, Func):
3877    pass
key = 'arraycontains'
class ArrayContained(Binary):
3880class ArrayContained(Binary):
3881    pass
key = 'arraycontained'
class ArrayFilter(Func):
3884class ArrayFilter(Func):
3885    arg_types = {"this": True, "expression": True}
3886    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3889class ArrayJoin(Func):
3890    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3893class ArraySize(Func):
3894    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3897class ArraySort(Func):
3898    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3901class ArraySum(Func):
3902    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3905class ArrayUnionAgg(AggFunc):
3906    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3909class Avg(AggFunc):
3910    pass
key = 'avg'
class AnyValue(AggFunc):
3913class AnyValue(AggFunc):
3914    pass
key = 'anyvalue'
class Case(Func):
3917class Case(Func):
3918    arg_types = {"this": False, "ifs": True, "default": False}
3919
3920    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3921        instance = _maybe_copy(self, copy)
3922        instance.append(
3923            "ifs",
3924            If(
3925                this=maybe_parse(condition, copy=copy, **opts),
3926                true=maybe_parse(then, copy=copy, **opts),
3927            ),
3928        )
3929        return instance
3930
3931    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3932        instance = _maybe_copy(self, copy)
3933        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3934        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:
3920    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3921        instance = _maybe_copy(self, copy)
3922        instance.append(
3923            "ifs",
3924            If(
3925                this=maybe_parse(condition, copy=copy, **opts),
3926                true=maybe_parse(then, copy=copy, **opts),
3927            ),
3928        )
3929        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3931    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3932        instance = _maybe_copy(self, copy)
3933        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3934        return instance
key = 'case'
class Cast(Func):
3937class Cast(Func):
3938    arg_types = {"this": True, "to": True}
3939
3940    @property
3941    def name(self) -> str:
3942        return self.this.name
3943
3944    @property
3945    def to(self) -> DataType:
3946        return self.args["to"]
3947
3948    @property
3949    def output_name(self) -> str:
3950        return self.name
3951
3952    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3953        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True}
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:
3952    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3953        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
3956class CastToStrType(Func):
3957    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
3960class Collate(Binary):
3961    pass
key = 'collate'
class TryCast(Cast):
3964class TryCast(Cast):
3965    pass
key = 'trycast'
class Ceil(Func):
3968class Ceil(Func):
3969    arg_types = {"this": True, "decimals": False}
3970    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
3973class Coalesce(Func):
3974    arg_types = {"this": True, "expressions": False}
3975    is_var_len_args = True
3976    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
3979class Concat(Func):
3980    arg_types = {"expressions": True}
3981    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
3984class SafeConcat(Concat):
3985    pass
key = 'safeconcat'
class ConcatWs(Concat):
3988class ConcatWs(Concat):
3989    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
3992class Count(AggFunc):
3993    arg_types = {"this": False, "expressions": False}
3994    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
3997class CountIf(AggFunc):
3998    pass
key = 'countif'
class CurrentDate(Func):
4001class CurrentDate(Func):
4002    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4005class CurrentDatetime(Func):
4006    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4009class CurrentTime(Func):
4010    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4013class CurrentTimestamp(Func):
4014    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4017class CurrentUser(Func):
4018    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4021class DateAdd(Func, TimeUnit):
4022    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4025class DateSub(Func, TimeUnit):
4026    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4029class DateDiff(Func, TimeUnit):
4030    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4031    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4034class DateTrunc(Func):
4035    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4038class DatetimeAdd(Func, TimeUnit):
4039    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4042class DatetimeSub(Func, TimeUnit):
4043    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4046class DatetimeDiff(Func, TimeUnit):
4047    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4050class DatetimeTrunc(Func, TimeUnit):
4051    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4054class DayOfWeek(Func):
4055    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4058class DayOfMonth(Func):
4059    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4062class DayOfYear(Func):
4063    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4066class WeekOfYear(Func):
4067    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class LastDateOfMonth(Func):
4070class LastDateOfMonth(Func):
4071    pass
key = 'lastdateofmonth'
class Extract(Func):
4074class Extract(Func):
4075    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4078class TimestampAdd(Func, TimeUnit):
4079    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4082class TimestampSub(Func, TimeUnit):
4083    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4086class TimestampDiff(Func, TimeUnit):
4087    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4090class TimestampTrunc(Func, TimeUnit):
4091    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4094class TimeAdd(Func, TimeUnit):
4095    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4098class TimeSub(Func, TimeUnit):
4099    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4102class TimeDiff(Func, TimeUnit):
4103    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4106class TimeTrunc(Func, TimeUnit):
4107    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4110class DateFromParts(Func):
4111    _sql_names = ["DATEFROMPARTS"]
4112    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4115class DateStrToDate(Func):
4116    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4119class DateToDateStr(Func):
4120    pass
key = 'datetodatestr'
class DateToDi(Func):
4123class DateToDi(Func):
4124    pass
key = 'datetodi'
class Date(Func):
4127class Date(Func):
4128    arg_types = {"expressions": True}
4129    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'date'
class Day(Func):
4132class Day(Func):
4133    pass
key = 'day'
class Decode(Func):
4136class Decode(Func):
4137    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4140class DiToDate(Func):
4141    pass
key = 'ditodate'
class Encode(Func):
4144class Encode(Func):
4145    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4148class Exp(Func):
4149    pass
key = 'exp'
class Explode(Func):
4152class Explode(Func):
4153    pass
key = 'explode'
class Floor(Func):
4156class Floor(Func):
4157    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4160class FromBase64(Func):
4161    pass
key = 'frombase64'
class ToBase64(Func):
4164class ToBase64(Func):
4165    pass
key = 'tobase64'
class Greatest(Func):
4168class Greatest(Func):
4169    arg_types = {"this": True, "expressions": False}
4170    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4173class GroupConcat(Func):
4174    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4177class Hex(Func):
4178    pass
key = 'hex'
class If(Func):
4181class If(Func):
4182    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4185class Initcap(Func):
4186    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4189class JSONKeyValue(Expression):
4190    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4193class JSONObject(Func):
4194    arg_types = {
4195        "expressions": False,
4196        "null_handling": False,
4197        "unique_keys": False,
4198        "return_type": False,
4199        "format_json": False,
4200        "encoding": False,
4201    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4204class OpenJSONColumnDef(Expression):
4205    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):
4208class OpenJSON(Func):
4209    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4212class JSONBContains(Binary):
4213    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4216class JSONExtract(Binary, Func):
4217    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4220class JSONExtractScalar(JSONExtract):
4221    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4224class JSONBExtract(JSONExtract):
4225    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4228class JSONBExtractScalar(JSONExtract):
4229    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4232class JSONFormat(Func):
4233    arg_types = {"this": False, "options": False}
4234    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class Least(Func):
4237class Least(Func):
4238    arg_types = {"expressions": False}
4239    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4242class Left(Func):
4243    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4250class Length(Func):
4251    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4254class Levenshtein(Func):
4255    arg_types = {
4256        "this": True,
4257        "expression": False,
4258        "ins_cost": False,
4259        "del_cost": False,
4260        "sub_cost": False,
4261    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4264class Ln(Func):
4265    pass
key = 'ln'
class Log(Func):
4268class Log(Func):
4269    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4272class Log2(Func):
4273    pass
key = 'log2'
class Log10(Func):
4276class Log10(Func):
4277    pass
key = 'log10'
class LogicalOr(AggFunc):
4280class LogicalOr(AggFunc):
4281    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4284class LogicalAnd(AggFunc):
4285    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4288class Lower(Func):
4289    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4292class Map(Func):
4293    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class StarMap(Func):
4296class StarMap(Func):
4297    pass
key = 'starmap'
class VarMap(Func):
4300class VarMap(Func):
4301    arg_types = {"keys": True, "values": True}
4302    is_var_len_args = True
4303
4304    @property
4305    def keys(self) -> t.List[Expression]:
4306        return self.args["keys"].expressions
4307
4308    @property
4309    def values(self) -> t.List[Expression]:
4310        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4314class MatchAgainst(Func):
4315    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4318class Max(AggFunc):
4319    arg_types = {"this": True, "expressions": False}
4320    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4323class MD5(Func):
4324    _sql_names = ["MD5"]
key = 'md5'
class Min(AggFunc):
4327class Min(AggFunc):
4328    arg_types = {"this": True, "expressions": False}
4329    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4332class Month(Func):
4333    pass
key = 'month'
class Nvl2(Func):
4336class Nvl2(Func):
4337    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4340class Posexplode(Func):
4341    pass
key = 'posexplode'
class Pow(Binary, Func):
4344class Pow(Binary, Func):
4345    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4348class PercentileCont(AggFunc):
4349    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4352class PercentileDisc(AggFunc):
4353    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4356class Quantile(AggFunc):
4357    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4360class ApproxQuantile(Quantile):
4361    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):
4364class RangeN(Func):
4365    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4368class ReadCSV(Func):
4369    _sql_names = ["READ_CSV"]
4370    is_var_len_args = True
4371    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4374class Reduce(Func):
4375    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):
4378class RegexpExtract(Func):
4379    arg_types = {
4380        "this": True,
4381        "expression": True,
4382        "position": False,
4383        "occurrence": False,
4384        "group": False,
4385    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'group': False}
key = 'regexpextract'
class RegexpLike(Func):
4388class RegexpLike(Func):
4389    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4392class RegexpILike(Func):
4393    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4398class RegexpSplit(Func):
4399    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4402class Repeat(Func):
4403    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4406class Round(Func):
4407    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4410class RowNumber(Func):
4411    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4414class SafeDivide(Func):
4415    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4418class SetAgg(AggFunc):
4419    pass
key = 'setagg'
class SHA(Func):
4422class SHA(Func):
4423    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4426class SHA2(Func):
4427    _sql_names = ["SHA2"]
4428    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4431class SortArray(Func):
4432    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4435class Split(Func):
4436    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4441class Substring(Func):
4442    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4445class StandardHash(Func):
4446    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4449class StrPosition(Func):
4450    arg_types = {
4451        "this": True,
4452        "substr": True,
4453        "position": False,
4454        "instance": False,
4455    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4458class StrToDate(Func):
4459    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4462class StrToTime(Func):
4463    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtotime'
class StrToUnix(Func):
4468class StrToUnix(Func):
4469    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4472class NumberToStr(Func):
4473    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4476class FromBase(Func):
4477    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4480class Struct(Func):
4481    arg_types = {"expressions": True}
4482    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4485class StructExtract(Func):
4486    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4489class Sum(AggFunc):
4490    pass
key = 'sum'
class Sqrt(Func):
4493class Sqrt(Func):
4494    pass
key = 'sqrt'
class Stddev(AggFunc):
4497class Stddev(AggFunc):
4498    pass
key = 'stddev'
class StddevPop(AggFunc):
4501class StddevPop(AggFunc):
4502    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4505class StddevSamp(AggFunc):
4506    pass
key = 'stddevsamp'
class TimeToStr(Func):
4509class TimeToStr(Func):
4510    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4513class TimeToTimeStr(Func):
4514    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4517class TimeToUnix(Func):
4518    pass
key = 'timetounix'
class TimeStrToDate(Func):
4521class TimeStrToDate(Func):
4522    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4525class TimeStrToTime(Func):
4526    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4529class TimeStrToUnix(Func):
4530    pass
key = 'timestrtounix'
class Trim(Func):
4533class Trim(Func):
4534    arg_types = {
4535        "this": True,
4536        "expression": False,
4537        "position": False,
4538        "collation": False,
4539    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4542class TsOrDsAdd(Func, TimeUnit):
4543    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4546class TsOrDsToDateStr(Func):
4547    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4550class TsOrDsToDate(Func):
4551    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4554class TsOrDiToDi(Func):
4555    pass
key = 'tsorditodi'
class Unhex(Func):
4558class Unhex(Func):
4559    pass
key = 'unhex'
class UnixToStr(Func):
4562class UnixToStr(Func):
4563    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4568class UnixToTime(Func):
4569    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4570
4571    SECONDS = Literal.string("seconds")
4572    MILLIS = Literal.string("millis")
4573    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):
4576class UnixToTimeStr(Func):
4577    pass
key = 'unixtotimestr'
class Upper(Func):
4580class Upper(Func):
4581    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4584class Variance(AggFunc):
4585    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4588class VariancePop(AggFunc):
4589    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4592class Week(Func):
4593    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4596class XMLTable(Func):
4597    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):
4600class Year(Func):
4601    pass
key = 'year'
class Use(Expression):
4604class Use(Expression):
4605    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4608class Merge(Expression):
4609    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):
4612class When(Func):
4613    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):
4618class NextValueFor(Func):
4619    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.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:
4656def maybe_parse(
4657    sql_or_expression: ExpOrStr,
4658    *,
4659    into: t.Optional[IntoType] = None,
4660    dialect: DialectType = None,
4661    prefix: t.Optional[str] = None,
4662    copy: bool = False,
4663    **opts,
4664) -> Expression:
4665    """Gracefully handle a possible string or expression.
4666
4667    Example:
4668        >>> maybe_parse("1")
4669        (LITERAL this: 1, is_string: False)
4670        >>> maybe_parse(to_identifier("x"))
4671        (IDENTIFIER this: x, quoted: False)
4672
4673    Args:
4674        sql_or_expression: the SQL code string or an expression
4675        into: the SQLGlot Expression to parse into
4676        dialect: the dialect used to parse the input expressions (in the case that an
4677            input expression is a SQL string).
4678        prefix: a string to prefix the sql with before it gets parsed
4679            (automatically includes a space)
4680        copy: whether or not to copy the expression.
4681        **opts: other options to use to parse the input expressions (again, in the case
4682            that an input expression is a SQL string).
4683
4684    Returns:
4685        Expression: the parsed or given expression.
4686    """
4687    if isinstance(sql_or_expression, Expression):
4688        if copy:
4689            return sql_or_expression.copy()
4690        return sql_or_expression
4691
4692    if sql_or_expression is None:
4693        raise ParseError(f"SQL cannot be None")
4694
4695    import sqlglot
4696
4697    sql = str(sql_or_expression)
4698    if prefix:
4699        sql = f"{prefix} {sql}"
4700
4701    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:
4885def union(
4886    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4887) -> Union:
4888    """
4889    Initializes a syntax tree from one UNION expression.
4890
4891    Example:
4892        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4893        'SELECT * FROM foo UNION SELECT * FROM bla'
4894
4895    Args:
4896        left: the SQL code string corresponding to the left-hand side.
4897            If an `Expression` instance is passed, it will be used as-is.
4898        right: the SQL code string corresponding to the right-hand side.
4899            If an `Expression` instance is passed, it will be used as-is.
4900        distinct: set the DISTINCT flag if and only if this is true.
4901        dialect: the dialect used to parse the input expression.
4902        opts: other options to use to parse the input expressions.
4903
4904    Returns:
4905        The new Union instance.
4906    """
4907    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4908    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4909
4910    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:
4913def intersect(
4914    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4915) -> Intersect:
4916    """
4917    Initializes a syntax tree from one INTERSECT expression.
4918
4919    Example:
4920        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4921        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4922
4923    Args:
4924        left: the SQL code string corresponding to the left-hand side.
4925            If an `Expression` instance is passed, it will be used as-is.
4926        right: the SQL code string corresponding to the right-hand side.
4927            If an `Expression` instance is passed, it will be used as-is.
4928        distinct: set the DISTINCT flag if and only if this is true.
4929        dialect: the dialect used to parse the input expression.
4930        opts: other options to use to parse the input expressions.
4931
4932    Returns:
4933        The new Intersect instance.
4934    """
4935    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4936    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4937
4938    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:
4941def except_(
4942    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4943) -> Except:
4944    """
4945    Initializes a syntax tree from one EXCEPT expression.
4946
4947    Example:
4948        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4949        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4950
4951    Args:
4952        left: the SQL code string corresponding to the left-hand side.
4953            If an `Expression` instance is passed, it will be used as-is.
4954        right: the SQL code string corresponding to the right-hand side.
4955            If an `Expression` instance is passed, it will be used as-is.
4956        distinct: set the DISTINCT flag if and only if this is true.
4957        dialect: the dialect used to parse the input expression.
4958        opts: other options to use to parse the input expressions.
4959
4960    Returns:
4961        The new Except instance.
4962    """
4963    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4964    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4965
4966    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:
4969def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4970    """
4971    Initializes a syntax tree from one or multiple SELECT expressions.
4972
4973    Example:
4974        >>> select("col1", "col2").from_("tbl").sql()
4975        'SELECT col1, col2 FROM tbl'
4976
4977    Args:
4978        *expressions: the SQL code string to parse as the expressions of a
4979            SELECT statement. If an Expression instance is passed, this is used as-is.
4980        dialect: the dialect used to parse the input expressions (in the case that an
4981            input expression is a SQL string).
4982        **opts: other options to use to parse the input expressions (again, in the case
4983            that an input expression is a SQL string).
4984
4985    Returns:
4986        Select: the syntax tree for the SELECT statement.
4987    """
4988    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:
4991def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4992    """
4993    Initializes a syntax tree from a FROM expression.
4994
4995    Example:
4996        >>> from_("tbl").select("col1", "col2").sql()
4997        'SELECT col1, col2 FROM tbl'
4998
4999    Args:
5000        *expression: the SQL code string to parse as the FROM expressions of a
5001            SELECT statement. If an Expression instance is passed, this is used as-is.
5002        dialect: the dialect used to parse the input expression (in the case that the
5003            input expression is a SQL string).
5004        **opts: other options to use to parse the input expressions (again, in the case
5005            that the input expression is a SQL string).
5006
5007    Returns:
5008        Select: the syntax tree for the SELECT statement.
5009    """
5010    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:
5013def update(
5014    table: str | Table,
5015    properties: dict,
5016    where: t.Optional[ExpOrStr] = None,
5017    from_: t.Optional[ExpOrStr] = None,
5018    dialect: DialectType = None,
5019    **opts,
5020) -> Update:
5021    """
5022    Creates an update statement.
5023
5024    Example:
5025        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5026        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5027
5028    Args:
5029        *properties: dictionary of properties to set which are
5030            auto converted to sql objects eg None -> NULL
5031        where: sql conditional parsed into a WHERE statement
5032        from_: sql statement parsed into a FROM statement
5033        dialect: the dialect used to parse the input expressions.
5034        **opts: other options to use to parse the input expressions.
5035
5036    Returns:
5037        Update: the syntax tree for the UPDATE statement.
5038    """
5039    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5040    update_expr.set(
5041        "expressions",
5042        [
5043            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5044            for k, v in properties.items()
5045        ],
5046    )
5047    if from_:
5048        update_expr.set(
5049            "from",
5050            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5051        )
5052    if isinstance(where, Condition):
5053        where = Where(this=where)
5054    if where:
5055        update_expr.set(
5056            "where",
5057            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5058        )
5059    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:
5062def delete(
5063    table: ExpOrStr,
5064    where: t.Optional[ExpOrStr] = None,
5065    returning: t.Optional[ExpOrStr] = None,
5066    dialect: DialectType = None,
5067    **opts,
5068) -> Delete:
5069    """
5070    Builds a delete statement.
5071
5072    Example:
5073        >>> delete("my_table", where="id > 1").sql()
5074        'DELETE FROM my_table WHERE id > 1'
5075
5076    Args:
5077        where: sql conditional parsed into a WHERE statement
5078        returning: sql conditional parsed into a RETURNING statement
5079        dialect: the dialect used to parse the input expressions.
5080        **opts: other options to use to parse the input expressions.
5081
5082    Returns:
5083        Delete: the syntax tree for the DELETE statement.
5084    """
5085    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5086    if where:
5087        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5088    if returning:
5089        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5090    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:
5093def insert(
5094    expression: ExpOrStr,
5095    into: ExpOrStr,
5096    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5097    overwrite: t.Optional[bool] = None,
5098    dialect: DialectType = None,
5099    copy: bool = True,
5100    **opts,
5101) -> Insert:
5102    """
5103    Builds an INSERT statement.
5104
5105    Example:
5106        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5107        'INSERT INTO tbl VALUES (1, 2, 3)'
5108
5109    Args:
5110        expression: the sql string or expression of the INSERT statement
5111        into: the tbl to insert data to.
5112        columns: optionally the table's column names.
5113        overwrite: whether to INSERT OVERWRITE or not.
5114        dialect: the dialect used to parse the input expressions.
5115        copy: whether or not to copy the expression.
5116        **opts: other options to use to parse the input expressions.
5117
5118    Returns:
5119        Insert: the syntax tree for the INSERT statement.
5120    """
5121    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5122    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5123
5124    if columns:
5125        this = _apply_list_builder(
5126            *columns,
5127            instance=Schema(this=this),
5128            arg="expressions",
5129            into=Identifier,
5130            copy=False,
5131            dialect=dialect,
5132            **opts,
5133        )
5134
5135    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:
5138def condition(
5139    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5140) -> Condition:
5141    """
5142    Initialize a logical condition expression.
5143
5144    Example:
5145        >>> condition("x=1").sql()
5146        'x = 1'
5147
5148        This is helpful for composing larger logical syntax trees:
5149        >>> where = condition("x=1")
5150        >>> where = where.and_("y=1")
5151        >>> Select().from_("tbl").select("*").where(where).sql()
5152        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5153
5154    Args:
5155        *expression: the SQL code string to parse.
5156            If an Expression instance is passed, this is used as-is.
5157        dialect: the dialect used to parse the input expression (in the case that the
5158            input expression is a SQL string).
5159        copy: Whether or not to copy `expression` (only applies to expressions).
5160        **opts: other options to use to parse the input expressions (again, in the case
5161            that the input expression is a SQL string).
5162
5163    Returns:
5164        The new Condition instance
5165    """
5166    return maybe_parse(
5167        expression,
5168        into=Condition,
5169        dialect=dialect,
5170        copy=copy,
5171        **opts,
5172    )

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:
5175def and_(
5176    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5177) -> Condition:
5178    """
5179    Combine multiple conditions with an AND logical operator.
5180
5181    Example:
5182        >>> and_("x=1", and_("y=1", "z=1")).sql()
5183        'x = 1 AND (y = 1 AND z = 1)'
5184
5185    Args:
5186        *expressions: the SQL code strings to parse.
5187            If an Expression instance is passed, this is used as-is.
5188        dialect: the dialect used to parse the input expression.
5189        copy: whether or not to copy `expressions` (only applies to Expressions).
5190        **opts: other options to use to parse the input expressions.
5191
5192    Returns:
5193        And: the new condition
5194    """
5195    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:
5198def or_(
5199    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5200) -> Condition:
5201    """
5202    Combine multiple conditions with an OR logical operator.
5203
5204    Example:
5205        >>> or_("x=1", or_("y=1", "z=1")).sql()
5206        'x = 1 OR (y = 1 OR z = 1)'
5207
5208    Args:
5209        *expressions: the SQL code strings to parse.
5210            If an Expression instance is passed, this is used as-is.
5211        dialect: the dialect used to parse the input expression.
5212        copy: whether or not to copy `expressions` (only applies to Expressions).
5213        **opts: other options to use to parse the input expressions.
5214
5215    Returns:
5216        Or: the new condition
5217    """
5218    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:
5221def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5222    """
5223    Wrap a condition with a NOT operator.
5224
5225    Example:
5226        >>> not_("this_suit='black'").sql()
5227        "NOT this_suit = 'black'"
5228
5229    Args:
5230        expression: the SQL code string to parse.
5231            If an Expression instance is passed, this is used as-is.
5232        dialect: the dialect used to parse the input expression.
5233        copy: whether to copy the expression or not.
5234        **opts: other options to use to parse the input expressions.
5235
5236    Returns:
5237        The new condition.
5238    """
5239    this = condition(
5240        expression,
5241        dialect=dialect,
5242        copy=copy,
5243        **opts,
5244    )
5245    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:
5248def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5249    """
5250    Wrap an expression in parentheses.
5251
5252    Example:
5253        >>> paren("5 + 3").sql()
5254        '(5 + 3)'
5255
5256    Args:
5257        expression: the SQL code string to parse.
5258            If an Expression instance is passed, this is used as-is.
5259        copy: whether to copy the expression or not.
5260
5261    Returns:
5262        The wrapped expression.
5263    """
5264    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):
5282def to_identifier(name, quoted=None, copy=True):
5283    """Builds an identifier.
5284
5285    Args:
5286        name: The name to turn into an identifier.
5287        quoted: Whether or not force quote the identifier.
5288        copy: Whether or not to copy a passed in Identefier node.
5289
5290    Returns:
5291        The identifier ast node.
5292    """
5293
5294    if name is None:
5295        return None
5296
5297    if isinstance(name, Identifier):
5298        identifier = _maybe_copy(name, copy)
5299    elif isinstance(name, str):
5300        identifier = Identifier(
5301            this=name,
5302            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5303        )
5304    else:
5305        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5306    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:
5312def to_interval(interval: str | Literal) -> Interval:
5313    """Builds an interval expression from a string like '1 day' or '5 months'."""
5314    if isinstance(interval, Literal):
5315        if not interval.is_string:
5316            raise ValueError("Invalid interval string.")
5317
5318        interval = interval.this
5319
5320    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5321
5322    if not interval_parts:
5323        raise ValueError("Invalid interval string.")
5324
5325    return Interval(
5326        this=Literal.string(interval_parts.group(1)),
5327        unit=Var(this=interval_parts.group(2)),
5328    )

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

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:
5500def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5501    """Cast an expression to a data type.
5502
5503    Example:
5504        >>> cast('x + 1', 'int').sql()
5505        'CAST(x + 1 AS INT)'
5506
5507    Args:
5508        expression: The expression to cast.
5509        to: The datatype to cast to.
5510
5511    Returns:
5512        The new Cast instance.
5513    """
5514    expression = maybe_parse(expression, **opts)
5515    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:
5518def table_(
5519    table: Identifier | str,
5520    db: t.Optional[Identifier | str] = None,
5521    catalog: t.Optional[Identifier | str] = None,
5522    quoted: t.Optional[bool] = None,
5523    alias: t.Optional[Identifier | str] = None,
5524) -> Table:
5525    """Build a Table.
5526
5527    Args:
5528        table: Table name.
5529        db: Database name.
5530        catalog: Catalog name.
5531        quote: Whether to force quotes on the table's identifiers.
5532        alias: Table's alias.
5533
5534    Returns:
5535        The new Table instance.
5536    """
5537    return Table(
5538        this=to_identifier(table, quoted=quoted),
5539        db=to_identifier(db, quoted=quoted),
5540        catalog=to_identifier(catalog, quoted=quoted),
5541        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5542    )

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:
5545def values(
5546    values: t.Iterable[t.Tuple[t.Any, ...]],
5547    alias: t.Optional[str] = None,
5548    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5549) -> Values:
5550    """Build VALUES statement.
5551
5552    Example:
5553        >>> values([(1, '2')]).sql()
5554        "VALUES (1, '2')"
5555
5556    Args:
5557        values: values statements that will be converted to SQL
5558        alias: optional alias
5559        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5560         If either are provided then an alias is also required.
5561
5562    Returns:
5563        Values: the Values expression object
5564    """
5565    if columns and not alias:
5566        raise ValueError("Alias is required when providing columns")
5567
5568    return Values(
5569        expressions=[convert(tup) for tup in values],
5570        alias=(
5571            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5572            if columns
5573            else (TableAlias(this=to_identifier(alias)) if alias else None)
5574        ),
5575    )

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:
5578def var(name: t.Optional[ExpOrStr]) -> Var:
5579    """Build a SQL variable.
5580
5581    Example:
5582        >>> repr(var('x'))
5583        '(VAR this: x)'
5584
5585        >>> repr(var(column('x', table='y')))
5586        '(VAR this: x)'
5587
5588    Args:
5589        name: The name of the var or an expression who's name will become the var.
5590
5591    Returns:
5592        The new variable node.
5593    """
5594    if not name:
5595        raise ValueError("Cannot convert empty name into var.")
5596
5597    if isinstance(name, Expression):
5598        name = name.name
5599    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:
5602def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5603    """Build ALTER TABLE... RENAME... expression
5604
5605    Args:
5606        old_name: The old name of the table
5607        new_name: The new name of the table
5608
5609    Returns:
5610        Alter table expression
5611    """
5612    old_table = to_table(old_name)
5613    new_table = to_table(new_name)
5614    return AlterTable(
5615        this=old_table,
5616        actions=[
5617            RenameTable(this=new_table),
5618        ],
5619    )

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

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) -> str:
5709def table_name(table: Table | str) -> str:
5710    """Get the full name of a table as a string.
5711
5712    Args:
5713        table: table expression node or string.
5714
5715    Examples:
5716        >>> from sqlglot import exp, parse_one
5717        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5718        'a.b.c'
5719
5720    Returns:
5721        The table name.
5722    """
5723
5724    table = maybe_parse(table, into=Table)
5725
5726    if not table:
5727        raise ValueError(f"Cannot parse {table}")
5728
5729    return ".".join(part for part in (table.text("catalog"), table.text("db"), table.name) if part)

Get the full name of a table as a string.

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

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5887def false() -> Boolean:
5888    """
5889    Returns a false Boolean expression.
5890    """
5891    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5894def null() -> Null:
5895    """
5896    Returns a Null expression.
5897    """
5898    return Null()

Returns a Null expression.

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