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

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

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)
class Predicate(Condition):
868class Predicate(Condition):
869    """Relationships like x = y, x > 1, x >= y."""

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

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

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 []
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    }
class Uncache(Expression):
977class Uncache(Expression):
978    arg_types = {"this": True, "exists": False}
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    }
class Clone(Expression):
 999class Clone(Expression):
1000    arg_types = {
1001        "this": True,
1002        "when": False,
1003        "kind": False,
1004        "expression": False,
1005    }
class Describe(Expression):
1008class Describe(Expression):
1009    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
1012class Pragma(Expression):
1013    pass
class Set(Expression):
1016class Set(Expression):
1017    arg_types = {"expressions": False}
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    }
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    }
class UserDefinedFunction(Expression):
1050class UserDefinedFunction(Expression):
1051    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
1054class CharacterSet(Expression):
1055    arg_types = {"this": True, "default": False}
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"))
class WithinGroup(Expression):
1066class WithinGroup(Expression):
1067    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
1070class CTE(DerivedTable):
1071    arg_types = {"this": True, "alias": True}
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 []
class BitString(Condition):
1082class BitString(Condition):
1083    pass
class HexString(Condition):
1086class HexString(Condition):
1087    pass
class ByteString(Condition):
1090class ByteString(Condition):
1091    pass
class RawString(Condition):
1094class RawString(Condition):
1095    pass
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)
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.

class ColumnPosition(Expression):
1139class ColumnPosition(Expression):
1140    arg_types = {"this": False, "position": True}
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 []
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    }
class RenameTable(Expression):
1168class RenameTable(Expression):
1169    pass
class SetTag(Expression):
1172class SetTag(Expression):
1173    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
1176class Comment(Expression):
1177    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
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    }
class MergeTreeTTL(Expression):
1192class MergeTreeTTL(Expression):
1193    arg_types = {
1194        "expressions": True,
1195        "where": False,
1196        "group": False,
1197        "aggregates": False,
1198    }
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"]
class ColumnConstraintKind(Expression):
1209class ColumnConstraintKind(Expression):
1210    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1213class AutoIncrementColumnConstraint(ColumnConstraintKind):
1214    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1217class CaseSpecificColumnConstraint(ColumnConstraintKind):
1218    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1221class CharacterSetColumnConstraint(ColumnConstraintKind):
1222    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1225class CheckColumnConstraint(ColumnConstraintKind):
1226    pass
class CollateColumnConstraint(ColumnConstraintKind):
1229class CollateColumnConstraint(ColumnConstraintKind):
1230    pass
class CommentColumnConstraint(ColumnConstraintKind):
1233class CommentColumnConstraint(ColumnConstraintKind):
1234    pass
class CompressColumnConstraint(ColumnConstraintKind):
1237class CompressColumnConstraint(ColumnConstraintKind):
1238    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1241class DateFormatColumnConstraint(ColumnConstraintKind):
1242    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1245class DefaultColumnConstraint(ColumnConstraintKind):
1246    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1249class EncodeColumnConstraint(ColumnConstraintKind):
1250    pass
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    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1267class InlineLengthColumnConstraint(ColumnConstraintKind):
1268    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1271class NotNullColumnConstraint(ColumnConstraintKind):
1272    arg_types = {"allow_null": False}
class OnUpdateColumnConstraint(ColumnConstraintKind):
1276class OnUpdateColumnConstraint(ColumnConstraintKind):
1277    pass
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1280class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1281    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1284class TitleColumnConstraint(ColumnConstraintKind):
1285    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1288class UniqueColumnConstraint(ColumnConstraintKind):
1289    arg_types = {"this": False}
class UppercaseColumnConstraint(ColumnConstraintKind):
1292class UppercaseColumnConstraint(ColumnConstraintKind):
1293    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1296class PathColumnConstraint(ColumnConstraintKind):
1297    pass
class Constraint(Expression):
1300class Constraint(Expression):
1301    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1304class Delete(Expression):
1305    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1306
1307    def delete(
1308        self,
1309        table: ExpOrStr,
1310        dialect: DialectType = None,
1311        copy: bool = True,
1312        **opts,
1313    ) -> Delete:
1314        """
1315        Create a DELETE expression or replace the table on an existing DELETE expression.
1316
1317        Example:
1318            >>> delete("tbl").sql()
1319            'DELETE FROM tbl'
1320
1321        Args:
1322            table: the table from which to delete.
1323            dialect: the dialect used to parse the input expression.
1324            copy: if `False`, modify this expression instance in-place.
1325            opts: other options to use to parse the input expressions.
1326
1327        Returns:
1328            Delete: the modified expression.
1329        """
1330        return _apply_builder(
1331            expression=table,
1332            instance=self,
1333            arg="this",
1334            dialect=dialect,
1335            into=Table,
1336            copy=copy,
1337            **opts,
1338        )
1339
1340    def where(
1341        self,
1342        *expressions: t.Optional[ExpOrStr],
1343        append: bool = True,
1344        dialect: DialectType = None,
1345        copy: bool = True,
1346        **opts,
1347    ) -> Delete:
1348        """
1349        Append to or set the WHERE expressions.
1350
1351        Example:
1352            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1353            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1354
1355        Args:
1356            *expressions: the SQL code strings to parse.
1357                If an `Expression` instance is passed, it will be used as-is.
1358                Multiple expressions are combined with an AND operator.
1359            append: if `True`, AND the new expressions to any existing expression.
1360                Otherwise, this resets the expression.
1361            dialect: the dialect used to parse the input expressions.
1362            copy: if `False`, modify this expression instance in-place.
1363            opts: other options to use to parse the input expressions.
1364
1365        Returns:
1366            Delete: the modified expression.
1367        """
1368        return _apply_conjunction_builder(
1369            *expressions,
1370            instance=self,
1371            arg="where",
1372            append=append,
1373            into=Where,
1374            dialect=dialect,
1375            copy=copy,
1376            **opts,
1377        )
1378
1379    def returning(
1380        self,
1381        expression: ExpOrStr,
1382        dialect: DialectType = None,
1383        copy: bool = True,
1384        **opts,
1385    ) -> Delete:
1386        """
1387        Set the RETURNING expression. Not supported by all dialects.
1388
1389        Example:
1390            >>> delete("tbl").returning("*", dialect="postgres").sql()
1391            'DELETE FROM tbl RETURNING *'
1392
1393        Args:
1394            expression: the SQL code strings to parse.
1395                If an `Expression` instance is passed, it will be used as-is.
1396            dialect: the dialect used to parse the input expressions.
1397            copy: if `False`, modify this expression instance in-place.
1398            opts: other options to use to parse the input expressions.
1399
1400        Returns:
1401            Delete: the modified expression.
1402        """
1403        return _apply_builder(
1404            expression=expression,
1405            instance=self,
1406            arg="returning",
1407            prefix="RETURNING",
1408            dialect=dialect,
1409            copy=copy,
1410            into=Returning,
1411            **opts,
1412        )
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:
1307    def delete(
1308        self,
1309        table: ExpOrStr,
1310        dialect: DialectType = None,
1311        copy: bool = True,
1312        **opts,
1313    ) -> Delete:
1314        """
1315        Create a DELETE expression or replace the table on an existing DELETE expression.
1316
1317        Example:
1318            >>> delete("tbl").sql()
1319            'DELETE FROM tbl'
1320
1321        Args:
1322            table: the table from which to delete.
1323            dialect: the dialect used to parse the input expression.
1324            copy: if `False`, modify this expression instance in-place.
1325            opts: other options to use to parse the input expressions.
1326
1327        Returns:
1328            Delete: the modified expression.
1329        """
1330        return _apply_builder(
1331            expression=table,
1332            instance=self,
1333            arg="this",
1334            dialect=dialect,
1335            into=Table,
1336            copy=copy,
1337            **opts,
1338        )

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

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

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.

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

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.

class OnConflict(Expression):
1563class OnConflict(Expression):
1564    arg_types = {
1565        "duplicate": False,
1566        "expressions": False,
1567        "nothing": False,
1568        "key": False,
1569        "constraint": False,
1570    }
class Returning(Expression):
1573class Returning(Expression):
1574    arg_types = {"expressions": True}
class Introducer(Expression):
1578class Introducer(Expression):
1579    arg_types = {"this": True, "expression": True}
class National(Expression):
1583class National(Expression):
1584    pass
class LoadData(Expression):
1587class LoadData(Expression):
1588    arg_types = {
1589        "this": True,
1590        "local": False,
1591        "overwrite": False,
1592        "inpath": True,
1593        "partition": False,
1594        "input_format": False,
1595        "serde": False,
1596    }
class Partition(Expression):
1599class Partition(Expression):
1600    arg_types = {"expressions": True}
class Fetch(Expression):
1603class Fetch(Expression):
1604    arg_types = {
1605        "direction": False,
1606        "count": False,
1607        "percent": False,
1608        "with_ties": False,
1609    }
class Group(Expression):
1612class Group(Expression):
1613    arg_types = {
1614        "expressions": False,
1615        "grouping_sets": False,
1616        "cube": False,
1617        "rollup": False,
1618        "totals": False,
1619    }
class Lambda(Expression):
1622class Lambda(Expression):
1623    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1626class Limit(Expression):
1627    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1630class Literal(Condition):
1631    arg_types = {"this": True, "is_string": True}
1632
1633    @property
1634    def hashable_args(self) -> t.Any:
1635        return (self.this, self.args.get("is_string"))
1636
1637    @classmethod
1638    def number(cls, number) -> Literal:
1639        return cls(this=str(number), is_string=False)
1640
1641    @classmethod
1642    def string(cls, string) -> Literal:
1643        return cls(this=str(string), is_string=True)
1644
1645    @property
1646    def output_name(self) -> str:
1647        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1637    @classmethod
1638    def number(cls, number) -> Literal:
1639        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1641    @classmethod
1642    def string(cls, string) -> Literal:
1643        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
''
class Join(Expression):
1650class Join(Expression):
1651    arg_types = {
1652        "this": True,
1653        "on": False,
1654        "side": False,
1655        "kind": False,
1656        "using": False,
1657        "natural": False,
1658        "global": False,
1659        "hint": False,
1660    }
1661
1662    @property
1663    def kind(self) -> str:
1664        return self.text("kind").upper()
1665
1666    @property
1667    def side(self) -> str:
1668        return self.text("side").upper()
1669
1670    @property
1671    def hint(self) -> str:
1672        return self.text("hint").upper()
1673
1674    @property
1675    def alias_or_name(self) -> str:
1676        return self.this.alias_or_name
1677
1678    def on(
1679        self,
1680        *expressions: t.Optional[ExpOrStr],
1681        append: bool = True,
1682        dialect: DialectType = None,
1683        copy: bool = True,
1684        **opts,
1685    ) -> Join:
1686        """
1687        Append to or set the ON expressions.
1688
1689        Example:
1690            >>> import sqlglot
1691            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1692            'JOIN x ON y = 1'
1693
1694        Args:
1695            *expressions: the SQL code strings to parse.
1696                If an `Expression` instance is passed, it will be used as-is.
1697                Multiple expressions are combined with an AND operator.
1698            append: if `True`, AND the new expressions to any existing expression.
1699                Otherwise, this resets the expression.
1700            dialect: the dialect used to parse the input expressions.
1701            copy: if `False`, modify this expression instance in-place.
1702            opts: other options to use to parse the input expressions.
1703
1704        Returns:
1705            The modified Join expression.
1706        """
1707        join = _apply_conjunction_builder(
1708            *expressions,
1709            instance=self,
1710            arg="on",
1711            append=append,
1712            dialect=dialect,
1713            copy=copy,
1714            **opts,
1715        )
1716
1717        if join.kind == "CROSS":
1718            join.set("kind", None)
1719
1720        return join
1721
1722    def using(
1723        self,
1724        *expressions: t.Optional[ExpOrStr],
1725        append: bool = True,
1726        dialect: DialectType = None,
1727        copy: bool = True,
1728        **opts,
1729    ) -> Join:
1730        """
1731        Append to or set the USING expressions.
1732
1733        Example:
1734            >>> import sqlglot
1735            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1736            'JOIN x USING (foo, bla)'
1737
1738        Args:
1739            *expressions: the SQL code strings to parse.
1740                If an `Expression` instance is passed, it will be used as-is.
1741            append: if `True`, concatenate the new expressions to the existing "using" list.
1742                Otherwise, this resets the expression.
1743            dialect: the dialect used to parse the input expressions.
1744            copy: if `False`, modify this expression instance in-place.
1745            opts: other options to use to parse the input expressions.
1746
1747        Returns:
1748            The modified Join expression.
1749        """
1750        join = _apply_list_builder(
1751            *expressions,
1752            instance=self,
1753            arg="using",
1754            append=append,
1755            dialect=dialect,
1756            copy=copy,
1757            **opts,
1758        )
1759
1760        if join.kind == "CROSS":
1761            join.set("kind", None)
1762
1763        return join
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:
1678    def on(
1679        self,
1680        *expressions: t.Optional[ExpOrStr],
1681        append: bool = True,
1682        dialect: DialectType = None,
1683        copy: bool = True,
1684        **opts,
1685    ) -> Join:
1686        """
1687        Append to or set the ON expressions.
1688
1689        Example:
1690            >>> import sqlglot
1691            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1692            'JOIN x ON y = 1'
1693
1694        Args:
1695            *expressions: the SQL code strings to parse.
1696                If an `Expression` instance is passed, it will be used as-is.
1697                Multiple expressions are combined with an AND operator.
1698            append: if `True`, AND the new expressions to any existing expression.
1699                Otherwise, this resets the expression.
1700            dialect: the dialect used to parse the input expressions.
1701            copy: if `False`, modify this expression instance in-place.
1702            opts: other options to use to parse the input expressions.
1703
1704        Returns:
1705            The modified Join expression.
1706        """
1707        join = _apply_conjunction_builder(
1708            *expressions,
1709            instance=self,
1710            arg="on",
1711            append=append,
1712            dialect=dialect,
1713            copy=copy,
1714            **opts,
1715        )
1716
1717        if join.kind == "CROSS":
1718            join.set("kind", None)
1719
1720        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:
1722    def using(
1723        self,
1724        *expressions: t.Optional[ExpOrStr],
1725        append: bool = True,
1726        dialect: DialectType = None,
1727        copy: bool = True,
1728        **opts,
1729    ) -> Join:
1730        """
1731        Append to or set the USING expressions.
1732
1733        Example:
1734            >>> import sqlglot
1735            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1736            'JOIN x USING (foo, bla)'
1737
1738        Args:
1739            *expressions: the SQL code strings to parse.
1740                If an `Expression` instance is passed, it will be used as-is.
1741            append: if `True`, concatenate the new expressions to the existing "using" list.
1742                Otherwise, this resets the expression.
1743            dialect: the dialect used to parse the input expressions.
1744            copy: if `False`, modify this expression instance in-place.
1745            opts: other options to use to parse the input expressions.
1746
1747        Returns:
1748            The modified Join expression.
1749        """
1750        join = _apply_list_builder(
1751            *expressions,
1752            instance=self,
1753            arg="using",
1754            append=append,
1755            dialect=dialect,
1756            copy=copy,
1757            **opts,
1758        )
1759
1760        if join.kind == "CROSS":
1761            join.set("kind", None)
1762
1763        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.

class Lateral(UDTF):
1766class Lateral(UDTF):
1767    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1770class MatchRecognize(Expression):
1771    arg_types = {
1772        "partition_by": False,
1773        "order": False,
1774        "measures": False,
1775        "rows": False,
1776        "after": False,
1777        "pattern": False,
1778        "define": False,
1779        "alias": False,
1780    }
class Final(Expression):
1785class Final(Expression):
1786    pass
class Offset(Expression):
1789class Offset(Expression):
1790    arg_types = {"this": False, "expression": True}
class Order(Expression):
1793class Order(Expression):
1794    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1799class Cluster(Order):
1800    pass
class Distribute(Order):
1803class Distribute(Order):
1804    pass
class Sort(Order):
1807class Sort(Order):
1808    pass
class Ordered(Expression):
1811class Ordered(Expression):
1812    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1815class Property(Expression):
1816    arg_types = {"this": True, "value": True}
class AlgorithmProperty(Property):
1819class AlgorithmProperty(Property):
1820    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1823class AutoIncrementProperty(Property):
1824    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1827class BlockCompressionProperty(Property):
1828    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1831class CharacterSetProperty(Property):
1832    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1835class ChecksumProperty(Property):
1836    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1839class CollateProperty(Property):
1840    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1843class DataBlocksizeProperty(Property):
1844    arg_types = {
1845        "size": False,
1846        "units": False,
1847        "minimum": False,
1848        "maximum": False,
1849        "default": False,
1850    }
class DefinerProperty(Property):
1853class DefinerProperty(Property):
1854    arg_types = {"this": True}
class DistKeyProperty(Property):
1857class DistKeyProperty(Property):
1858    arg_types = {"this": True}
class DistStyleProperty(Property):
1861class DistStyleProperty(Property):
1862    arg_types = {"this": True}
class EngineProperty(Property):
1865class EngineProperty(Property):
1866    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1869class ExecuteAsProperty(Property):
1870    arg_types = {"this": True}
class ExternalProperty(Property):
1873class ExternalProperty(Property):
1874    arg_types = {"this": False}
class FallbackProperty(Property):
1877class FallbackProperty(Property):
1878    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1881class FileFormatProperty(Property):
1882    arg_types = {"this": True}
class FreespaceProperty(Property):
1885class FreespaceProperty(Property):
1886    arg_types = {"this": True, "percent": False}
class InputOutputFormat(Expression):
1889class InputOutputFormat(Expression):
1890    arg_types = {"input_format": False, "output_format": False}
class IsolatedLoadingProperty(Property):
1893class IsolatedLoadingProperty(Property):
1894    arg_types = {
1895        "no": True,
1896        "concurrent": True,
1897        "for_all": True,
1898        "for_insert": True,
1899        "for_none": True,
1900    }
class JournalProperty(Property):
1903class JournalProperty(Property):
1904    arg_types = {
1905        "no": False,
1906        "dual": False,
1907        "before": False,
1908        "local": False,
1909        "after": False,
1910    }
class LanguageProperty(Property):
1913class LanguageProperty(Property):
1914    arg_types = {"this": True}
class LikeProperty(Property):
1917class LikeProperty(Property):
1918    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1921class LocationProperty(Property):
1922    arg_types = {"this": True}
class LockingProperty(Property):
1925class LockingProperty(Property):
1926    arg_types = {
1927        "this": False,
1928        "kind": True,
1929        "for_or_in": True,
1930        "lock_type": True,
1931        "override": False,
1932    }
class LogProperty(Property):
1935class LogProperty(Property):
1936    arg_types = {"no": True}
class MaterializedProperty(Property):
1939class MaterializedProperty(Property):
1940    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1943class MergeBlockRatioProperty(Property):
1944    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1947class NoPrimaryIndexProperty(Property):
1948    arg_types = {}
class OnCommitProperty(Property):
1951class OnCommitProperty(Property):
1952    arg_type = {"delete": False}
class PartitionedByProperty(Property):
1955class PartitionedByProperty(Property):
1956    arg_types = {"this": True}
class ReturnsProperty(Property):
1959class ReturnsProperty(Property):
1960    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatProperty(Property):
1963class RowFormatProperty(Property):
1964    arg_types = {"this": True}
class RowFormatDelimitedProperty(Property):
1967class RowFormatDelimitedProperty(Property):
1968    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1969    arg_types = {
1970        "fields": False,
1971        "escaped": False,
1972        "collection_items": False,
1973        "map_keys": False,
1974        "lines": False,
1975        "null": False,
1976        "serde": False,
1977    }
class RowFormatSerdeProperty(Property):
1980class RowFormatSerdeProperty(Property):
1981    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1984class SchemaCommentProperty(Property):
1985    arg_types = {"this": True}
class SerdeProperties(Property):
1988class SerdeProperties(Property):
1989    arg_types = {"expressions": True}
class SetProperty(Property):
1992class SetProperty(Property):
1993    arg_types = {"multi": True}
class SettingsProperty(Property):
1996class SettingsProperty(Property):
1997    arg_types = {"expressions": True}
class SortKeyProperty(Property):
2000class SortKeyProperty(Property):
2001    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
2004class SqlSecurityProperty(Property):
2005    arg_types = {"definer": True}
class StabilityProperty(Property):
2008class StabilityProperty(Property):
2009    arg_types = {"this": True}
class TemporaryProperty(Property):
2012class TemporaryProperty(Property):
2013    arg_types = {}
class TransientProperty(Property):
2016class TransientProperty(Property):
2017    arg_types = {"this": False}
class VolatileProperty(Property):
2020class VolatileProperty(Property):
2021    arg_types = {"this": False}
class WithDataProperty(Property):
2024class WithDataProperty(Property):
2025    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
2028class WithJournalTableProperty(Property):
2029    arg_types = {"this": True}
class Properties(Expression):
2032class Properties(Expression):
2033    arg_types = {"expressions": True}
2034
2035    NAME_TO_PROPERTY = {
2036        "ALGORITHM": AlgorithmProperty,
2037        "AUTO_INCREMENT": AutoIncrementProperty,
2038        "CHARACTER SET": CharacterSetProperty,
2039        "COLLATE": CollateProperty,
2040        "COMMENT": SchemaCommentProperty,
2041        "DEFINER": DefinerProperty,
2042        "DISTKEY": DistKeyProperty,
2043        "DISTSTYLE": DistStyleProperty,
2044        "ENGINE": EngineProperty,
2045        "EXECUTE AS": ExecuteAsProperty,
2046        "FORMAT": FileFormatProperty,
2047        "LANGUAGE": LanguageProperty,
2048        "LOCATION": LocationProperty,
2049        "PARTITIONED_BY": PartitionedByProperty,
2050        "RETURNS": ReturnsProperty,
2051        "ROW_FORMAT": RowFormatProperty,
2052        "SORTKEY": SortKeyProperty,
2053    }
2054
2055    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2056
2057    # CREATE property locations
2058    # Form: schema specified
2059    #   create [POST_CREATE]
2060    #     table a [POST_NAME]
2061    #     (b int) [POST_SCHEMA]
2062    #     with ([POST_WITH])
2063    #     index (b) [POST_INDEX]
2064    #
2065    # Form: alias selection
2066    #   create [POST_CREATE]
2067    #     table a [POST_NAME]
2068    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2069    #     index (c) [POST_INDEX]
2070    class Location(AutoName):
2071        POST_CREATE = auto()
2072        POST_NAME = auto()
2073        POST_SCHEMA = auto()
2074        POST_WITH = auto()
2075        POST_ALIAS = auto()
2076        POST_EXPRESSION = auto()
2077        POST_INDEX = auto()
2078        UNSUPPORTED = auto()
2079
2080    @classmethod
2081    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2082        expressions = []
2083        for key, value in properties_dict.items():
2084            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2085            if property_cls:
2086                expressions.append(property_cls(this=convert(value)))
2087            else:
2088                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2089
2090        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict: Dict) -> sqlglot.expressions.Properties:
2080    @classmethod
2081    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2082        expressions = []
2083        for key, value in properties_dict.items():
2084            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2085            if property_cls:
2086                expressions.append(property_cls(this=convert(value)))
2087            else:
2088                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2089
2090        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
2070    class Location(AutoName):
2071        POST_CREATE = auto()
2072        POST_NAME = auto()
2073        POST_SCHEMA = auto()
2074        POST_WITH = auto()
2075        POST_ALIAS = auto()
2076        POST_EXPRESSION = auto()
2077        POST_INDEX = auto()
2078        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):
2093class Qualify(Expression):
2094    pass
class Return(Expression):
2098class Return(Expression):
2099    pass
class Reference(Expression):
2102class Reference(Expression):
2103    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
2106class Tuple(Expression):
2107    arg_types = {"expressions": False}
2108
2109    def isin(
2110        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2111    ) -> In:
2112        return In(
2113            this=_maybe_copy(self, copy),
2114            expressions=[convert(e, copy=copy) for e in expressions],
2115            query=maybe_parse(query, copy=copy, **opts) if query else None,
2116        )
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2109    def isin(
2110        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2111    ) -> In:
2112        return In(
2113            this=_maybe_copy(self, copy),
2114            expressions=[convert(e, copy=copy) for e in expressions],
2115            query=maybe_parse(query, copy=copy, **opts) if query else None,
2116        )
class Subqueryable(Unionable):
2119class Subqueryable(Unionable):
2120    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2121        """
2122        Convert this expression to an aliased expression that can be used as a Subquery.
2123
2124        Example:
2125            >>> subquery = Select().select("x").from_("tbl").subquery()
2126            >>> Select().select("x").from_(subquery).sql()
2127            'SELECT x FROM (SELECT x FROM tbl)'
2128
2129        Args:
2130            alias (str | Identifier): an optional alias for the subquery
2131            copy (bool): if `False`, modify this expression instance in-place.
2132
2133        Returns:
2134            Alias: the subquery
2135        """
2136        instance = _maybe_copy(self, copy)
2137        if not isinstance(alias, Expression):
2138            alias = TableAlias(this=to_identifier(alias)) if alias else None
2139
2140        return Subquery(this=instance, alias=alias)
2141
2142    def limit(
2143        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2144    ) -> Select:
2145        raise NotImplementedError
2146
2147    @property
2148    def ctes(self):
2149        with_ = self.args.get("with")
2150        if not with_:
2151            return []
2152        return with_.expressions
2153
2154    @property
2155    def selects(self):
2156        raise NotImplementedError("Subqueryable objects must implement `selects`")
2157
2158    @property
2159    def named_selects(self):
2160        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2161
2162    def with_(
2163        self,
2164        alias: ExpOrStr,
2165        as_: ExpOrStr,
2166        recursive: t.Optional[bool] = None,
2167        append: bool = True,
2168        dialect: DialectType = None,
2169        copy: bool = True,
2170        **opts,
2171    ) -> Subqueryable:
2172        """
2173        Append to or set the common table expressions.
2174
2175        Example:
2176            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2177            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2178
2179        Args:
2180            alias: the SQL code string to parse as the table name.
2181                If an `Expression` instance is passed, this is used as-is.
2182            as_: the SQL code string to parse as the table expression.
2183                If an `Expression` instance is passed, it will be used as-is.
2184            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2185            append: if `True`, add to any existing expressions.
2186                Otherwise, this resets the expressions.
2187            dialect: the dialect used to parse the input expression.
2188            copy: if `False`, modify this expression instance in-place.
2189            opts: other options to use to parse the input expressions.
2190
2191        Returns:
2192            The modified expression.
2193        """
2194        return _apply_cte_builder(
2195            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2196        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2120    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2121        """
2122        Convert this expression to an aliased expression that can be used as a Subquery.
2123
2124        Example:
2125            >>> subquery = Select().select("x").from_("tbl").subquery()
2126            >>> Select().select("x").from_(subquery).sql()
2127            'SELECT x FROM (SELECT x FROM tbl)'
2128
2129        Args:
2130            alias (str | Identifier): an optional alias for the subquery
2131            copy (bool): if `False`, modify this expression instance in-place.
2132
2133        Returns:
2134            Alias: the subquery
2135        """
2136        instance = _maybe_copy(self, copy)
2137        if not isinstance(alias, Expression):
2138            alias = TableAlias(this=to_identifier(alias)) if alias else None
2139
2140        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:
2142    def limit(
2143        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2144    ) -> Select:
2145        raise NotImplementedError
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:
2162    def with_(
2163        self,
2164        alias: ExpOrStr,
2165        as_: ExpOrStr,
2166        recursive: t.Optional[bool] = None,
2167        append: bool = True,
2168        dialect: DialectType = None,
2169        copy: bool = True,
2170        **opts,
2171    ) -> Subqueryable:
2172        """
2173        Append to or set the common table expressions.
2174
2175        Example:
2176            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2177            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2178
2179        Args:
2180            alias: the SQL code string to parse as the table name.
2181                If an `Expression` instance is passed, this is used as-is.
2182            as_: the SQL code string to parse as the table expression.
2183                If an `Expression` instance is passed, it will be used as-is.
2184            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2185            append: if `True`, add to any existing expressions.
2186                Otherwise, this resets the expressions.
2187            dialect: the dialect used to parse the input expression.
2188            copy: if `False`, modify this expression instance in-place.
2189            opts: other options to use to parse the input expressions.
2190
2191        Returns:
2192            The modified expression.
2193        """
2194        return _apply_cte_builder(
2195            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2196        )

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.

class Table(Expression):
2222class Table(Expression):
2223    arg_types = {
2224        "this": True,
2225        "alias": False,
2226        "db": False,
2227        "catalog": False,
2228        "laterals": False,
2229        "joins": False,
2230        "pivots": False,
2231        "hints": False,
2232        "system_time": False,
2233    }
2234
2235    @property
2236    def db(self) -> str:
2237        return self.text("db")
2238
2239    @property
2240    def catalog(self) -> str:
2241        return self.text("catalog")
2242
2243    @property
2244    def parts(self) -> t.List[Identifier]:
2245        """Return the parts of a table in order catalog, db, table."""
2246        return [
2247            t.cast(Identifier, self.args[part])
2248            for part in ("catalog", "db", "this")
2249            if self.args.get(part)
2250        ]

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

class SystemTime(Expression):
2254class SystemTime(Expression):
2255    arg_types = {
2256        "this": False,
2257        "expression": False,
2258        "kind": True,
2259    }
class Union(Subqueryable):
2262class Union(Subqueryable):
2263    arg_types = {
2264        "with": False,
2265        "this": True,
2266        "expression": True,
2267        "distinct": False,
2268        **QUERY_MODIFIERS,
2269    }
2270
2271    def limit(
2272        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2273    ) -> Select:
2274        """
2275        Set the LIMIT expression.
2276
2277        Example:
2278            >>> select("1").union(select("1")).limit(1).sql()
2279            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2280
2281        Args:
2282            expression: the SQL code string to parse.
2283                This can also be an integer.
2284                If a `Limit` instance is passed, this is used as-is.
2285                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2286            dialect: the dialect used to parse the input expression.
2287            copy: if `False`, modify this expression instance in-place.
2288            opts: other options to use to parse the input expressions.
2289
2290        Returns:
2291            The limited subqueryable.
2292        """
2293        return (
2294            select("*")
2295            .from_(self.subquery(alias="_l_0", copy=copy))
2296            .limit(expression, dialect=dialect, copy=False, **opts)
2297        )
2298
2299    def select(
2300        self,
2301        *expressions: t.Optional[ExpOrStr],
2302        append: bool = True,
2303        dialect: DialectType = None,
2304        copy: bool = True,
2305        **opts,
2306    ) -> Union:
2307        """Append to or set the SELECT of the union recursively.
2308
2309        Example:
2310            >>> from sqlglot import parse_one
2311            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2312            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2313
2314        Args:
2315            *expressions: the SQL code strings to parse.
2316                If an `Expression` instance is passed, it will be used as-is.
2317            append: if `True`, add to any existing expressions.
2318                Otherwise, this resets the expressions.
2319            dialect: the dialect used to parse the input expressions.
2320            copy: if `False`, modify this expression instance in-place.
2321            opts: other options to use to parse the input expressions.
2322
2323        Returns:
2324            Union: the modified expression.
2325        """
2326        this = self.copy() if copy else self
2327        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2328        this.expression.unnest().select(
2329            *expressions, append=append, dialect=dialect, copy=False, **opts
2330        )
2331        return this
2332
2333    @property
2334    def named_selects(self):
2335        return self.this.unnest().named_selects
2336
2337    @property
2338    def is_star(self) -> bool:
2339        return self.this.is_star or self.expression.is_star
2340
2341    @property
2342    def selects(self):
2343        return self.this.unnest().selects
2344
2345    @property
2346    def left(self):
2347        return self.this
2348
2349    @property
2350    def right(self):
2351        return self.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:
2271    def limit(
2272        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2273    ) -> Select:
2274        """
2275        Set the LIMIT expression.
2276
2277        Example:
2278            >>> select("1").union(select("1")).limit(1).sql()
2279            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2280
2281        Args:
2282            expression: the SQL code string to parse.
2283                This can also be an integer.
2284                If a `Limit` instance is passed, this is used as-is.
2285                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2286            dialect: the dialect used to parse the input expression.
2287            copy: if `False`, modify this expression instance in-place.
2288            opts: other options to use to parse the input expressions.
2289
2290        Returns:
2291            The limited subqueryable.
2292        """
2293        return (
2294            select("*")
2295            .from_(self.subquery(alias="_l_0", copy=copy))
2296            .limit(expression, dialect=dialect, copy=False, **opts)
2297        )

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:
2299    def select(
2300        self,
2301        *expressions: t.Optional[ExpOrStr],
2302        append: bool = True,
2303        dialect: DialectType = None,
2304        copy: bool = True,
2305        **opts,
2306    ) -> Union:
2307        """Append to or set the SELECT of the union recursively.
2308
2309        Example:
2310            >>> from sqlglot import parse_one
2311            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2312            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2313
2314        Args:
2315            *expressions: the SQL code strings to parse.
2316                If an `Expression` instance is passed, it will be used as-is.
2317            append: if `True`, add to any existing expressions.
2318                Otherwise, this resets the expressions.
2319            dialect: the dialect used to parse the input expressions.
2320            copy: if `False`, modify this expression instance in-place.
2321            opts: other options to use to parse the input expressions.
2322
2323        Returns:
2324            Union: the modified expression.
2325        """
2326        this = self.copy() if copy else self
2327        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2328        this.expression.unnest().select(
2329            *expressions, append=append, dialect=dialect, copy=False, **opts
2330        )
2331        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.

is_star: bool

Checks whether an expression is a star.

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

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:
2450    def group_by(
2451        self,
2452        *expressions: t.Optional[ExpOrStr],
2453        append: bool = True,
2454        dialect: DialectType = None,
2455        copy: bool = True,
2456        **opts,
2457    ) -> Select:
2458        """
2459        Set the GROUP BY expression.
2460
2461        Example:
2462            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2463            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2464
2465        Args:
2466            *expressions: the SQL code strings to parse.
2467                If a `Group` instance is passed, this is used as-is.
2468                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2469                If nothing is passed in then a group by is not applied to the expression
2470            append: if `True`, add to any existing expressions.
2471                Otherwise, this flattens all the `Group` expression into a single expression.
2472            dialect: the dialect used to parse the input expression.
2473            copy: if `False`, modify this expression instance in-place.
2474            opts: other options to use to parse the input expressions.
2475
2476        Returns:
2477            The modified Select expression.
2478        """
2479        if not expressions:
2480            return self if not copy else self.copy()
2481
2482        return _apply_child_list_builder(
2483            *expressions,
2484            instance=self,
2485            arg="group",
2486            append=append,
2487            copy=copy,
2488            prefix="GROUP BY",
2489            into=Group,
2490            dialect=dialect,
2491            **opts,
2492        )

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

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

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

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:
2614    def limit(
2615        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2616    ) -> Select:
2617        """
2618        Set the LIMIT expression.
2619
2620        Example:
2621            >>> Select().from_("tbl").select("x").limit(10).sql()
2622            'SELECT x FROM tbl LIMIT 10'
2623
2624        Args:
2625            expression: the SQL code string to parse.
2626                This can also be an integer.
2627                If a `Limit` instance is passed, this is used as-is.
2628                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2629            dialect: the dialect used to parse the input expression.
2630            copy: if `False`, modify this expression instance in-place.
2631            opts: other options to use to parse the input expressions.
2632
2633        Returns:
2634            Select: the modified expression.
2635        """
2636        return _apply_builder(
2637            expression=expression,
2638            instance=self,
2639            arg="limit",
2640            into=Limit,
2641            prefix="LIMIT",
2642            dialect=dialect,
2643            copy=copy,
2644            **opts,
2645        )

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:
2647    def offset(
2648        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2649    ) -> Select:
2650        """
2651        Set the OFFSET expression.
2652
2653        Example:
2654            >>> Select().from_("tbl").select("x").offset(10).sql()
2655            'SELECT x FROM tbl OFFSET 10'
2656
2657        Args:
2658            expression: the SQL code string to parse.
2659                This can also be an integer.
2660                If a `Offset` instance is passed, this is used as-is.
2661                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2662            dialect: the dialect used to parse the input expression.
2663            copy: if `False`, modify this expression instance in-place.
2664            opts: other options to use to parse the input expressions.
2665
2666        Returns:
2667            The modified Select expression.
2668        """
2669        return _apply_builder(
2670            expression=expression,
2671            instance=self,
2672            arg="offset",
2673            into=Offset,
2674            prefix="OFFSET",
2675            dialect=dialect,
2676            copy=copy,
2677            **opts,
2678        )

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:
2680    def select(
2681        self,
2682        *expressions: t.Optional[ExpOrStr],
2683        append: bool = True,
2684        dialect: DialectType = None,
2685        copy: bool = True,
2686        **opts,
2687    ) -> Select:
2688        """
2689        Append to or set the SELECT expressions.
2690
2691        Example:
2692            >>> Select().select("x", "y").sql()
2693            'SELECT x, y'
2694
2695        Args:
2696            *expressions: the SQL code strings to parse.
2697                If an `Expression` instance is passed, it will be used as-is.
2698            append: if `True`, add to any existing expressions.
2699                Otherwise, this resets the expressions.
2700            dialect: the dialect used to parse the input expressions.
2701            copy: if `False`, modify this expression instance in-place.
2702            opts: other options to use to parse the input expressions.
2703
2704        Returns:
2705            The modified Select expression.
2706        """
2707        return _apply_list_builder(
2708            *expressions,
2709            instance=self,
2710            arg="expressions",
2711            append=append,
2712            dialect=dialect,
2713            copy=copy,
2714            **opts,
2715        )

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:
2717    def lateral(
2718        self,
2719        *expressions: t.Optional[ExpOrStr],
2720        append: bool = True,
2721        dialect: DialectType = None,
2722        copy: bool = True,
2723        **opts,
2724    ) -> Select:
2725        """
2726        Append to or set the LATERAL expressions.
2727
2728        Example:
2729            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2730            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2731
2732        Args:
2733            *expressions: the SQL code strings to parse.
2734                If an `Expression` instance is passed, it will be used as-is.
2735            append: if `True`, add to any existing expressions.
2736                Otherwise, this resets the expressions.
2737            dialect: the dialect used to parse the input expressions.
2738            copy: if `False`, modify this expression instance in-place.
2739            opts: other options to use to parse the input expressions.
2740
2741        Returns:
2742            The modified Select expression.
2743        """
2744        return _apply_list_builder(
2745            *expressions,
2746            instance=self,
2747            arg="laterals",
2748            append=append,
2749            into=Lateral,
2750            prefix="LATERAL VIEW",
2751            dialect=dialect,
2752            copy=copy,
2753            **opts,
2754        )

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:
2756    def join(
2757        self,
2758        expression: ExpOrStr,
2759        on: t.Optional[ExpOrStr] = None,
2760        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2761        append: bool = True,
2762        join_type: t.Optional[str] = None,
2763        join_alias: t.Optional[Identifier | str] = None,
2764        dialect: DialectType = None,
2765        copy: bool = True,
2766        **opts,
2767    ) -> Select:
2768        """
2769        Append to or set the JOIN expressions.
2770
2771        Example:
2772            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2773            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2774
2775            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2776            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2777
2778            Use `join_type` to change the type of join:
2779
2780            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2781            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2782
2783        Args:
2784            expression: the SQL code string to parse.
2785                If an `Expression` instance is passed, it will be used as-is.
2786            on: optionally specify the join "on" criteria as a SQL string.
2787                If an `Expression` instance is passed, it will be used as-is.
2788            using: optionally specify the join "using" criteria as a SQL string.
2789                If an `Expression` instance is passed, it will be used as-is.
2790            append: if `True`, add to any existing expressions.
2791                Otherwise, this resets the expressions.
2792            join_type: if set, alter the parsed join type.
2793            join_alias: an optional alias for the joined source.
2794            dialect: the dialect used to parse the input expressions.
2795            copy: if `False`, modify this expression instance in-place.
2796            opts: other options to use to parse the input expressions.
2797
2798        Returns:
2799            Select: the modified expression.
2800        """
2801        parse_args = {"dialect": dialect, **opts}
2802
2803        try:
2804            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)  # type: ignore
2805        except ParseError:
2806            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)  # type: ignore
2807
2808        join = expression if isinstance(expression, Join) else Join(this=expression)
2809
2810        if isinstance(join.this, Select):
2811            join.this.replace(join.this.subquery())
2812
2813        if join_type:
2814            natural: t.Optional[Token]
2815            side: t.Optional[Token]
2816            kind: t.Optional[Token]
2817
2818            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2819
2820            if natural:
2821                join.set("natural", True)
2822            if side:
2823                join.set("side", side.text)
2824            if kind:
2825                join.set("kind", kind.text)
2826
2827        if on:
2828            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2829            join.set("on", on)
2830
2831        if using:
2832            join = _apply_list_builder(
2833                *ensure_list(using),
2834                instance=join,
2835                arg="using",
2836                append=append,
2837                copy=copy,
2838                **opts,
2839            )
2840
2841        if join_alias:
2842            join.set("this", alias_(join.this, join_alias, table=True))
2843
2844        return _apply_list_builder(
2845            join,
2846            instance=self,
2847            arg="joins",
2848            append=append,
2849            copy=copy,
2850            **opts,
2851        )

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:
2853    def where(
2854        self,
2855        *expressions: t.Optional[ExpOrStr],
2856        append: bool = True,
2857        dialect: DialectType = None,
2858        copy: bool = True,
2859        **opts,
2860    ) -> Select:
2861        """
2862        Append to or set the WHERE expressions.
2863
2864        Example:
2865            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2866            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2867
2868        Args:
2869            *expressions: the SQL code strings to parse.
2870                If an `Expression` instance is passed, it will be used as-is.
2871                Multiple expressions are combined with an AND operator.
2872            append: if `True`, AND the new expressions to any existing expression.
2873                Otherwise, this resets the expression.
2874            dialect: the dialect used to parse the input expressions.
2875            copy: if `False`, modify this expression instance in-place.
2876            opts: other options to use to parse the input expressions.
2877
2878        Returns:
2879            Select: the modified expression.
2880        """
2881        return _apply_conjunction_builder(
2882            *expressions,
2883            instance=self,
2884            arg="where",
2885            append=append,
2886            into=Where,
2887            dialect=dialect,
2888            copy=copy,
2889            **opts,
2890        )

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:
2892    def having(
2893        self,
2894        *expressions: t.Optional[ExpOrStr],
2895        append: bool = True,
2896        dialect: DialectType = None,
2897        copy: bool = True,
2898        **opts,
2899    ) -> Select:
2900        """
2901        Append to or set the HAVING expressions.
2902
2903        Example:
2904            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2905            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2906
2907        Args:
2908            *expressions: the SQL code strings to parse.
2909                If an `Expression` instance is passed, it will be used as-is.
2910                Multiple expressions are combined with an AND operator.
2911            append: if `True`, AND the new expressions to any existing expression.
2912                Otherwise, this resets the expression.
2913            dialect: the dialect used to parse the input expressions.
2914            copy: if `False`, modify this expression instance in-place.
2915            opts: other options to use to parse the input expressions.
2916
2917        Returns:
2918            The modified Select expression.
2919        """
2920        return _apply_conjunction_builder(
2921            *expressions,
2922            instance=self,
2923            arg="having",
2924            append=append,
2925            into=Having,
2926            dialect=dialect,
2927            copy=copy,
2928            **opts,
2929        )

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:
2931    def window(
2932        self,
2933        *expressions: t.Optional[ExpOrStr],
2934        append: bool = True,
2935        dialect: DialectType = None,
2936        copy: bool = True,
2937        **opts,
2938    ) -> Select:
2939        return _apply_list_builder(
2940            *expressions,
2941            instance=self,
2942            arg="windows",
2943            append=append,
2944            into=Window,
2945            dialect=dialect,
2946            copy=copy,
2947            **opts,
2948        )
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:
2950    def qualify(
2951        self,
2952        *expressions: t.Optional[ExpOrStr],
2953        append: bool = True,
2954        dialect: DialectType = None,
2955        copy: bool = True,
2956        **opts,
2957    ) -> Select:
2958        return _apply_conjunction_builder(
2959            *expressions,
2960            instance=self,
2961            arg="qualify",
2962            append=append,
2963            into=Qualify,
2964            dialect=dialect,
2965            copy=copy,
2966            **opts,
2967        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2969    def distinct(
2970        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
2971    ) -> Select:
2972        """
2973        Set the OFFSET expression.
2974
2975        Example:
2976            >>> Select().from_("tbl").select("x").distinct().sql()
2977            'SELECT DISTINCT x FROM tbl'
2978
2979        Args:
2980            ons: the expressions to distinct on
2981            distinct: whether the Select should be distinct
2982            copy: if `False`, modify this expression instance in-place.
2983
2984        Returns:
2985            Select: the modified expression.
2986        """
2987        instance = _maybe_copy(self, copy)
2988        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
2989        instance.set("distinct", Distinct(on=on) if distinct else None)
2990        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:
2992    def ctas(
2993        self,
2994        table: ExpOrStr,
2995        properties: t.Optional[t.Dict] = None,
2996        dialect: DialectType = None,
2997        copy: bool = True,
2998        **opts,
2999    ) -> Create:
3000        """
3001        Convert this expression to a CREATE TABLE AS statement.
3002
3003        Example:
3004            >>> Select().select("*").from_("tbl").ctas("x").sql()
3005            'CREATE TABLE x AS SELECT * FROM tbl'
3006
3007        Args:
3008            table: the SQL code string to parse as the table name.
3009                If another `Expression` instance is passed, it will be used as-is.
3010            properties: an optional mapping of table properties
3011            dialect: the dialect used to parse the input table.
3012            copy: if `False`, modify this expression instance in-place.
3013            opts: other options to use to parse the input table.
3014
3015        Returns:
3016            The new Create expression.
3017        """
3018        instance = _maybe_copy(self, copy)
3019        table_expression = maybe_parse(
3020            table,
3021            into=Table,
3022            dialect=dialect,
3023            **opts,
3024        )
3025        properties_expression = None
3026        if properties:
3027            properties_expression = Properties.from_dict(properties)
3028
3029        return Create(
3030            this=table_expression,
3031            kind="table",
3032            expression=instance,
3033            properties=properties_expression,
3034        )

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:
3036    def lock(self, update: bool = True, copy: bool = True) -> Select:
3037        """
3038        Set the locking read mode for this expression.
3039
3040        Examples:
3041            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3042            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3043
3044            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3045            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3046
3047        Args:
3048            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3049            copy: if `False`, modify this expression instance in-place.
3050
3051        Returns:
3052            The modified expression.
3053        """
3054
3055        inst = _maybe_copy(self, copy)
3056        inst.set("locks", [Lock(update=update)])
3057
3058        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.

is_star: bool

Checks whether an expression is a star.

class Subquery(DerivedTable, Unionable):
3073class Subquery(DerivedTable, Unionable):
3074    arg_types = {
3075        "this": True,
3076        "alias": False,
3077        "with": False,
3078        **QUERY_MODIFIERS,
3079    }
3080
3081    def unnest(self):
3082        """
3083        Returns the first non subquery.
3084        """
3085        expression = self
3086        while isinstance(expression, Subquery):
3087            expression = expression.this
3088        return expression
3089
3090    @property
3091    def is_star(self) -> bool:
3092        return self.this.is_star
3093
3094    @property
3095    def output_name(self) -> str:
3096        return self.alias
def unnest(self):
3081    def unnest(self):
3082        """
3083        Returns the first non subquery.
3084        """
3085        expression = self
3086        while isinstance(expression, Subquery):
3087            expression = expression.this
3088        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
''
class TableSample(Expression):
3099class TableSample(Expression):
3100    arg_types = {
3101        "this": False,
3102        "method": False,
3103        "bucket_numerator": False,
3104        "bucket_denominator": False,
3105        "bucket_field": False,
3106        "percent": False,
3107        "rows": False,
3108        "size": False,
3109        "seed": False,
3110        "kind": False,
3111    }
class Tag(Expression):
3114class Tag(Expression):
3115    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3116
3117    arg_types = {
3118        "this": False,
3119        "prefix": False,
3120        "postfix": False,
3121    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
3126class Pivot(Expression):
3127    arg_types = {
3128        "this": False,
3129        "alias": False,
3130        "expressions": True,
3131        "field": False,
3132        "unpivot": False,
3133        "using": False,
3134        "group": False,
3135        "columns": False,
3136    }
class Window(Expression):
3139class Window(Expression):
3140    arg_types = {
3141        "this": True,
3142        "partition_by": False,
3143        "order": False,
3144        "spec": False,
3145        "alias": False,
3146        "over": False,
3147        "first": False,
3148    }
class WindowSpec(Expression):
3151class WindowSpec(Expression):
3152    arg_types = {
3153        "kind": False,
3154        "start": False,
3155        "start_side": False,
3156        "end": False,
3157        "end_side": False,
3158    }
class Where(Expression):
3161class Where(Expression):
3162    pass
class Star(Expression):
3165class Star(Expression):
3166    arg_types = {"except": False, "replace": False}
3167
3168    @property
3169    def name(self) -> str:
3170        return "*"
3171
3172    @property
3173    def output_name(self) -> str:
3174        return self.name
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
''
class Parameter(Expression):
3177class Parameter(Expression):
3178    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
3181class SessionParameter(Expression):
3182    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
3185class Placeholder(Expression):
3186    arg_types = {"this": False, "kind": False}
class Null(Condition):
3189class Null(Condition):
3190    arg_types: t.Dict[str, t.Any] = {}
3191
3192    @property
3193    def name(self) -> str:
3194        return "NULL"
class Boolean(Condition):
3197class Boolean(Condition):
3198    pass
class DataTypeSize(Expression):
3201class DataTypeSize(Expression):
3202    arg_types = {"this": True, "expression": False}
class DataType(Expression):
3205class DataType(Expression):
3206    arg_types = {
3207        "this": True,
3208        "expressions": False,
3209        "nested": False,
3210        "values": False,
3211        "prefix": False,
3212    }
3213
3214    class Type(AutoName):
3215        ARRAY = auto()
3216        BIGDECIMAL = auto()
3217        BIGINT = auto()
3218        BIGSERIAL = auto()
3219        BINARY = auto()
3220        BIT = auto()
3221        BOOLEAN = auto()
3222        CHAR = auto()
3223        DATE = auto()
3224        DATETIME = auto()
3225        DATETIME64 = auto()
3226        DECIMAL = auto()
3227        DOUBLE = auto()
3228        FLOAT = auto()
3229        GEOGRAPHY = auto()
3230        GEOMETRY = auto()
3231        HLLSKETCH = auto()
3232        HSTORE = auto()
3233        IMAGE = auto()
3234        INET = auto()
3235        INT = auto()
3236        INT128 = auto()
3237        INT256 = auto()
3238        INTERVAL = auto()
3239        JSON = auto()
3240        JSONB = auto()
3241        LONGBLOB = auto()
3242        LONGTEXT = auto()
3243        MAP = auto()
3244        MEDIUMBLOB = auto()
3245        MEDIUMTEXT = auto()
3246        MONEY = auto()
3247        NCHAR = auto()
3248        NULL = auto()
3249        NULLABLE = auto()
3250        NVARCHAR = auto()
3251        OBJECT = auto()
3252        ROWVERSION = auto()
3253        SERIAL = auto()
3254        SMALLINT = auto()
3255        SMALLMONEY = auto()
3256        SMALLSERIAL = auto()
3257        STRUCT = auto()
3258        SUPER = auto()
3259        TEXT = auto()
3260        TIME = auto()
3261        TIMESTAMP = auto()
3262        TIMESTAMPTZ = auto()
3263        TIMESTAMPLTZ = auto()
3264        TINYINT = auto()
3265        UBIGINT = auto()
3266        UINT = auto()
3267        USMALLINT = auto()
3268        UTINYINT = auto()
3269        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3270        UINT128 = auto()
3271        UINT256 = auto()
3272        UNIQUEIDENTIFIER = auto()
3273        UUID = auto()
3274        VARBINARY = auto()
3275        VARCHAR = auto()
3276        VARIANT = auto()
3277        XML = auto()
3278
3279    TEXT_TYPES = {
3280        Type.CHAR,
3281        Type.NCHAR,
3282        Type.VARCHAR,
3283        Type.NVARCHAR,
3284        Type.TEXT,
3285    }
3286
3287    INTEGER_TYPES = {
3288        Type.INT,
3289        Type.TINYINT,
3290        Type.SMALLINT,
3291        Type.BIGINT,
3292        Type.INT128,
3293        Type.INT256,
3294    }
3295
3296    FLOAT_TYPES = {
3297        Type.FLOAT,
3298        Type.DOUBLE,
3299    }
3300
3301    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3302
3303    TEMPORAL_TYPES = {
3304        Type.TIMESTAMP,
3305        Type.TIMESTAMPTZ,
3306        Type.TIMESTAMPLTZ,
3307        Type.DATE,
3308        Type.DATETIME,
3309        Type.DATETIME64,
3310    }
3311
3312    @classmethod
3313    def build(
3314        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3315    ) -> DataType:
3316        from sqlglot import parse_one
3317
3318        if isinstance(dtype, str):
3319            if dtype.upper() in cls.Type.__members__:
3320                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3321            else:
3322                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3323
3324            if data_type_exp is None:
3325                raise ValueError(f"Unparsable data type value: {dtype}")
3326        elif isinstance(dtype, DataType.Type):
3327            data_type_exp = DataType(this=dtype)
3328        elif isinstance(dtype, DataType):
3329            return dtype
3330        else:
3331            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3332
3333        return DataType(**{**data_type_exp.args, **kwargs})
3334
3335    def is_type(self, dtype: DataType.Type) -> bool:
3336        return self.this == dtype
@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:
3312    @classmethod
3313    def build(
3314        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3315    ) -> DataType:
3316        from sqlglot import parse_one
3317
3318        if isinstance(dtype, str):
3319            if dtype.upper() in cls.Type.__members__:
3320                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3321            else:
3322                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3323
3324            if data_type_exp is None:
3325                raise ValueError(f"Unparsable data type value: {dtype}")
3326        elif isinstance(dtype, DataType.Type):
3327            data_type_exp = DataType(this=dtype)
3328        elif isinstance(dtype, DataType):
3329            return dtype
3330        else:
3331            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3332
3333        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3335    def is_type(self, dtype: DataType.Type) -> bool:
3336        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
3214    class Type(AutoName):
3215        ARRAY = auto()
3216        BIGDECIMAL = auto()
3217        BIGINT = auto()
3218        BIGSERIAL = auto()
3219        BINARY = auto()
3220        BIT = auto()
3221        BOOLEAN = auto()
3222        CHAR = auto()
3223        DATE = auto()
3224        DATETIME = auto()
3225        DATETIME64 = auto()
3226        DECIMAL = auto()
3227        DOUBLE = auto()
3228        FLOAT = auto()
3229        GEOGRAPHY = auto()
3230        GEOMETRY = auto()
3231        HLLSKETCH = auto()
3232        HSTORE = auto()
3233        IMAGE = auto()
3234        INET = auto()
3235        INT = auto()
3236        INT128 = auto()
3237        INT256 = auto()
3238        INTERVAL = auto()
3239        JSON = auto()
3240        JSONB = auto()
3241        LONGBLOB = auto()
3242        LONGTEXT = auto()
3243        MAP = auto()
3244        MEDIUMBLOB = auto()
3245        MEDIUMTEXT = auto()
3246        MONEY = auto()
3247        NCHAR = auto()
3248        NULL = auto()
3249        NULLABLE = auto()
3250        NVARCHAR = auto()
3251        OBJECT = auto()
3252        ROWVERSION = auto()
3253        SERIAL = auto()
3254        SMALLINT = auto()
3255        SMALLMONEY = auto()
3256        SMALLSERIAL = auto()
3257        STRUCT = auto()
3258        SUPER = auto()
3259        TEXT = auto()
3260        TIME = auto()
3261        TIMESTAMP = auto()
3262        TIMESTAMPTZ = auto()
3263        TIMESTAMPLTZ = auto()
3264        TINYINT = auto()
3265        UBIGINT = auto()
3266        UINT = auto()
3267        USMALLINT = auto()
3268        UTINYINT = auto()
3269        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3270        UINT128 = auto()
3271        UINT256 = auto()
3272        UNIQUEIDENTIFIER = auto()
3273        UUID = auto()
3274        VARBINARY = auto()
3275        VARCHAR = auto()
3276        VARIANT = auto()
3277        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'>
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'>
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'>
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):
3340class PseudoType(Expression):
3341    pass
class SubqueryPredicate(Predicate):
3345class SubqueryPredicate(Predicate):
3346    pass
class All(SubqueryPredicate):
3349class All(SubqueryPredicate):
3350    pass
class Any(SubqueryPredicate):
3353class Any(SubqueryPredicate):
3354    pass
class Exists(SubqueryPredicate):
3357class Exists(SubqueryPredicate):
3358    pass
class Command(Expression):
3363class Command(Expression):
3364    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
3367class Transaction(Expression):
3368    arg_types = {"this": False, "modes": False}
class Commit(Expression):
3371class Commit(Expression):
3372    arg_types = {"chain": False}
class Rollback(Expression):
3375class Rollback(Expression):
3376    arg_types = {"savepoint": False}
class AlterTable(Expression):
3379class AlterTable(Expression):
3380    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
3383class AddConstraint(Expression):
3384    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
3387class DropPartition(Expression):
3388    arg_types = {"expressions": True, "exists": False}
class Binary(Condition):
3392class Binary(Condition):
3393    arg_types = {"this": True, "expression": True}
3394
3395    @property
3396    def left(self):
3397        return self.this
3398
3399    @property
3400    def right(self):
3401        return self.expression
class Add(Binary):
3404class Add(Binary):
3405    pass
class Connector(Binary):
3408class Connector(Binary):
3409    pass
class And(Connector):
3412class And(Connector):
3413    pass
class Or(Connector):
3416class Or(Connector):
3417    pass
class BitwiseAnd(Binary):
3420class BitwiseAnd(Binary):
3421    pass
class BitwiseLeftShift(Binary):
3424class BitwiseLeftShift(Binary):
3425    pass
class BitwiseOr(Binary):
3428class BitwiseOr(Binary):
3429    pass
class BitwiseRightShift(Binary):
3432class BitwiseRightShift(Binary):
3433    pass
class BitwiseXor(Binary):
3436class BitwiseXor(Binary):
3437    pass
class Div(Binary):
3440class Div(Binary):
3441    pass
class Overlaps(Binary):
3444class Overlaps(Binary):
3445    pass
class Dot(Binary):
3448class Dot(Binary):
3449    @property
3450    def name(self) -> str:
3451        return self.expression.name
3452
3453    @classmethod
3454    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3455        """Build a Dot object with a sequence of expressions."""
3456        if len(expressions) < 2:
3457            raise ValueError(f"Dot requires >= 2 expressions.")
3458
3459        a, b, *expressions = expressions
3460        dot = Dot(this=a, expression=b)
3461
3462        for expression in expressions:
3463            dot = Dot(this=dot, expression=expression)
3464
3465        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3453    @classmethod
3454    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3455        """Build a Dot object with a sequence of expressions."""
3456        if len(expressions) < 2:
3457            raise ValueError(f"Dot requires >= 2 expressions.")
3458
3459        a, b, *expressions = expressions
3460        dot = Dot(this=a, expression=b)
3461
3462        for expression in expressions:
3463            dot = Dot(this=dot, expression=expression)
3464
3465        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3468class DPipe(Binary):
3469    pass
class EQ(Binary, Predicate):
3472class EQ(Binary, Predicate):
3473    pass
class NullSafeEQ(Binary, Predicate):
3476class NullSafeEQ(Binary, Predicate):
3477    pass
class NullSafeNEQ(Binary, Predicate):
3480class NullSafeNEQ(Binary, Predicate):
3481    pass
class Distance(Binary):
3484class Distance(Binary):
3485    pass
class Escape(Binary):
3488class Escape(Binary):
3489    pass
class Glob(Binary, Predicate):
3492class Glob(Binary, Predicate):
3493    pass
class GT(Binary, Predicate):
3496class GT(Binary, Predicate):
3497    pass
class GTE(Binary, Predicate):
3500class GTE(Binary, Predicate):
3501    pass
class ILike(Binary, Predicate):
3504class ILike(Binary, Predicate):
3505    pass
class ILikeAny(Binary, Predicate):
3508class ILikeAny(Binary, Predicate):
3509    pass
class IntDiv(Binary):
3512class IntDiv(Binary):
3513    pass
class Is(Binary, Predicate):
3516class Is(Binary, Predicate):
3517    pass
class Kwarg(Binary):
3520class Kwarg(Binary):
3521    """Kwarg in special functions like func(kwarg => y)."""

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

class Like(Binary, Predicate):
3524class Like(Binary, Predicate):
3525    pass
class LikeAny(Binary, Predicate):
3528class LikeAny(Binary, Predicate):
3529    pass
class LT(Binary, Predicate):
3532class LT(Binary, Predicate):
3533    pass
class LTE(Binary, Predicate):
3536class LTE(Binary, Predicate):
3537    pass
class Mod(Binary):
3540class Mod(Binary):
3541    pass
class Mul(Binary):
3544class Mul(Binary):
3545    pass
class NEQ(Binary, Predicate):
3548class NEQ(Binary, Predicate):
3549    pass
class SimilarTo(Binary, Predicate):
3552class SimilarTo(Binary, Predicate):
3553    pass
class Slice(Binary):
3556class Slice(Binary):
3557    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3560class Sub(Binary):
3561    pass
class ArrayOverlaps(Binary):
3564class ArrayOverlaps(Binary):
3565    pass
class Unary(Condition):
3570class Unary(Condition):
3571    pass
class BitwiseNot(Unary):
3574class BitwiseNot(Unary):
3575    pass
class Not(Unary):
3578class Not(Unary):
3579    pass
class Paren(Unary):
3582class Paren(Unary):
3583    arg_types = {"this": True, "with": False}
class Neg(Unary):
3586class Neg(Unary):
3587    pass
class Alias(Expression):
3590class Alias(Expression):
3591    arg_types = {"this": True, "alias": False}
3592
3593    @property
3594    def output_name(self) -> str:
3595        return self.alias
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
''
class Aliases(Expression):
3598class Aliases(Expression):
3599    arg_types = {"this": True, "expressions": True}
3600
3601    @property
3602    def aliases(self):
3603        return self.expressions
class AtTimeZone(Expression):
3606class AtTimeZone(Expression):
3607    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3610class Between(Predicate):
3611    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3614class Bracket(Condition):
3615    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3618class Distinct(Expression):
3619    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3622class In(Predicate):
3623    arg_types = {
3624        "this": True,
3625        "expressions": False,
3626        "query": False,
3627        "unnest": False,
3628        "field": False,
3629        "is_global": False,
3630    }
class TimeUnit(Expression):
3633class TimeUnit(Expression):
3634    """Automatically converts unit arg into a var."""
3635
3636    arg_types = {"unit": False}
3637
3638    def __init__(self, **args):
3639        unit = args.get("unit")
3640        if isinstance(unit, (Column, Literal)):
3641            args["unit"] = Var(this=unit.name)
3642        elif isinstance(unit, Week):
3643            unit.set("this", Var(this=unit.this.name))
3644
3645        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3638    def __init__(self, **args):
3639        unit = args.get("unit")
3640        if isinstance(unit, (Column, Literal)):
3641            args["unit"] = Var(this=unit.name)
3642        elif isinstance(unit, Week):
3643            unit.set("this", Var(this=unit.this.name))
3644
3645        super().__init__(**args)
class Interval(TimeUnit):
3648class Interval(TimeUnit):
3649    arg_types = {"this": False, "unit": False}
3650
3651    @property
3652    def unit(self) -> t.Optional[Var]:
3653        return self.args.get("unit")
class IgnoreNulls(Expression):
3656class IgnoreNulls(Expression):
3657    pass
class RespectNulls(Expression):
3660class RespectNulls(Expression):
3661    pass
class Func(Condition):
3665class Func(Condition):
3666    """
3667    The base class for all function expressions.
3668
3669    Attributes:
3670        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3671            treated as a variable length argument and the argument's value will be stored as a list.
3672        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3673            for this function expression. These values are used to map this node to a name during parsing
3674            as well as to provide the function's name during SQL string generation. By default the SQL
3675            name is set to the expression's class name transformed to snake case.
3676    """
3677
3678    is_var_len_args = False
3679
3680    @classmethod
3681    def from_arg_list(cls, args):
3682        if cls.is_var_len_args:
3683            all_arg_keys = list(cls.arg_types)
3684            # If this function supports variable length argument treat the last argument as such.
3685            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3686            num_non_var = len(non_var_len_arg_keys)
3687
3688            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3689            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3690        else:
3691            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3692
3693        return cls(**args_dict)
3694
3695    @classmethod
3696    def sql_names(cls):
3697        if cls is Func:
3698            raise NotImplementedError(
3699                "SQL name is only supported by concrete function implementations"
3700            )
3701        if "_sql_names" not in cls.__dict__:
3702            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3703        return cls._sql_names
3704
3705    @classmethod
3706    def sql_name(cls):
3707        return cls.sql_names()[0]
3708
3709    @classmethod
3710    def default_parser_mappings(cls):
3711        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.
@classmethod
def from_arg_list(cls, args):
3680    @classmethod
3681    def from_arg_list(cls, args):
3682        if cls.is_var_len_args:
3683            all_arg_keys = list(cls.arg_types)
3684            # If this function supports variable length argument treat the last argument as such.
3685            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3686            num_non_var = len(non_var_len_arg_keys)
3687
3688            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3689            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3690        else:
3691            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3692
3693        return cls(**args_dict)
@classmethod
def sql_names(cls):
3695    @classmethod
3696    def sql_names(cls):
3697        if cls is Func:
3698            raise NotImplementedError(
3699                "SQL name is only supported by concrete function implementations"
3700            )
3701        if "_sql_names" not in cls.__dict__:
3702            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3703        return cls._sql_names
@classmethod
def sql_name(cls):
3705    @classmethod
3706    def sql_name(cls):
3707        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3709    @classmethod
3710    def default_parser_mappings(cls):
3711        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3714class AggFunc(Func):
3715    pass
class ParameterizedAgg(AggFunc):
3718class ParameterizedAgg(AggFunc):
3719    arg_types = {"this": True, "expressions": True, "params": True}
class Abs(Func):
3722class Abs(Func):
3723    pass
class Anonymous(Func):
3726class Anonymous(Func):
3727    arg_types = {"this": True, "expressions": False}
3728    is_var_len_args = True
class Hll(AggFunc):
3733class Hll(AggFunc):
3734    arg_types = {"this": True, "expressions": False}
3735    is_var_len_args = True
class ApproxDistinct(AggFunc):
3738class ApproxDistinct(AggFunc):
3739    arg_types = {"this": True, "accuracy": False}
3740    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
class Array(Func):
3743class Array(Func):
3744    arg_types = {"expressions": False}
3745    is_var_len_args = True
class ToChar(Func):
3749class ToChar(Func):
3750    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3753class GenerateSeries(Func):
3754    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3757class ArrayAgg(AggFunc):
3758    pass
class ArrayAll(Func):
3761class ArrayAll(Func):
3762    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3765class ArrayAny(Func):
3766    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3769class ArrayConcat(Func):
3770    arg_types = {"this": True, "expressions": False}
3771    is_var_len_args = True
class ArrayContains(Binary, Func):
3774class ArrayContains(Binary, Func):
3775    pass
class ArrayContained(Binary):
3778class ArrayContained(Binary):
3779    pass
class ArrayFilter(Func):
3782class ArrayFilter(Func):
3783    arg_types = {"this": True, "expression": True}
3784    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3787class ArrayJoin(Func):
3788    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3791class ArraySize(Func):
3792    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3795class ArraySort(Func):
3796    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3799class ArraySum(Func):
3800    pass
class ArrayUnionAgg(AggFunc):
3803class ArrayUnionAgg(AggFunc):
3804    pass
class Avg(AggFunc):
3807class Avg(AggFunc):
3808    pass
class AnyValue(AggFunc):
3811class AnyValue(AggFunc):
3812    pass
class Case(Func):
3815class Case(Func):
3816    arg_types = {"this": False, "ifs": True, "default": False}
3817
3818    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3819        instance = _maybe_copy(self, copy)
3820        instance.append(
3821            "ifs",
3822            If(
3823                this=maybe_parse(condition, copy=copy, **opts),
3824                true=maybe_parse(then, copy=copy, **opts),
3825            ),
3826        )
3827        return instance
3828
3829    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3830        instance = _maybe_copy(self, copy)
3831        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3832        return instance
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3818    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3819        instance = _maybe_copy(self, copy)
3820        instance.append(
3821            "ifs",
3822            If(
3823                this=maybe_parse(condition, copy=copy, **opts),
3824                true=maybe_parse(then, copy=copy, **opts),
3825            ),
3826        )
3827        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3829    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3830        instance = _maybe_copy(self, copy)
3831        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3832        return instance
class Cast(Func):
3835class Cast(Func):
3836    arg_types = {"this": True, "to": True}
3837
3838    @property
3839    def name(self) -> str:
3840        return self.this.name
3841
3842    @property
3843    def to(self) -> DataType:
3844        return self.args["to"]
3845
3846    @property
3847    def output_name(self) -> str:
3848        return self.name
3849
3850    def is_type(self, dtype: DataType.Type) -> bool:
3851        return self.to.is_type(dtype)
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, dtype: sqlglot.expressions.DataType.Type) -> bool:
3850    def is_type(self, dtype: DataType.Type) -> bool:
3851        return self.to.is_type(dtype)
class CastToStrType(Func):
3854class CastToStrType(Func):
3855    arg_types = {"this": True, "expression": True}
class Collate(Binary):
3858class Collate(Binary):
3859    pass
class TryCast(Cast):
3862class TryCast(Cast):
3863    pass
class Ceil(Func):
3866class Ceil(Func):
3867    arg_types = {"this": True, "decimals": False}
3868    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3871class Coalesce(Func):
3872    arg_types = {"this": True, "expressions": False}
3873    is_var_len_args = True
class Concat(Func):
3876class Concat(Func):
3877    arg_types = {"expressions": True}
3878    is_var_len_args = True
class ConcatWs(Concat):
3881class ConcatWs(Concat):
3882    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3885class Count(AggFunc):
3886    arg_types = {"this": False}
class CountIf(AggFunc):
3889class CountIf(AggFunc):
3890    pass
class CurrentDate(Func):
3893class CurrentDate(Func):
3894    arg_types = {"this": False}
class CurrentDatetime(Func):
3897class CurrentDatetime(Func):
3898    arg_types = {"this": False}
class CurrentTime(Func):
3901class CurrentTime(Func):
3902    arg_types = {"this": False}
class CurrentTimestamp(Func):
3905class CurrentTimestamp(Func):
3906    arg_types = {"this": False}
class CurrentUser(Func):
3909class CurrentUser(Func):
3910    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3913class DateAdd(Func, TimeUnit):
3914    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3917class DateSub(Func, TimeUnit):
3918    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3921class DateDiff(Func, TimeUnit):
3922    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3923    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3926class DateTrunc(Func):
3927    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3930class DatetimeAdd(Func, TimeUnit):
3931    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3934class DatetimeSub(Func, TimeUnit):
3935    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3938class DatetimeDiff(Func, TimeUnit):
3939    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3942class DatetimeTrunc(Func, TimeUnit):
3943    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3946class DayOfWeek(Func):
3947    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3950class DayOfMonth(Func):
3951    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3954class DayOfYear(Func):
3955    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3958class WeekOfYear(Func):
3959    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3962class LastDateOfMonth(Func):
3963    pass
class Extract(Func):
3966class Extract(Func):
3967    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3970class TimestampAdd(Func, TimeUnit):
3971    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3974class TimestampSub(Func, TimeUnit):
3975    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3978class TimestampDiff(Func, TimeUnit):
3979    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3982class TimestampTrunc(Func, TimeUnit):
3983    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3986class TimeAdd(Func, TimeUnit):
3987    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3990class TimeSub(Func, TimeUnit):
3991    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3994class TimeDiff(Func, TimeUnit):
3995    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3998class TimeTrunc(Func, TimeUnit):
3999    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
4002class DateFromParts(Func):
4003    _sql_names = ["DATEFROMPARTS"]
4004    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
4007class DateStrToDate(Func):
4008    pass
class DateToDateStr(Func):
4011class DateToDateStr(Func):
4012    pass
class DateToDi(Func):
4015class DateToDi(Func):
4016    pass
class Day(Func):
4019class Day(Func):
4020    pass
class Decode(Func):
4023class Decode(Func):
4024    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
4027class DiToDate(Func):
4028    pass
class Encode(Func):
4031class Encode(Func):
4032    arg_types = {"this": True, "charset": True}
class Exp(Func):
4035class Exp(Func):
4036    pass
class Explode(Func):
4039class Explode(Func):
4040    pass
class Floor(Func):
4043class Floor(Func):
4044    arg_types = {"this": True, "decimals": False}
class FromBase64(Func):
4047class FromBase64(Func):
4048    pass
class ToBase64(Func):
4051class ToBase64(Func):
4052    pass
class Greatest(Func):
4055class Greatest(Func):
4056    arg_types = {"this": True, "expressions": False}
4057    is_var_len_args = True
class GroupConcat(Func):
4060class GroupConcat(Func):
4061    arg_types = {"this": True, "separator": False}
class Hex(Func):
4064class Hex(Func):
4065    pass
class If(Func):
4068class If(Func):
4069    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
4072class IfNull(Func):
4073    arg_types = {"this": True, "expression": False}
4074    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
4077class Initcap(Func):
4078    arg_types = {"this": True, "expression": False}
class JSONKeyValue(Expression):
4081class JSONKeyValue(Expression):
4082    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
4085class JSONObject(Func):
4086    arg_types = {
4087        "expressions": False,
4088        "null_handling": False,
4089        "unique_keys": False,
4090        "return_type": False,
4091        "format_json": False,
4092        "encoding": False,
4093    }
class OpenJSONColumnDef(Expression):
4096class OpenJSONColumnDef(Expression):
4097    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
class OpenJSON(Func):
4100class OpenJSON(Func):
4101    arg_types = {"this": True, "path": False, "expressions": False}
class JSONBContains(Binary):
4104class JSONBContains(Binary):
4105    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
4108class JSONExtract(Binary, Func):
4109    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
4112class JSONExtractScalar(JSONExtract):
4113    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
4116class JSONBExtract(JSONExtract):
4117    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
4120class JSONBExtractScalar(JSONExtract):
4121    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
4124class JSONFormat(Func):
4125    arg_types = {"this": False, "options": False}
4126    _sql_names = ["JSON_FORMAT"]
class Least(Func):
4129class Least(Func):
4130    arg_types = {"expressions": False}
4131    is_var_len_args = True
class Length(Func):
4134class Length(Func):
4135    pass
class Levenshtein(Func):
4138class Levenshtein(Func):
4139    arg_types = {
4140        "this": True,
4141        "expression": False,
4142        "ins_cost": False,
4143        "del_cost": False,
4144        "sub_cost": False,
4145    }
class Ln(Func):
4148class Ln(Func):
4149    pass
class Log(Func):
4152class Log(Func):
4153    arg_types = {"this": True, "expression": False}
class Log2(Func):
4156class Log2(Func):
4157    pass
class Log10(Func):
4160class Log10(Func):
4161    pass
class LogicalOr(AggFunc):
4164class LogicalOr(AggFunc):
4165    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
4168class LogicalAnd(AggFunc):
4169    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
4172class Lower(Func):
4173    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
4176class Map(Func):
4177    arg_types = {"keys": False, "values": False}
class StarMap(Func):
4180class StarMap(Func):
4181    pass
class VarMap(Func):
4184class VarMap(Func):
4185    arg_types = {"keys": True, "values": True}
4186    is_var_len_args = True
4187
4188    @property
4189    def keys(self) -> t.List[Expression]:
4190        return self.args["keys"].expressions
4191
4192    @property
4193    def values(self) -> t.List[Expression]:
4194        return self.args["values"].expressions
class MatchAgainst(Func):
4198class MatchAgainst(Func):
4199    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
4202class Max(AggFunc):
4203    arg_types = {"this": True, "expressions": False}
4204    is_var_len_args = True
class MD5(Func):
4207class MD5(Func):
4208    _sql_names = ["MD5"]
class Min(AggFunc):
4211class Min(AggFunc):
4212    arg_types = {"this": True, "expressions": False}
4213    is_var_len_args = True
class Month(Func):
4216class Month(Func):
4217    pass
class Nvl2(Func):
4220class Nvl2(Func):
4221    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
4224class Posexplode(Func):
4225    pass
class Pow(Binary, Func):
4228class Pow(Binary, Func):
4229    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
4232class PercentileCont(AggFunc):
4233    arg_types = {"this": True, "expression": False}
class PercentileDisc(AggFunc):
4236class PercentileDisc(AggFunc):
4237    arg_types = {"this": True, "expression": False}
class Quantile(AggFunc):
4240class Quantile(AggFunc):
4241    arg_types = {"this": True, "quantile": True}
class ApproxQuantile(Quantile):
4244class ApproxQuantile(Quantile):
4245    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
4248class RangeN(Func):
4249    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
4252class ReadCSV(Func):
4253    _sql_names = ["READ_CSV"]
4254    is_var_len_args = True
4255    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
4258class Reduce(Func):
4259    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
4262class RegexpExtract(Func):
4263    arg_types = {
4264        "this": True,
4265        "expression": True,
4266        "position": False,
4267        "occurrence": False,
4268        "group": False,
4269    }
class RegexpLike(Func):
4272class RegexpLike(Func):
4273    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
4276class RegexpILike(Func):
4277    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
4282class RegexpSplit(Func):
4283    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
4286class Repeat(Func):
4287    arg_types = {"this": True, "times": True}
class Round(Func):
4290class Round(Func):
4291    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
4294class RowNumber(Func):
4295    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
4298class SafeDivide(Func):
4299    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
4302class SetAgg(AggFunc):
4303    pass
class SHA(Func):
4306class SHA(Func):
4307    _sql_names = ["SHA", "SHA1"]
class SHA2(Func):
4310class SHA2(Func):
4311    _sql_names = ["SHA2"]
4312    arg_types = {"this": True, "length": False}
class SortArray(Func):
4315class SortArray(Func):
4316    arg_types = {"this": True, "asc": False}
class Split(Func):
4319class Split(Func):
4320    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
4325class Substring(Func):
4326    arg_types = {"this": True, "start": False, "length": False}
class StandardHash(Func):
4329class StandardHash(Func):
4330    arg_types = {"this": True, "expression": False}
class StrPosition(Func):
4333class StrPosition(Func):
4334    arg_types = {
4335        "this": True,
4336        "substr": True,
4337        "position": False,
4338        "instance": False,
4339    }
class StrToDate(Func):
4342class StrToDate(Func):
4343    arg_types = {"this": True, "format": True}
class StrToTime(Func):
4346class StrToTime(Func):
4347    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
4352class StrToUnix(Func):
4353    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
4356class NumberToStr(Func):
4357    arg_types = {"this": True, "format": True}
class Struct(Func):
4360class Struct(Func):
4361    arg_types = {"expressions": True}
4362    is_var_len_args = True
class StructExtract(Func):
4365class StructExtract(Func):
4366    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
4369class Sum(AggFunc):
4370    pass
class Sqrt(Func):
4373class Sqrt(Func):
4374    pass
class Stddev(AggFunc):
4377class Stddev(AggFunc):
4378    pass
class StddevPop(AggFunc):
4381class StddevPop(AggFunc):
4382    pass
class StddevSamp(AggFunc):
4385class StddevSamp(AggFunc):
4386    pass
class TimeToStr(Func):
4389class TimeToStr(Func):
4390    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
4393class TimeToTimeStr(Func):
4394    pass
class TimeToUnix(Func):
4397class TimeToUnix(Func):
4398    pass
class TimeStrToDate(Func):
4401class TimeStrToDate(Func):
4402    pass
class TimeStrToTime(Func):
4405class TimeStrToTime(Func):
4406    pass
class TimeStrToUnix(Func):
4409class TimeStrToUnix(Func):
4410    pass
class Trim(Func):
4413class Trim(Func):
4414    arg_types = {
4415        "this": True,
4416        "expression": False,
4417        "position": False,
4418        "collation": False,
4419    }
class TsOrDsAdd(Func, TimeUnit):
4422class TsOrDsAdd(Func, TimeUnit):
4423    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
4426class TsOrDsToDateStr(Func):
4427    pass
class TsOrDsToDate(Func):
4430class TsOrDsToDate(Func):
4431    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
4434class TsOrDiToDi(Func):
4435    pass
class Unhex(Func):
4438class Unhex(Func):
4439    pass
class UnixToStr(Func):
4442class UnixToStr(Func):
4443    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
4448class UnixToTime(Func):
4449    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4450
4451    SECONDS = Literal.string("seconds")
4452    MILLIS = Literal.string("millis")
4453    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
4456class UnixToTimeStr(Func):
4457    pass
class Upper(Func):
4460class Upper(Func):
4461    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
4464class Variance(AggFunc):
4465    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
4468class VariancePop(AggFunc):
4469    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
4472class Week(Func):
4473    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
4476class XMLTable(Func):
4477    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4480class Year(Func):
4481    pass
class Use(Expression):
4484class Use(Expression):
4485    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4488class Merge(Expression):
4489    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4492class When(Func):
4493    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
class NextValueFor(Func):
4498class NextValueFor(Func):
4499    arg_types = {"this": True, "order": False}
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:
4536def maybe_parse(
4537    sql_or_expression: ExpOrStr,
4538    *,
4539    into: t.Optional[IntoType] = None,
4540    dialect: DialectType = None,
4541    prefix: t.Optional[str] = None,
4542    copy: bool = False,
4543    **opts,
4544) -> Expression:
4545    """Gracefully handle a possible string or expression.
4546
4547    Example:
4548        >>> maybe_parse("1")
4549        (LITERAL this: 1, is_string: False)
4550        >>> maybe_parse(to_identifier("x"))
4551        (IDENTIFIER this: x, quoted: False)
4552
4553    Args:
4554        sql_or_expression: the SQL code string or an expression
4555        into: the SQLGlot Expression to parse into
4556        dialect: the dialect used to parse the input expressions (in the case that an
4557            input expression is a SQL string).
4558        prefix: a string to prefix the sql with before it gets parsed
4559            (automatically includes a space)
4560        copy: whether or not to copy the expression.
4561        **opts: other options to use to parse the input expressions (again, in the case
4562            that an input expression is a SQL string).
4563
4564    Returns:
4565        Expression: the parsed or given expression.
4566    """
4567    if isinstance(sql_or_expression, Expression):
4568        if copy:
4569            return sql_or_expression.copy()
4570        return sql_or_expression
4571
4572    if sql_or_expression is None:
4573        raise ParseError(f"SQL cannot be None")
4574
4575    import sqlglot
4576
4577    sql = str(sql_or_expression)
4578    if prefix:
4579        sql = f"{prefix} {sql}"
4580
4581    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:
4765def union(
4766    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4767) -> Union:
4768    """
4769    Initializes a syntax tree from one UNION expression.
4770
4771    Example:
4772        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4773        'SELECT * FROM foo UNION SELECT * FROM bla'
4774
4775    Args:
4776        left: the SQL code string corresponding to the left-hand side.
4777            If an `Expression` instance is passed, it will be used as-is.
4778        right: the SQL code string corresponding to the right-hand side.
4779            If an `Expression` instance is passed, it will be used as-is.
4780        distinct: set the DISTINCT flag if and only if this is true.
4781        dialect: the dialect used to parse the input expression.
4782        opts: other options to use to parse the input expressions.
4783
4784    Returns:
4785        The new Union instance.
4786    """
4787    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4788    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4789
4790    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:
4793def intersect(
4794    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4795) -> Intersect:
4796    """
4797    Initializes a syntax tree from one INTERSECT expression.
4798
4799    Example:
4800        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4801        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4802
4803    Args:
4804        left: the SQL code string corresponding to the left-hand side.
4805            If an `Expression` instance is passed, it will be used as-is.
4806        right: the SQL code string corresponding to the right-hand side.
4807            If an `Expression` instance is passed, it will be used as-is.
4808        distinct: set the DISTINCT flag if and only if this is true.
4809        dialect: the dialect used to parse the input expression.
4810        opts: other options to use to parse the input expressions.
4811
4812    Returns:
4813        The new Intersect instance.
4814    """
4815    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4816    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4817
4818    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:
4821def except_(
4822    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4823) -> Except:
4824    """
4825    Initializes a syntax tree from one EXCEPT expression.
4826
4827    Example:
4828        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4829        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4830
4831    Args:
4832        left: the SQL code string corresponding to the left-hand side.
4833            If an `Expression` instance is passed, it will be used as-is.
4834        right: the SQL code string corresponding to the right-hand side.
4835            If an `Expression` instance is passed, it will be used as-is.
4836        distinct: set the DISTINCT flag if and only if this is true.
4837        dialect: the dialect used to parse the input expression.
4838        opts: other options to use to parse the input expressions.
4839
4840    Returns:
4841        The new Except instance.
4842    """
4843    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4844    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4845
4846    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:
4849def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4850    """
4851    Initializes a syntax tree from one or multiple SELECT expressions.
4852
4853    Example:
4854        >>> select("col1", "col2").from_("tbl").sql()
4855        'SELECT col1, col2 FROM tbl'
4856
4857    Args:
4858        *expressions: the SQL code string to parse as the expressions of a
4859            SELECT statement. If an Expression instance is passed, this is used as-is.
4860        dialect: the dialect used to parse the input expressions (in the case that an
4861            input expression is a SQL string).
4862        **opts: other options to use to parse the input expressions (again, in the case
4863            that an input expression is a SQL string).
4864
4865    Returns:
4866        Select: the syntax tree for the SELECT statement.
4867    """
4868    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:
4871def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4872    """
4873    Initializes a syntax tree from a FROM expression.
4874
4875    Example:
4876        >>> from_("tbl").select("col1", "col2").sql()
4877        'SELECT col1, col2 FROM tbl'
4878
4879    Args:
4880        *expression: the SQL code string to parse as the FROM expressions of a
4881            SELECT statement. If an Expression instance is passed, this is used as-is.
4882        dialect: the dialect used to parse the input expression (in the case that the
4883            input expression is a SQL string).
4884        **opts: other options to use to parse the input expressions (again, in the case
4885            that the input expression is a SQL string).
4886
4887    Returns:
4888        Select: the syntax tree for the SELECT statement.
4889    """
4890    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:
4893def update(
4894    table: str | Table,
4895    properties: dict,
4896    where: t.Optional[ExpOrStr] = None,
4897    from_: t.Optional[ExpOrStr] = None,
4898    dialect: DialectType = None,
4899    **opts,
4900) -> Update:
4901    """
4902    Creates an update statement.
4903
4904    Example:
4905        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4906        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4907
4908    Args:
4909        *properties: dictionary of properties to set which are
4910            auto converted to sql objects eg None -> NULL
4911        where: sql conditional parsed into a WHERE statement
4912        from_: sql statement parsed into a FROM statement
4913        dialect: the dialect used to parse the input expressions.
4914        **opts: other options to use to parse the input expressions.
4915
4916    Returns:
4917        Update: the syntax tree for the UPDATE statement.
4918    """
4919    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4920    update_expr.set(
4921        "expressions",
4922        [
4923            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4924            for k, v in properties.items()
4925        ],
4926    )
4927    if from_:
4928        update_expr.set(
4929            "from",
4930            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4931        )
4932    if isinstance(where, Condition):
4933        where = Where(this=where)
4934    if where:
4935        update_expr.set(
4936            "where",
4937            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4938        )
4939    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:
4942def delete(
4943    table: ExpOrStr,
4944    where: t.Optional[ExpOrStr] = None,
4945    returning: t.Optional[ExpOrStr] = None,
4946    dialect: DialectType = None,
4947    **opts,
4948) -> Delete:
4949    """
4950    Builds a delete statement.
4951
4952    Example:
4953        >>> delete("my_table", where="id > 1").sql()
4954        'DELETE FROM my_table WHERE id > 1'
4955
4956    Args:
4957        where: sql conditional parsed into a WHERE statement
4958        returning: sql conditional parsed into a RETURNING statement
4959        dialect: the dialect used to parse the input expressions.
4960        **opts: other options to use to parse the input expressions.
4961
4962    Returns:
4963        Delete: the syntax tree for the DELETE statement.
4964    """
4965    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4966    if where:
4967        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4968    if returning:
4969        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4970    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:
4973def insert(
4974    expression: ExpOrStr,
4975    into: ExpOrStr,
4976    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
4977    overwrite: t.Optional[bool] = None,
4978    dialect: DialectType = None,
4979    copy: bool = True,
4980    **opts,
4981) -> Insert:
4982    """
4983    Builds an INSERT statement.
4984
4985    Example:
4986        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
4987        'INSERT INTO tbl VALUES (1, 2, 3)'
4988
4989    Args:
4990        expression: the sql string or expression of the INSERT statement
4991        into: the tbl to insert data to.
4992        columns: optionally the table's column names.
4993        overwrite: whether to INSERT OVERWRITE or not.
4994        dialect: the dialect used to parse the input expressions.
4995        copy: whether or not to copy the expression.
4996        **opts: other options to use to parse the input expressions.
4997
4998    Returns:
4999        Insert: the syntax tree for the INSERT statement.
5000    """
5001    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5002    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5003
5004    if columns:
5005        this = _apply_list_builder(
5006            *columns,
5007            instance=Schema(this=this),
5008            arg="expressions",
5009            into=Identifier,
5010            copy=False,
5011            dialect=dialect,
5012            **opts,
5013        )
5014
5015    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:
5018def condition(
5019    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5020) -> Condition:
5021    """
5022    Initialize a logical condition expression.
5023
5024    Example:
5025        >>> condition("x=1").sql()
5026        'x = 1'
5027
5028        This is helpful for composing larger logical syntax trees:
5029        >>> where = condition("x=1")
5030        >>> where = where.and_("y=1")
5031        >>> Select().from_("tbl").select("*").where(where).sql()
5032        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5033
5034    Args:
5035        *expression: the SQL code string to parse.
5036            If an Expression instance is passed, this is used as-is.
5037        dialect: the dialect used to parse the input expression (in the case that the
5038            input expression is a SQL string).
5039        copy: Whether or not to copy `expression` (only applies to expressions).
5040        **opts: other options to use to parse the input expressions (again, in the case
5041            that the input expression is a SQL string).
5042
5043    Returns:
5044        The new Condition instance
5045    """
5046    return maybe_parse(
5047        expression,
5048        into=Condition,
5049        dialect=dialect,
5050        copy=copy,
5051        **opts,
5052    )

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:
5055def and_(
5056    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5057) -> Condition:
5058    """
5059    Combine multiple conditions with an AND logical operator.
5060
5061    Example:
5062        >>> and_("x=1", and_("y=1", "z=1")).sql()
5063        'x = 1 AND (y = 1 AND z = 1)'
5064
5065    Args:
5066        *expressions: the SQL code strings to parse.
5067            If an Expression instance is passed, this is used as-is.
5068        dialect: the dialect used to parse the input expression.
5069        copy: whether or not to copy `expressions` (only applies to Expressions).
5070        **opts: other options to use to parse the input expressions.
5071
5072    Returns:
5073        And: the new condition
5074    """
5075    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:
5078def or_(
5079    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5080) -> Condition:
5081    """
5082    Combine multiple conditions with an OR logical operator.
5083
5084    Example:
5085        >>> or_("x=1", or_("y=1", "z=1")).sql()
5086        'x = 1 OR (y = 1 OR z = 1)'
5087
5088    Args:
5089        *expressions: the SQL code strings to parse.
5090            If an Expression instance is passed, this is used as-is.
5091        dialect: the dialect used to parse the input expression.
5092        copy: whether or not to copy `expressions` (only applies to Expressions).
5093        **opts: other options to use to parse the input expressions.
5094
5095    Returns:
5096        Or: the new condition
5097    """
5098    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:
5101def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5102    """
5103    Wrap a condition with a NOT operator.
5104
5105    Example:
5106        >>> not_("this_suit='black'").sql()
5107        "NOT this_suit = 'black'"
5108
5109    Args:
5110        expression: the SQL code string to parse.
5111            If an Expression instance is passed, this is used as-is.
5112        dialect: the dialect used to parse the input expression.
5113        copy: whether to copy the expression or not.
5114        **opts: other options to use to parse the input expressions.
5115
5116    Returns:
5117        The new condition.
5118    """
5119    this = condition(
5120        expression,
5121        dialect=dialect,
5122        copy=copy,
5123        **opts,
5124    )
5125    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:
5128def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5129    """
5130    Wrap an expression in parentheses.
5131
5132    Example:
5133        >>> paren("5 + 3").sql()
5134        '(5 + 3)'
5135
5136    Args:
5137        expression: the SQL code string to parse.
5138            If an Expression instance is passed, this is used as-is.
5139        copy: whether to copy the expression or not.
5140
5141    Returns:
5142        The wrapped expression.
5143    """
5144    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.

def to_identifier(name, quoted=None, copy=True):
5162def to_identifier(name, quoted=None, copy=True):
5163    """Builds an identifier.
5164
5165    Args:
5166        name: The name to turn into an identifier.
5167        quoted: Whether or not force quote the identifier.
5168        copy: Whether or not to copy a passed in Identefier node.
5169
5170    Returns:
5171        The identifier ast node.
5172    """
5173
5174    if name is None:
5175        return None
5176
5177    if isinstance(name, Identifier):
5178        identifier = _maybe_copy(name, copy)
5179    elif isinstance(name, str):
5180        identifier = Identifier(
5181            this=name,
5182            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5183        )
5184    else:
5185        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5186    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.

def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
5192def to_interval(interval: str | Literal) -> Interval:
5193    """Builds an interval expression from a string like '1 day' or '5 months'."""
5194    if isinstance(interval, Literal):
5195        if not interval.is_string:
5196            raise ValueError("Invalid interval string.")
5197
5198        interval = interval.this
5199
5200    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5201
5202    if not interval_parts:
5203        raise ValueError("Invalid interval string.")
5204
5205    return Interval(
5206        this=Literal.string(interval_parts.group(1)),
5207        unit=Var(this=interval_parts.group(2)),
5208    )

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]:
5221def to_table(
5222    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5223) -> t.Optional[Table]:
5224    """
5225    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5226    If a table is passed in then that table is returned.
5227
5228    Args:
5229        sql_path: a `[catalog].[schema].[table]` string.
5230        dialect: the source dialect according to which the table name will be parsed.
5231        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5232
5233    Returns:
5234        A table expression.
5235    """
5236    if sql_path is None or isinstance(sql_path, Table):
5237        return sql_path
5238    if not isinstance(sql_path, str):
5239        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5240
5241    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5242    if table:
5243        for k, v in kwargs.items():
5244            table.set(k, v)
5245
5246    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:
5249def to_column(sql_path: str | Column, **kwargs) -> Column:
5250    """
5251    Create a column from a `[table].[column]` sql path. Schema is optional.
5252
5253    If a column is passed in then that column is returned.
5254
5255    Args:
5256        sql_path: `[table].[column]` string
5257    Returns:
5258        Table: A column expression
5259    """
5260    if sql_path is None or isinstance(sql_path, Column):
5261        return sql_path
5262    if not isinstance(sql_path, str):
5263        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5264    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):
5267def alias_(
5268    expression: ExpOrStr,
5269    alias: str | Identifier,
5270    table: bool | t.Sequence[str | Identifier] = False,
5271    quoted: t.Optional[bool] = None,
5272    dialect: DialectType = None,
5273    copy: bool = True,
5274    **opts,
5275):
5276    """Create an Alias expression.
5277
5278    Example:
5279        >>> alias_('foo', 'bar').sql()
5280        'foo AS bar'
5281
5282        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5283        '(SELECT 1, 2) AS bar(a, b)'
5284
5285    Args:
5286        expression: the SQL code strings to parse.
5287            If an Expression instance is passed, this is used as-is.
5288        alias: the alias name to use. If the name has
5289            special characters it is quoted.
5290        table: Whether or not to create a table alias, can also be a list of columns.
5291        quoted: whether or not to quote the alias
5292        dialect: the dialect used to parse the input expression.
5293        copy: Whether or not to copy the expression.
5294        **opts: other options to use to parse the input expressions.
5295
5296    Returns:
5297        Alias: the aliased expression
5298    """
5299    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5300    alias = to_identifier(alias, quoted=quoted)
5301
5302    if table:
5303        table_alias = TableAlias(this=alias)
5304        exp.set("alias", table_alias)
5305
5306        if not isinstance(table, bool):
5307            for column in table:
5308                table_alias.append("columns", to_identifier(column, quoted=quoted))
5309
5310        return exp
5311
5312    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5313    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5314    # for the complete Window expression.
5315    #
5316    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5317
5318    if "alias" in exp.arg_types and not isinstance(exp, Window):
5319        exp.set("alias", alias)
5320        return exp
5321    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:
5324def subquery(
5325    expression: ExpOrStr,
5326    alias: t.Optional[Identifier | str] = None,
5327    dialect: DialectType = None,
5328    **opts,
5329) -> Select:
5330    """
5331    Build a subquery expression.
5332
5333    Example:
5334        >>> subquery('select x from tbl', 'bar').select('x').sql()
5335        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5336
5337    Args:
5338        expression: the SQL code strings to parse.
5339            If an Expression instance is passed, this is used as-is.
5340        alias: the alias name to use.
5341        dialect: the dialect used to parse the input expression.
5342        **opts: other options to use to parse the input expressions.
5343
5344    Returns:
5345        A new Select instance with the subquery expression included.
5346    """
5347
5348    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5349    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:
5352def column(
5353    col: str | Identifier,
5354    table: t.Optional[str | Identifier] = None,
5355    db: t.Optional[str | Identifier] = None,
5356    catalog: t.Optional[str | Identifier] = None,
5357    quoted: t.Optional[bool] = None,
5358) -> Column:
5359    """
5360    Build a Column.
5361
5362    Args:
5363        col: Column name.
5364        table: Table name.
5365        db: Database name.
5366        catalog: Catalog name.
5367        quoted: Whether to force quotes on the column's identifiers.
5368
5369    Returns:
5370        The new Column instance.
5371    """
5372    return Column(
5373        this=to_identifier(col, quoted=quoted),
5374        table=to_identifier(table, quoted=quoted),
5375        db=to_identifier(db, quoted=quoted),
5376        catalog=to_identifier(catalog, quoted=quoted),
5377    )

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:
5380def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5381    """Cast an expression to a data type.
5382
5383    Example:
5384        >>> cast('x + 1', 'int').sql()
5385        'CAST(x + 1 AS INT)'
5386
5387    Args:
5388        expression: The expression to cast.
5389        to: The datatype to cast to.
5390
5391    Returns:
5392        The new Cast instance.
5393    """
5394    expression = maybe_parse(expression, **opts)
5395    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:
5398def table_(
5399    table: Identifier | str,
5400    db: t.Optional[Identifier | str] = None,
5401    catalog: t.Optional[Identifier | str] = None,
5402    quoted: t.Optional[bool] = None,
5403    alias: t.Optional[Identifier | str] = None,
5404) -> Table:
5405    """Build a Table.
5406
5407    Args:
5408        table: Table name.
5409        db: Database name.
5410        catalog: Catalog name.
5411        quote: Whether to force quotes on the table's identifiers.
5412        alias: Table's alias.
5413
5414    Returns:
5415        The new Table instance.
5416    """
5417    return Table(
5418        this=to_identifier(table, quoted=quoted),
5419        db=to_identifier(db, quoted=quoted),
5420        catalog=to_identifier(catalog, quoted=quoted),
5421        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5422    )

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:
5425def values(
5426    values: t.Iterable[t.Tuple[t.Any, ...]],
5427    alias: t.Optional[str] = None,
5428    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5429) -> Values:
5430    """Build VALUES statement.
5431
5432    Example:
5433        >>> values([(1, '2')]).sql()
5434        "VALUES (1, '2')"
5435
5436    Args:
5437        values: values statements that will be converted to SQL
5438        alias: optional alias
5439        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5440         If either are provided then an alias is also required.
5441
5442    Returns:
5443        Values: the Values expression object
5444    """
5445    if columns and not alias:
5446        raise ValueError("Alias is required when providing columns")
5447
5448    return Values(
5449        expressions=[convert(tup) for tup in values],
5450        alias=(
5451            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5452            if columns
5453            else (TableAlias(this=to_identifier(alias)) if alias else None)
5454        ),
5455    )

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:
5458def var(name: t.Optional[ExpOrStr]) -> Var:
5459    """Build a SQL variable.
5460
5461    Example:
5462        >>> repr(var('x'))
5463        '(VAR this: x)'
5464
5465        >>> repr(var(column('x', table='y')))
5466        '(VAR this: x)'
5467
5468    Args:
5469        name: The name of the var or an expression who's name will become the var.
5470
5471    Returns:
5472        The new variable node.
5473    """
5474    if not name:
5475        raise ValueError("Cannot convert empty name into var.")
5476
5477    if isinstance(name, Expression):
5478        name = name.name
5479    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:
5482def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5483    """Build ALTER TABLE... RENAME... expression
5484
5485    Args:
5486        old_name: The old name of the table
5487        new_name: The new name of the table
5488
5489    Returns:
5490        Alter table expression
5491    """
5492    old_table = to_table(old_name)
5493    new_table = to_table(new_name)
5494    return AlterTable(
5495        this=old_table,
5496        actions=[
5497            RenameTable(this=new_table),
5498        ],
5499    )

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:
5502def convert(value: t.Any, copy: bool = False) -> Expression:
5503    """Convert a python value into an expression object.
5504
5505    Raises an error if a conversion is not possible.
5506
5507    Args:
5508        value: A python object.
5509        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5510
5511    Returns:
5512        Expression: the equivalent expression object.
5513    """
5514    if isinstance(value, Expression):
5515        return _maybe_copy(value, copy)
5516    if isinstance(value, str):
5517        return Literal.string(value)
5518    if isinstance(value, bool):
5519        return Boolean(this=value)
5520    if value is None or (isinstance(value, float) and math.isnan(value)):
5521        return NULL
5522    if isinstance(value, numbers.Number):
5523        return Literal.number(value)
5524    if isinstance(value, datetime.datetime):
5525        datetime_literal = Literal.string(
5526            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5527        )
5528        return TimeStrToTime(this=datetime_literal)
5529    if isinstance(value, datetime.date):
5530        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5531        return DateStrToDate(this=date_literal)
5532    if isinstance(value, tuple):
5533        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5534    if isinstance(value, list):
5535        return Array(expressions=[convert(v, copy=copy) for v in value])
5536    if isinstance(value, dict):
5537        return Map(
5538            keys=[convert(k, copy=copy) for k in value],
5539            values=[convert(v, copy=copy) for v in value.values()],
5540        )
5541    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:
5544def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5545    """
5546    Replace children of an expression with the result of a lambda fun(child) -> exp.
5547    """
5548    for k, v in expression.args.items():
5549        is_list_arg = type(v) is list
5550
5551        child_nodes = v if is_list_arg else [v]
5552        new_child_nodes = []
5553
5554        for cn in child_nodes:
5555            if isinstance(cn, Expression):
5556                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5557                    new_child_nodes.append(child_node)
5558                    child_node.parent = expression
5559                    child_node.arg_key = k
5560            else:
5561                new_child_nodes.append(cn)
5562
5563        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) -> List[str]:
5566def column_table_names(expression: Expression) -> t.List[str]:
5567    """
5568    Return all table names referenced through columns in an expression.
5569
5570    Example:
5571        >>> import sqlglot
5572        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
5573        ['c', 'a']
5574
5575    Args:
5576        expression: expression to find table names.
5577
5578    Returns:
5579        A list of unique names.
5580    """
5581    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))

Return all table names referenced through columns in an expression.

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

A list of unique names.

def table_name(table: sqlglot.expressions.Table | str) -> str:
5584def table_name(table: Table | str) -> str:
5585    """Get the full name of a table as a string.
5586
5587    Args:
5588        table: table expression node or string.
5589
5590    Examples:
5591        >>> from sqlglot import exp, parse_one
5592        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5593        'a.b.c'
5594
5595    Returns:
5596        The table name.
5597    """
5598
5599    table = maybe_parse(table, into=Table)
5600
5601    if not table:
5602        raise ValueError(f"Cannot parse {table}")
5603
5604    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]) -> ~E:
5607def replace_tables(expression: E, mapping: t.Dict[str, str]) -> E:
5608    """Replace all tables in expression according to the mapping.
5609
5610    Args:
5611        expression: expression node to be transformed and replaced.
5612        mapping: mapping of table names.
5613
5614    Examples:
5615        >>> from sqlglot import exp, parse_one
5616        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5617        'SELECT * FROM c'
5618
5619    Returns:
5620        The mapped expression.
5621    """
5622
5623    def _replace_tables(node: Expression) -> Expression:
5624        if isinstance(node, Table):
5625            new_name = mapping.get(table_name(node))
5626            if new_name:
5627                return to_table(
5628                    new_name,
5629                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5630                )
5631        return node
5632
5633    return expression.transform(_replace_tables)

Replace all tables in expression according to the mapping.

Arguments:
  • expression: expression node to be transformed and replaced.
  • mapping: mapping of table names.
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:
5636def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5637    """Replace placeholders in an expression.
5638
5639    Args:
5640        expression: expression node to be transformed and replaced.
5641        args: positional names that will substitute unnamed placeholders in the given order.
5642        kwargs: keyword arguments that will substitute named placeholders.
5643
5644    Examples:
5645        >>> from sqlglot import exp, parse_one
5646        >>> replace_placeholders(
5647        ...     parse_one("select * from :tbl where ? = ?"),
5648        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5649        ... ).sql()
5650        "SELECT * FROM foo WHERE str_col = 'b'"
5651
5652    Returns:
5653        The mapped expression.
5654    """
5655
5656    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5657        if isinstance(node, Placeholder):
5658            if node.name:
5659                new_name = kwargs.get(node.name)
5660                if new_name:
5661                    return convert(new_name)
5662            else:
5663                try:
5664                    return convert(next(args))
5665                except StopIteration:
5666                    pass
5667        return node
5668
5669    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:
5672def expand(
5673    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5674) -> Expression:
5675    """Transforms an expression by expanding all referenced sources into subqueries.
5676
5677    Examples:
5678        >>> from sqlglot import parse_one
5679        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5680        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5681
5682        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5683        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5684
5685    Args:
5686        expression: The expression to expand.
5687        sources: A dictionary of name to Subqueryables.
5688        copy: Whether or not to copy the expression during transformation. Defaults to True.
5689
5690    Returns:
5691        The transformed expression.
5692    """
5693
5694    def _expand(node: Expression):
5695        if isinstance(node, Table):
5696            name = table_name(node)
5697            source = sources.get(name)
5698            if source:
5699                subquery = source.subquery(node.alias or name)
5700                subquery.comments = [f"source: {name}"]
5701                return subquery.transform(_expand, copy=False)
5702        return node
5703
5704    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:
5707def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5708    """
5709    Returns a Func expression.
5710
5711    Examples:
5712        >>> func("abs", 5).sql()
5713        'ABS(5)'
5714
5715        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5716        'CAST(5 AS DOUBLE)'
5717
5718    Args:
5719        name: the name of the function to build.
5720        args: the args used to instantiate the function of interest.
5721        dialect: the source dialect.
5722        kwargs: the kwargs used to instantiate the function of interest.
5723
5724    Note:
5725        The arguments `args` and `kwargs` are mutually exclusive.
5726
5727    Returns:
5728        An instance of the function of interest, or an anonymous function, if `name` doesn't
5729        correspond to an existing `sqlglot.expressions.Func` class.
5730    """
5731    if args and kwargs:
5732        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5733
5734    from sqlglot.dialects.dialect import Dialect
5735
5736    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5737    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5738
5739    parser = Dialect.get_or_raise(dialect)().parser()
5740    from_args_list = parser.FUNCTIONS.get(name.upper())
5741
5742    if from_args_list:
5743        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5744    else:
5745        kwargs = kwargs or {"expressions": converted}
5746        function = Anonymous(this=name, **kwargs)
5747
5748    for error_message in function.error_messages(converted):
5749        raise ValueError(error_message)
5750
5751    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:
5754def true() -> Boolean:
5755    """
5756    Returns a true Boolean expression.
5757    """
5758    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5761def false() -> Boolean:
5762    """
5763    Returns a false Boolean expression.
5764    """
5765    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5768def null() -> Null:
5769    """
5770    Returns a Null expression.
5771    """
5772    return Null()

Returns a Null expression.