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

Converts the column into a dot expression.

class ColumnPosition(Expression):
1140class ColumnPosition(Expression):
1141    arg_types = {"this": False, "position": True}
class ColumnDef(Expression):
1144class ColumnDef(Expression):
1145    arg_types = {
1146        "this": True,
1147        "kind": False,
1148        "constraints": False,
1149        "exists": False,
1150        "position": False,
1151    }
1152
1153    @property
1154    def constraints(self) -> t.List[ColumnConstraint]:
1155        return self.args.get("constraints") or []
class AlterColumn(Expression):
1158class AlterColumn(Expression):
1159    arg_types = {
1160        "this": True,
1161        "dtype": False,
1162        "collate": False,
1163        "using": False,
1164        "default": False,
1165        "drop": False,
1166    }
class RenameTable(Expression):
1169class RenameTable(Expression):
1170    pass
class SetTag(Expression):
1173class SetTag(Expression):
1174    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
1177class Comment(Expression):
1178    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class MergeTreeTTLAction(Expression):
1182class MergeTreeTTLAction(Expression):
1183    arg_types = {
1184        "this": True,
1185        "delete": False,
1186        "recompress": False,
1187        "to_disk": False,
1188        "to_volume": False,
1189    }
class MergeTreeTTL(Expression):
1193class MergeTreeTTL(Expression):
1194    arg_types = {
1195        "expressions": True,
1196        "where": False,
1197        "group": False,
1198        "aggregates": False,
1199    }
class ColumnConstraint(Expression):
1202class ColumnConstraint(Expression):
1203    arg_types = {"this": False, "kind": True}
1204
1205    @property
1206    def kind(self) -> ColumnConstraintKind:
1207        return self.args["kind"]
class ColumnConstraintKind(Expression):
1210class ColumnConstraintKind(Expression):
1211    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1214class AutoIncrementColumnConstraint(ColumnConstraintKind):
1215    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1218class CaseSpecificColumnConstraint(ColumnConstraintKind):
1219    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1222class CharacterSetColumnConstraint(ColumnConstraintKind):
1223    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1226class CheckColumnConstraint(ColumnConstraintKind):
1227    pass
class CollateColumnConstraint(ColumnConstraintKind):
1230class CollateColumnConstraint(ColumnConstraintKind):
1231    pass
class CommentColumnConstraint(ColumnConstraintKind):
1234class CommentColumnConstraint(ColumnConstraintKind):
1235    pass
class CompressColumnConstraint(ColumnConstraintKind):
1238class CompressColumnConstraint(ColumnConstraintKind):
1239    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1242class DateFormatColumnConstraint(ColumnConstraintKind):
1243    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1246class DefaultColumnConstraint(ColumnConstraintKind):
1247    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1250class EncodeColumnConstraint(ColumnConstraintKind):
1251    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1254class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1255    # this: True -> ALWAYS, this: False -> BY DEFAULT
1256    arg_types = {
1257        "this": False,
1258        "expression": False,
1259        "on_null": False,
1260        "start": False,
1261        "increment": False,
1262        "minvalue": False,
1263        "maxvalue": False,
1264        "cycle": False,
1265    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1268class InlineLengthColumnConstraint(ColumnConstraintKind):
1269    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1272class NotNullColumnConstraint(ColumnConstraintKind):
1273    arg_types = {"allow_null": False}
class OnUpdateColumnConstraint(ColumnConstraintKind):
1277class OnUpdateColumnConstraint(ColumnConstraintKind):
1278    pass
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1281class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1282    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1285class TitleColumnConstraint(ColumnConstraintKind):
1286    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1289class UniqueColumnConstraint(ColumnConstraintKind):
1290    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1293class UppercaseColumnConstraint(ColumnConstraintKind):
1294    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1297class PathColumnConstraint(ColumnConstraintKind):
1298    pass
class Constraint(Expression):
1301class Constraint(Expression):
1302    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1305class Delete(Expression):
1306    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1307
1308    def delete(
1309        self,
1310        table: ExpOrStr,
1311        dialect: DialectType = None,
1312        copy: bool = True,
1313        **opts,
1314    ) -> Delete:
1315        """
1316        Create a DELETE expression or replace the table on an existing DELETE expression.
1317
1318        Example:
1319            >>> delete("tbl").sql()
1320            'DELETE FROM tbl'
1321
1322        Args:
1323            table: the table from which to delete.
1324            dialect: the dialect used to parse the input expression.
1325            copy: if `False`, modify this expression instance in-place.
1326            opts: other options to use to parse the input expressions.
1327
1328        Returns:
1329            Delete: the modified expression.
1330        """
1331        return _apply_builder(
1332            expression=table,
1333            instance=self,
1334            arg="this",
1335            dialect=dialect,
1336            into=Table,
1337            copy=copy,
1338            **opts,
1339        )
1340
1341    def where(
1342        self,
1343        *expressions: t.Optional[ExpOrStr],
1344        append: bool = True,
1345        dialect: DialectType = None,
1346        copy: bool = True,
1347        **opts,
1348    ) -> Delete:
1349        """
1350        Append to or set the WHERE expressions.
1351
1352        Example:
1353            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1354            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1355
1356        Args:
1357            *expressions: the SQL code strings to parse.
1358                If an `Expression` instance is passed, it will be used as-is.
1359                Multiple expressions are combined with an AND operator.
1360            append: if `True`, AND the new expressions to any existing expression.
1361                Otherwise, this resets the expression.
1362            dialect: the dialect used to parse the input expressions.
1363            copy: if `False`, modify this expression instance in-place.
1364            opts: other options to use to parse the input expressions.
1365
1366        Returns:
1367            Delete: the modified expression.
1368        """
1369        return _apply_conjunction_builder(
1370            *expressions,
1371            instance=self,
1372            arg="where",
1373            append=append,
1374            into=Where,
1375            dialect=dialect,
1376            copy=copy,
1377            **opts,
1378        )
1379
1380    def returning(
1381        self,
1382        expression: ExpOrStr,
1383        dialect: DialectType = None,
1384        copy: bool = True,
1385        **opts,
1386    ) -> Delete:
1387        """
1388        Set the RETURNING expression. Not supported by all dialects.
1389
1390        Example:
1391            >>> delete("tbl").returning("*", dialect="postgres").sql()
1392            'DELETE FROM tbl RETURNING *'
1393
1394        Args:
1395            expression: the SQL code strings to parse.
1396                If an `Expression` instance is passed, it will be used as-is.
1397            dialect: the dialect used to parse the input expressions.
1398            copy: if `False`, modify this expression instance in-place.
1399            opts: other options to use to parse the input expressions.
1400
1401        Returns:
1402            Delete: the modified expression.
1403        """
1404        return _apply_builder(
1405            expression=expression,
1406            instance=self,
1407            arg="returning",
1408            prefix="RETURNING",
1409            dialect=dialect,
1410            copy=copy,
1411            into=Returning,
1412            **opts,
1413        )
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:
1308    def delete(
1309        self,
1310        table: ExpOrStr,
1311        dialect: DialectType = None,
1312        copy: bool = True,
1313        **opts,
1314    ) -> Delete:
1315        """
1316        Create a DELETE expression or replace the table on an existing DELETE expression.
1317
1318        Example:
1319            >>> delete("tbl").sql()
1320            'DELETE FROM tbl'
1321
1322        Args:
1323            table: the table from which to delete.
1324            dialect: the dialect used to parse the input expression.
1325            copy: if `False`, modify this expression instance in-place.
1326            opts: other options to use to parse the input expressions.
1327
1328        Returns:
1329            Delete: the modified expression.
1330        """
1331        return _apply_builder(
1332            expression=table,
1333            instance=self,
1334            arg="this",
1335            dialect=dialect,
1336            into=Table,
1337            copy=copy,
1338            **opts,
1339        )

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

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

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

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):
1567class OnConflict(Expression):
1568    arg_types = {
1569        "duplicate": False,
1570        "expressions": False,
1571        "nothing": False,
1572        "key": False,
1573        "constraint": False,
1574    }
class Returning(Expression):
1577class Returning(Expression):
1578    arg_types = {"expressions": True}
class Introducer(Expression):
1582class Introducer(Expression):
1583    arg_types = {"this": True, "expression": True}
class National(Expression):
1587class National(Expression):
1588    pass
class LoadData(Expression):
1591class LoadData(Expression):
1592    arg_types = {
1593        "this": True,
1594        "local": False,
1595        "overwrite": False,
1596        "inpath": True,
1597        "partition": False,
1598        "input_format": False,
1599        "serde": False,
1600    }
class Partition(Expression):
1603class Partition(Expression):
1604    arg_types = {"expressions": True}
class Fetch(Expression):
1607class Fetch(Expression):
1608    arg_types = {
1609        "direction": False,
1610        "count": False,
1611        "percent": False,
1612        "with_ties": False,
1613    }
class Group(Expression):
1616class Group(Expression):
1617    arg_types = {
1618        "expressions": False,
1619        "grouping_sets": False,
1620        "cube": False,
1621        "rollup": False,
1622        "totals": False,
1623    }
class Lambda(Expression):
1626class Lambda(Expression):
1627    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1630class Limit(Expression):
1631    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1634class Literal(Condition):
1635    arg_types = {"this": True, "is_string": True}
1636
1637    @property
1638    def hashable_args(self) -> t.Any:
1639        return (self.this, self.args.get("is_string"))
1640
1641    @classmethod
1642    def number(cls, number) -> Literal:
1643        return cls(this=str(number), is_string=False)
1644
1645    @classmethod
1646    def string(cls, string) -> Literal:
1647        return cls(this=str(string), is_string=True)
1648
1649    @property
1650    def output_name(self) -> str:
1651        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1641    @classmethod
1642    def number(cls, number) -> Literal:
1643        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1645    @classmethod
1646    def string(cls, string) -> Literal:
1647        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):
1654class Join(Expression):
1655    arg_types = {
1656        "this": True,
1657        "on": False,
1658        "side": False,
1659        "kind": False,
1660        "using": False,
1661        "natural": False,
1662        "global": False,
1663        "hint": False,
1664    }
1665
1666    @property
1667    def kind(self) -> str:
1668        return self.text("kind").upper()
1669
1670    @property
1671    def side(self) -> str:
1672        return self.text("side").upper()
1673
1674    @property
1675    def hint(self) -> str:
1676        return self.text("hint").upper()
1677
1678    @property
1679    def alias_or_name(self) -> str:
1680        return self.this.alias_or_name
1681
1682    def on(
1683        self,
1684        *expressions: t.Optional[ExpOrStr],
1685        append: bool = True,
1686        dialect: DialectType = None,
1687        copy: bool = True,
1688        **opts,
1689    ) -> Join:
1690        """
1691        Append to or set the ON expressions.
1692
1693        Example:
1694            >>> import sqlglot
1695            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1696            'JOIN x ON y = 1'
1697
1698        Args:
1699            *expressions: the SQL code strings to parse.
1700                If an `Expression` instance is passed, it will be used as-is.
1701                Multiple expressions are combined with an AND operator.
1702            append: if `True`, AND the new expressions to any existing expression.
1703                Otherwise, this resets the expression.
1704            dialect: the dialect used to parse the input expressions.
1705            copy: if `False`, modify this expression instance in-place.
1706            opts: other options to use to parse the input expressions.
1707
1708        Returns:
1709            The modified Join expression.
1710        """
1711        join = _apply_conjunction_builder(
1712            *expressions,
1713            instance=self,
1714            arg="on",
1715            append=append,
1716            dialect=dialect,
1717            copy=copy,
1718            **opts,
1719        )
1720
1721        if join.kind == "CROSS":
1722            join.set("kind", None)
1723
1724        return join
1725
1726    def using(
1727        self,
1728        *expressions: t.Optional[ExpOrStr],
1729        append: bool = True,
1730        dialect: DialectType = None,
1731        copy: bool = True,
1732        **opts,
1733    ) -> Join:
1734        """
1735        Append to or set the USING expressions.
1736
1737        Example:
1738            >>> import sqlglot
1739            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1740            'JOIN x USING (foo, bla)'
1741
1742        Args:
1743            *expressions: the SQL code strings to parse.
1744                If an `Expression` instance is passed, it will be used as-is.
1745            append: if `True`, concatenate the new expressions to the existing "using" list.
1746                Otherwise, this resets the expression.
1747            dialect: the dialect used to parse the input expressions.
1748            copy: if `False`, modify this expression instance in-place.
1749            opts: other options to use to parse the input expressions.
1750
1751        Returns:
1752            The modified Join expression.
1753        """
1754        join = _apply_list_builder(
1755            *expressions,
1756            instance=self,
1757            arg="using",
1758            append=append,
1759            dialect=dialect,
1760            copy=copy,
1761            **opts,
1762        )
1763
1764        if join.kind == "CROSS":
1765            join.set("kind", None)
1766
1767        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:
1682    def on(
1683        self,
1684        *expressions: t.Optional[ExpOrStr],
1685        append: bool = True,
1686        dialect: DialectType = None,
1687        copy: bool = True,
1688        **opts,
1689    ) -> Join:
1690        """
1691        Append to or set the ON expressions.
1692
1693        Example:
1694            >>> import sqlglot
1695            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1696            'JOIN x ON y = 1'
1697
1698        Args:
1699            *expressions: the SQL code strings to parse.
1700                If an `Expression` instance is passed, it will be used as-is.
1701                Multiple expressions are combined with an AND operator.
1702            append: if `True`, AND the new expressions to any existing expression.
1703                Otherwise, this resets the expression.
1704            dialect: the dialect used to parse the input expressions.
1705            copy: if `False`, modify this expression instance in-place.
1706            opts: other options to use to parse the input expressions.
1707
1708        Returns:
1709            The modified Join expression.
1710        """
1711        join = _apply_conjunction_builder(
1712            *expressions,
1713            instance=self,
1714            arg="on",
1715            append=append,
1716            dialect=dialect,
1717            copy=copy,
1718            **opts,
1719        )
1720
1721        if join.kind == "CROSS":
1722            join.set("kind", None)
1723
1724        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:
1726    def using(
1727        self,
1728        *expressions: t.Optional[ExpOrStr],
1729        append: bool = True,
1730        dialect: DialectType = None,
1731        copy: bool = True,
1732        **opts,
1733    ) -> Join:
1734        """
1735        Append to or set the USING expressions.
1736
1737        Example:
1738            >>> import sqlglot
1739            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1740            'JOIN x USING (foo, bla)'
1741
1742        Args:
1743            *expressions: the SQL code strings to parse.
1744                If an `Expression` instance is passed, it will be used as-is.
1745            append: if `True`, concatenate the new expressions to the existing "using" list.
1746                Otherwise, this resets the expression.
1747            dialect: the dialect used to parse the input expressions.
1748            copy: if `False`, modify this expression instance in-place.
1749            opts: other options to use to parse the input expressions.
1750
1751        Returns:
1752            The modified Join expression.
1753        """
1754        join = _apply_list_builder(
1755            *expressions,
1756            instance=self,
1757            arg="using",
1758            append=append,
1759            dialect=dialect,
1760            copy=copy,
1761            **opts,
1762        )
1763
1764        if join.kind == "CROSS":
1765            join.set("kind", None)
1766
1767        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):
1770class Lateral(UDTF):
1771    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1774class MatchRecognize(Expression):
1775    arg_types = {
1776        "partition_by": False,
1777        "order": False,
1778        "measures": False,
1779        "rows": False,
1780        "after": False,
1781        "pattern": False,
1782        "define": False,
1783        "alias": False,
1784    }
class Final(Expression):
1789class Final(Expression):
1790    pass
class Offset(Expression):
1793class Offset(Expression):
1794    arg_types = {"this": False, "expression": True}
class Order(Expression):
1797class Order(Expression):
1798    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1803class Cluster(Order):
1804    pass
class Distribute(Order):
1807class Distribute(Order):
1808    pass
class Sort(Order):
1811class Sort(Order):
1812    pass
class Ordered(Expression):
1815class Ordered(Expression):
1816    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1819class Property(Expression):
1820    arg_types = {"this": True, "value": True}
class AlgorithmProperty(Property):
1823class AlgorithmProperty(Property):
1824    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1827class AutoIncrementProperty(Property):
1828    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1831class BlockCompressionProperty(Property):
1832    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1835class CharacterSetProperty(Property):
1836    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1839class ChecksumProperty(Property):
1840    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1843class CollateProperty(Property):
1844    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1847class DataBlocksizeProperty(Property):
1848    arg_types = {
1849        "size": False,
1850        "units": False,
1851        "minimum": False,
1852        "maximum": False,
1853        "default": False,
1854    }
class DefinerProperty(Property):
1857class DefinerProperty(Property):
1858    arg_types = {"this": True}
class DistKeyProperty(Property):
1861class DistKeyProperty(Property):
1862    arg_types = {"this": True}
class DistStyleProperty(Property):
1865class DistStyleProperty(Property):
1866    arg_types = {"this": True}
class EngineProperty(Property):
1869class EngineProperty(Property):
1870    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1873class ExecuteAsProperty(Property):
1874    arg_types = {"this": True}
class ExternalProperty(Property):
1877class ExternalProperty(Property):
1878    arg_types = {"this": False}
class FallbackProperty(Property):
1881class FallbackProperty(Property):
1882    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1885class FileFormatProperty(Property):
1886    arg_types = {"this": True}
class FreespaceProperty(Property):
1889class FreespaceProperty(Property):
1890    arg_types = {"this": True, "percent": False}
class InputOutputFormat(Expression):
1893class InputOutputFormat(Expression):
1894    arg_types = {"input_format": False, "output_format": False}
class IsolatedLoadingProperty(Property):
1897class IsolatedLoadingProperty(Property):
1898    arg_types = {
1899        "no": True,
1900        "concurrent": True,
1901        "for_all": True,
1902        "for_insert": True,
1903        "for_none": True,
1904    }
class JournalProperty(Property):
1907class JournalProperty(Property):
1908    arg_types = {
1909        "no": False,
1910        "dual": False,
1911        "before": False,
1912        "local": False,
1913        "after": False,
1914    }
class LanguageProperty(Property):
1917class LanguageProperty(Property):
1918    arg_types = {"this": True}
class LikeProperty(Property):
1921class LikeProperty(Property):
1922    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1925class LocationProperty(Property):
1926    arg_types = {"this": True}
class LockingProperty(Property):
1929class LockingProperty(Property):
1930    arg_types = {
1931        "this": False,
1932        "kind": True,
1933        "for_or_in": True,
1934        "lock_type": True,
1935        "override": False,
1936    }
class LogProperty(Property):
1939class LogProperty(Property):
1940    arg_types = {"no": True}
class MaterializedProperty(Property):
1943class MaterializedProperty(Property):
1944    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1947class MergeBlockRatioProperty(Property):
1948    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1951class NoPrimaryIndexProperty(Property):
1952    arg_types = {}
class OnCommitProperty(Property):
1955class OnCommitProperty(Property):
1956    arg_type = {"delete": False}
class PartitionedByProperty(Property):
1959class PartitionedByProperty(Property):
1960    arg_types = {"this": True}
class ReturnsProperty(Property):
1963class ReturnsProperty(Property):
1964    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatProperty(Property):
1967class RowFormatProperty(Property):
1968    arg_types = {"this": True}
class RowFormatDelimitedProperty(Property):
1971class RowFormatDelimitedProperty(Property):
1972    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1973    arg_types = {
1974        "fields": False,
1975        "escaped": False,
1976        "collection_items": False,
1977        "map_keys": False,
1978        "lines": False,
1979        "null": False,
1980        "serde": False,
1981    }
class RowFormatSerdeProperty(Property):
1984class RowFormatSerdeProperty(Property):
1985    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1988class SchemaCommentProperty(Property):
1989    arg_types = {"this": True}
class SerdeProperties(Property):
1992class SerdeProperties(Property):
1993    arg_types = {"expressions": True}
class SetProperty(Property):
1996class SetProperty(Property):
1997    arg_types = {"multi": True}
class SettingsProperty(Property):
2000class SettingsProperty(Property):
2001    arg_types = {"expressions": True}
class SortKeyProperty(Property):
2004class SortKeyProperty(Property):
2005    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
2008class SqlSecurityProperty(Property):
2009    arg_types = {"definer": True}
class StabilityProperty(Property):
2012class StabilityProperty(Property):
2013    arg_types = {"this": True}
class TemporaryProperty(Property):
2016class TemporaryProperty(Property):
2017    arg_types = {}
class TransientProperty(Property):
2020class TransientProperty(Property):
2021    arg_types = {"this": False}
class VolatileProperty(Property):
2024class VolatileProperty(Property):
2025    arg_types = {"this": False}
class WithDataProperty(Property):
2028class WithDataProperty(Property):
2029    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
2032class WithJournalTableProperty(Property):
2033    arg_types = {"this": True}
class Properties(Expression):
2036class Properties(Expression):
2037    arg_types = {"expressions": True}
2038
2039    NAME_TO_PROPERTY = {
2040        "ALGORITHM": AlgorithmProperty,
2041        "AUTO_INCREMENT": AutoIncrementProperty,
2042        "CHARACTER SET": CharacterSetProperty,
2043        "COLLATE": CollateProperty,
2044        "COMMENT": SchemaCommentProperty,
2045        "DEFINER": DefinerProperty,
2046        "DISTKEY": DistKeyProperty,
2047        "DISTSTYLE": DistStyleProperty,
2048        "ENGINE": EngineProperty,
2049        "EXECUTE AS": ExecuteAsProperty,
2050        "FORMAT": FileFormatProperty,
2051        "LANGUAGE": LanguageProperty,
2052        "LOCATION": LocationProperty,
2053        "PARTITIONED_BY": PartitionedByProperty,
2054        "RETURNS": ReturnsProperty,
2055        "ROW_FORMAT": RowFormatProperty,
2056        "SORTKEY": SortKeyProperty,
2057    }
2058
2059    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2060
2061    # CREATE property locations
2062    # Form: schema specified
2063    #   create [POST_CREATE]
2064    #     table a [POST_NAME]
2065    #     (b int) [POST_SCHEMA]
2066    #     with ([POST_WITH])
2067    #     index (b) [POST_INDEX]
2068    #
2069    # Form: alias selection
2070    #   create [POST_CREATE]
2071    #     table a [POST_NAME]
2072    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2073    #     index (c) [POST_INDEX]
2074    class Location(AutoName):
2075        POST_CREATE = auto()
2076        POST_NAME = auto()
2077        POST_SCHEMA = auto()
2078        POST_WITH = auto()
2079        POST_ALIAS = auto()
2080        POST_EXPRESSION = auto()
2081        POST_INDEX = auto()
2082        UNSUPPORTED = auto()
2083
2084    @classmethod
2085    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2086        expressions = []
2087        for key, value in properties_dict.items():
2088            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2089            if property_cls:
2090                expressions.append(property_cls(this=convert(value)))
2091            else:
2092                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2093
2094        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict: Dict) -> sqlglot.expressions.Properties:
2084    @classmethod
2085    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2086        expressions = []
2087        for key, value in properties_dict.items():
2088            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2089            if property_cls:
2090                expressions.append(property_cls(this=convert(value)))
2091            else:
2092                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2093
2094        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
2074    class Location(AutoName):
2075        POST_CREATE = auto()
2076        POST_NAME = auto()
2077        POST_SCHEMA = auto()
2078        POST_WITH = auto()
2079        POST_ALIAS = auto()
2080        POST_EXPRESSION = auto()
2081        POST_INDEX = auto()
2082        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):
2097class Qualify(Expression):
2098    pass
class Return(Expression):
2102class Return(Expression):
2103    pass
class Reference(Expression):
2106class Reference(Expression):
2107    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
2110class Tuple(Expression):
2111    arg_types = {"expressions": False}
2112
2113    def isin(
2114        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2115    ) -> In:
2116        return In(
2117            this=_maybe_copy(self, copy),
2118            expressions=[convert(e, copy=copy) for e in expressions],
2119            query=maybe_parse(query, copy=copy, **opts) if query else None,
2120        )
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2113    def isin(
2114        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2115    ) -> In:
2116        return In(
2117            this=_maybe_copy(self, copy),
2118            expressions=[convert(e, copy=copy) for e in expressions],
2119            query=maybe_parse(query, copy=copy, **opts) if query else None,
2120        )
class Subqueryable(Unionable):
2123class Subqueryable(Unionable):
2124    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2125        """
2126        Convert this expression to an aliased expression that can be used as a Subquery.
2127
2128        Example:
2129            >>> subquery = Select().select("x").from_("tbl").subquery()
2130            >>> Select().select("x").from_(subquery).sql()
2131            'SELECT x FROM (SELECT x FROM tbl)'
2132
2133        Args:
2134            alias (str | Identifier): an optional alias for the subquery
2135            copy (bool): if `False`, modify this expression instance in-place.
2136
2137        Returns:
2138            Alias: the subquery
2139        """
2140        instance = _maybe_copy(self, copy)
2141        if not isinstance(alias, Expression):
2142            alias = TableAlias(this=to_identifier(alias)) if alias else None
2143
2144        return Subquery(this=instance, alias=alias)
2145
2146    def limit(
2147        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2148    ) -> Select:
2149        raise NotImplementedError
2150
2151    @property
2152    def ctes(self):
2153        with_ = self.args.get("with")
2154        if not with_:
2155            return []
2156        return with_.expressions
2157
2158    @property
2159    def selects(self):
2160        raise NotImplementedError("Subqueryable objects must implement `selects`")
2161
2162    @property
2163    def named_selects(self):
2164        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2165
2166    def with_(
2167        self,
2168        alias: ExpOrStr,
2169        as_: ExpOrStr,
2170        recursive: t.Optional[bool] = None,
2171        append: bool = True,
2172        dialect: DialectType = None,
2173        copy: bool = True,
2174        **opts,
2175    ) -> Subqueryable:
2176        """
2177        Append to or set the common table expressions.
2178
2179        Example:
2180            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2181            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2182
2183        Args:
2184            alias: the SQL code string to parse as the table name.
2185                If an `Expression` instance is passed, this is used as-is.
2186            as_: the SQL code string to parse as the table expression.
2187                If an `Expression` instance is passed, it will be used as-is.
2188            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2189            append: if `True`, add to any existing expressions.
2190                Otherwise, this resets the expressions.
2191            dialect: the dialect used to parse the input expression.
2192            copy: if `False`, modify this expression instance in-place.
2193            opts: other options to use to parse the input expressions.
2194
2195        Returns:
2196            The modified expression.
2197        """
2198        return _apply_cte_builder(
2199            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2200        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2124    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2125        """
2126        Convert this expression to an aliased expression that can be used as a Subquery.
2127
2128        Example:
2129            >>> subquery = Select().select("x").from_("tbl").subquery()
2130            >>> Select().select("x").from_(subquery).sql()
2131            'SELECT x FROM (SELECT x FROM tbl)'
2132
2133        Args:
2134            alias (str | Identifier): an optional alias for the subquery
2135            copy (bool): if `False`, modify this expression instance in-place.
2136
2137        Returns:
2138            Alias: the subquery
2139        """
2140        instance = _maybe_copy(self, copy)
2141        if not isinstance(alias, Expression):
2142            alias = TableAlias(this=to_identifier(alias)) if alias else None
2143
2144        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:
2146    def limit(
2147        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2148    ) -> Select:
2149        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:
2166    def with_(
2167        self,
2168        alias: ExpOrStr,
2169        as_: ExpOrStr,
2170        recursive: t.Optional[bool] = None,
2171        append: bool = True,
2172        dialect: DialectType = None,
2173        copy: bool = True,
2174        **opts,
2175    ) -> Subqueryable:
2176        """
2177        Append to or set the common table expressions.
2178
2179        Example:
2180            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2181            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2182
2183        Args:
2184            alias: the SQL code string to parse as the table name.
2185                If an `Expression` instance is passed, this is used as-is.
2186            as_: the SQL code string to parse as the table expression.
2187                If an `Expression` instance is passed, it will be used as-is.
2188            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2189            append: if `True`, add to any existing expressions.
2190                Otherwise, this resets the expressions.
2191            dialect: the dialect used to parse the input expression.
2192            copy: if `False`, modify this expression instance in-place.
2193            opts: other options to use to parse the input expressions.
2194
2195        Returns:
2196            The modified expression.
2197        """
2198        return _apply_cte_builder(
2199            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2200        )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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:
3040    def lock(self, update: bool = True, copy: bool = True) -> Select:
3041        """
3042        Set the locking read mode for this expression.
3043
3044        Examples:
3045            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3046            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3047
3048            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3049            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3050
3051        Args:
3052            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3053            copy: if `False`, modify this expression instance in-place.
3054
3055        Returns:
3056            The modified expression.
3057        """
3058
3059        inst = _maybe_copy(self, copy)
3060        inst.set("locks", [Lock(update=update)])
3061
3062        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):
3077class Subquery(DerivedTable, Unionable):
3078    arg_types = {
3079        "this": True,
3080        "alias": False,
3081        "with": False,
3082        **QUERY_MODIFIERS,
3083    }
3084
3085    def unnest(self):
3086        """
3087        Returns the first non subquery.
3088        """
3089        expression = self
3090        while isinstance(expression, Subquery):
3091            expression = expression.this
3092        return expression
3093
3094    @property
3095    def is_star(self) -> bool:
3096        return self.this.is_star
3097
3098    @property
3099    def output_name(self) -> str:
3100        return self.alias
def unnest(self):
3085    def unnest(self):
3086        """
3087        Returns the first non subquery.
3088        """
3089        expression = self
3090        while isinstance(expression, Subquery):
3091            expression = expression.this
3092        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):
3103class TableSample(Expression):
3104    arg_types = {
3105        "this": False,
3106        "method": False,
3107        "bucket_numerator": False,
3108        "bucket_denominator": False,
3109        "bucket_field": False,
3110        "percent": False,
3111        "rows": False,
3112        "size": False,
3113        "seed": False,
3114        "kind": False,
3115    }
class Tag(Expression):
3118class Tag(Expression):
3119    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3120
3121    arg_types = {
3122        "this": False,
3123        "prefix": False,
3124        "postfix": False,
3125    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
3128class Pivot(Expression):
3129    arg_types = {
3130        "alias": False,
3131        "expressions": True,
3132        "field": True,
3133        "unpivot": True,
3134        "columns": False,
3135    }
class Window(Expression):
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    }
class WindowSpec(Expression):
3150class WindowSpec(Expression):
3151    arg_types = {
3152        "kind": False,
3153        "start": False,
3154        "start_side": False,
3155        "end": False,
3156        "end_side": False,
3157    }
class Where(Expression):
3160class Where(Expression):
3161    pass
class Star(Expression):
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
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):
3176class Parameter(Expression):
3177    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
3180class SessionParameter(Expression):
3181    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
3184class Placeholder(Expression):
3185    arg_types = {"this": False, "kind": False}
class Null(Condition):
3188class Null(Condition):
3189    arg_types: t.Dict[str, t.Any] = {}
3190
3191    @property
3192    def name(self) -> str:
3193        return "NULL"
class Boolean(Condition):
3196class Boolean(Condition):
3197    pass
class DataTypeSize(Expression):
3200class DataTypeSize(Expression):
3201    arg_types = {"this": True, "expression": False}
class DataType(Expression):
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
@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:
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})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3334    def is_type(self, dtype: DataType.Type) -> bool:
3335        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
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()

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):
3339class PseudoType(Expression):
3340    pass
class SubqueryPredicate(Predicate):
3344class SubqueryPredicate(Predicate):
3345    pass
class All(SubqueryPredicate):
3348class All(SubqueryPredicate):
3349    pass
class Any(SubqueryPredicate):
3352class Any(SubqueryPredicate):
3353    pass
class Exists(SubqueryPredicate):
3356class Exists(SubqueryPredicate):
3357    pass
class Command(Expression):
3362class Command(Expression):
3363    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
3366class Transaction(Expression):
3367    arg_types = {"this": False, "modes": False}
class Commit(Expression):
3370class Commit(Expression):
3371    arg_types = {"chain": False}
class Rollback(Expression):
3374class Rollback(Expression):
3375    arg_types = {"savepoint": False}
class AlterTable(Expression):
3378class AlterTable(Expression):
3379    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
3382class AddConstraint(Expression):
3383    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
3386class DropPartition(Expression):
3387    arg_types = {"expressions": True, "exists": False}
class Binary(Condition):
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
class Add(Binary):
3403class Add(Binary):
3404    pass
class Connector(Binary):
3407class Connector(Binary):
3408    pass
class And(Connector):
3411class And(Connector):
3412    pass
class Or(Connector):
3415class Or(Connector):
3416    pass
class BitwiseAnd(Binary):
3419class BitwiseAnd(Binary):
3420    pass
class BitwiseLeftShift(Binary):
3423class BitwiseLeftShift(Binary):
3424    pass
class BitwiseOr(Binary):
3427class BitwiseOr(Binary):
3428    pass
class BitwiseRightShift(Binary):
3431class BitwiseRightShift(Binary):
3432    pass
class BitwiseXor(Binary):
3435class BitwiseXor(Binary):
3436    pass
class Div(Binary):
3439class Div(Binary):
3440    pass
class Overlaps(Binary):
3443class Overlaps(Binary):
3444    pass
class Dot(Binary):
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
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
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

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3467class DPipe(Binary):
3468    pass
class EQ(Binary, Predicate):
3471class EQ(Binary, Predicate):
3472    pass
class NullSafeEQ(Binary, Predicate):
3475class NullSafeEQ(Binary, Predicate):
3476    pass
class NullSafeNEQ(Binary, Predicate):
3479class NullSafeNEQ(Binary, Predicate):
3480    pass
class Distance(Binary):
3483class Distance(Binary):
3484    pass
class Escape(Binary):
3487class Escape(Binary):
3488    pass
class Glob(Binary, Predicate):
3491class Glob(Binary, Predicate):
3492    pass
class GT(Binary, Predicate):
3495class GT(Binary, Predicate):
3496    pass
class GTE(Binary, Predicate):
3499class GTE(Binary, Predicate):
3500    pass
class ILike(Binary, Predicate):
3503class ILike(Binary, Predicate):
3504    pass
class ILikeAny(Binary, Predicate):
3507class ILikeAny(Binary, Predicate):
3508    pass
class IntDiv(Binary):
3511class IntDiv(Binary):
3512    pass
class Is(Binary, Predicate):
3515class Is(Binary, Predicate):
3516    pass
class Kwarg(Binary):
3519class Kwarg(Binary):
3520    """Kwarg in special functions like func(kwarg => y)."""

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

class Like(Binary, Predicate):
3523class Like(Binary, Predicate):
3524    pass
class LikeAny(Binary, Predicate):
3527class LikeAny(Binary, Predicate):
3528    pass
class LT(Binary, Predicate):
3531class LT(Binary, Predicate):
3532    pass
class LTE(Binary, Predicate):
3535class LTE(Binary, Predicate):
3536    pass
class Mod(Binary):
3539class Mod(Binary):
3540    pass
class Mul(Binary):
3543class Mul(Binary):
3544    pass
class NEQ(Binary, Predicate):
3547class NEQ(Binary, Predicate):
3548    pass
class SimilarTo(Binary, Predicate):
3551class SimilarTo(Binary, Predicate):
3552    pass
class Slice(Binary):
3555class Slice(Binary):
3556    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3559class Sub(Binary):
3560    pass
class ArrayOverlaps(Binary):
3563class ArrayOverlaps(Binary):
3564    pass
class Unary(Condition):
3569class Unary(Condition):
3570    pass
class BitwiseNot(Unary):
3573class BitwiseNot(Unary):
3574    pass
class Not(Unary):
3577class Not(Unary):
3578    pass
class Paren(Unary):
3581class Paren(Unary):
3582    arg_types = {"this": True, "with": False}
class Neg(Unary):
3585class Neg(Unary):
3586    pass
class Alias(Expression):
3589class Alias(Expression):
3590    arg_types = {"this": True, "alias": False}
3591
3592    @property
3593    def output_name(self) -> str:
3594        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):
3597class Aliases(Expression):
3598    arg_types = {"this": True, "expressions": True}
3599
3600    @property
3601    def aliases(self):
3602        return self.expressions
class AtTimeZone(Expression):
3605class AtTimeZone(Expression):
3606    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3609class Between(Predicate):
3610    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3613class Bracket(Condition):
3614    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3617class Distinct(Expression):
3618    arg_types = {"expressions": False, "on": False}
class In(Predicate):
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    }
class TimeUnit(Expression):
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)

Automatically converts unit arg into a var.

TimeUnit(**args)
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)
class Interval(TimeUnit):
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")
class IgnoreNulls(Expression):
3655class IgnoreNulls(Expression):
3656    pass
class RespectNulls(Expression):
3659class RespectNulls(Expression):
3660    pass
class Func(Condition):
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()}

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):
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)
@classmethod
def sql_names(cls):
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
@classmethod
def sql_name(cls):
3704    @classmethod
3705    def sql_name(cls):
3706        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3708    @classmethod
3709    def default_parser_mappings(cls):
3710        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3713class AggFunc(Func):
3714    pass
class ParameterizedAgg(AggFunc):
3717class ParameterizedAgg(AggFunc):
3718    arg_types = {"this": True, "expressions": True, "params": True}
class Abs(Func):
3721class Abs(Func):
3722    pass
class Anonymous(Func):
3725class Anonymous(Func):
3726    arg_types = {"this": True, "expressions": False}
3727    is_var_len_args = True
class Hll(AggFunc):
3732class Hll(AggFunc):
3733    arg_types = {"this": True, "expressions": False}
3734    is_var_len_args = True
class ApproxDistinct(AggFunc):
3737class ApproxDistinct(AggFunc):
3738    arg_types = {"this": True, "accuracy": False}
3739    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
class Array(Func):
3742class Array(Func):
3743    arg_types = {"expressions": False}
3744    is_var_len_args = True
class ToChar(Func):
3748class ToChar(Func):
3749    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3752class GenerateSeries(Func):
3753    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3756class ArrayAgg(AggFunc):
3757    pass
class ArrayAll(Func):
3760class ArrayAll(Func):
3761    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3764class ArrayAny(Func):
3765    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3768class ArrayConcat(Func):
3769    arg_types = {"this": True, "expressions": False}
3770    is_var_len_args = True
class ArrayContains(Binary, Func):
3773class ArrayContains(Binary, Func):
3774    pass
class ArrayContained(Binary):
3777class ArrayContained(Binary):
3778    pass
class ArrayFilter(Func):
3781class ArrayFilter(Func):
3782    arg_types = {"this": True, "expression": True}
3783    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3786class ArrayJoin(Func):
3787    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3790class ArraySize(Func):
3791    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3794class ArraySort(Func):
3795    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3798class ArraySum(Func):
3799    pass
class ArrayUnionAgg(AggFunc):
3802class ArrayUnionAgg(AggFunc):
3803    pass
class Avg(AggFunc):
3806class Avg(AggFunc):
3807    pass
class AnyValue(AggFunc):
3810class AnyValue(AggFunc):
3811    pass
class Case(Func):
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
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
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
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
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
class Cast(Func):
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)
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:
3849    def is_type(self, dtype: DataType.Type) -> bool:
3850        return self.to.is_type(dtype)
class CastToStrType(Func):
3853class CastToStrType(Func):
3854    arg_types = {"this": True, "expression": True}
class Collate(Binary):
3857class Collate(Binary):
3858    pass
class TryCast(Cast):
3861class TryCast(Cast):
3862    pass
class Ceil(Func):
3865class Ceil(Func):
3866    arg_types = {"this": True, "decimals": False}
3867    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3870class Coalesce(Func):
3871    arg_types = {"this": True, "expressions": False}
3872    is_var_len_args = True
class Concat(Func):
3875class Concat(Func):
3876    arg_types = {"expressions": True}
3877    is_var_len_args = True
class ConcatWs(Concat):
3880class ConcatWs(Concat):
3881    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3884class Count(AggFunc):
3885    arg_types = {"this": False}
class CountIf(AggFunc):
3888class CountIf(AggFunc):
3889    pass
class CurrentDate(Func):
3892class CurrentDate(Func):
3893    arg_types = {"this": False}
class CurrentDatetime(Func):
3896class CurrentDatetime(Func):
3897    arg_types = {"this": False}
class CurrentTime(Func):
3900class CurrentTime(Func):
3901    arg_types = {"this": False}
class CurrentTimestamp(Func):
3904class CurrentTimestamp(Func):
3905    arg_types = {"this": False}
class CurrentUser(Func):
3908class CurrentUser(Func):
3909    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3912class DateAdd(Func, TimeUnit):
3913    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3916class DateSub(Func, TimeUnit):
3917    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3920class DateDiff(Func, TimeUnit):
3921    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3922    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3925class DateTrunc(Func):
3926    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3929class DatetimeAdd(Func, TimeUnit):
3930    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3933class DatetimeSub(Func, TimeUnit):
3934    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3937class DatetimeDiff(Func, TimeUnit):
3938    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3941class DatetimeTrunc(Func, TimeUnit):
3942    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3945class DayOfWeek(Func):
3946    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3949class DayOfMonth(Func):
3950    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3953class DayOfYear(Func):
3954    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3957class WeekOfYear(Func):
3958    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3961class LastDateOfMonth(Func):
3962    pass
class Extract(Func):
3965class Extract(Func):
3966    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3969class TimestampAdd(Func, TimeUnit):
3970    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3973class TimestampSub(Func, TimeUnit):
3974    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3977class TimestampDiff(Func, TimeUnit):
3978    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3981class TimestampTrunc(Func, TimeUnit):
3982    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3985class TimeAdd(Func, TimeUnit):
3986    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3989class TimeSub(Func, TimeUnit):
3990    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3993class TimeDiff(Func, TimeUnit):
3994    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3997class TimeTrunc(Func, TimeUnit):
3998    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
4001class DateFromParts(Func):
4002    _sql_names = ["DATEFROMPARTS"]
4003    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
4006class DateStrToDate(Func):
4007    pass
class DateToDateStr(Func):
4010class DateToDateStr(Func):
4011    pass
class DateToDi(Func):
4014class DateToDi(Func):
4015    pass
class Day(Func):
4018class Day(Func):
4019    pass
class Decode(Func):
4022class Decode(Func):
4023    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
4026class DiToDate(Func):
4027    pass
class Encode(Func):
4030class Encode(Func):
4031    arg_types = {"this": True, "charset": True}
class Exp(Func):
4034class Exp(Func):
4035    pass
class Explode(Func):
4038class Explode(Func):
4039    pass
class Floor(Func):
4042class Floor(Func):
4043    arg_types = {"this": True, "decimals": False}
class FromBase64(Func):
4046class FromBase64(Func):
4047    pass
class ToBase64(Func):
4050class ToBase64(Func):
4051    pass
class Greatest(Func):
4054class Greatest(Func):
4055    arg_types = {"this": True, "expressions": False}
4056    is_var_len_args = True
class GroupConcat(Func):
4059class GroupConcat(Func):
4060    arg_types = {"this": True, "separator": False}
class Hex(Func):
4063class Hex(Func):
4064    pass
class If(Func):
4067class If(Func):
4068    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
4071class IfNull(Func):
4072    arg_types = {"this": True, "expression": False}
4073    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
4076class Initcap(Func):
4077    arg_types = {"this": True, "expression": False}
class JSONKeyValue(Expression):
4080class JSONKeyValue(Expression):
4081    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
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    }
class OpenJSONColumnDef(Expression):
4095class OpenJSONColumnDef(Expression):
4096    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
class OpenJSON(Func):
4099class OpenJSON(Func):
4100    arg_types = {"this": True, "path": False, "expressions": False}
class JSONBContains(Binary):
4103class JSONBContains(Binary):
4104    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
4107class JSONExtract(Binary, Func):
4108    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
4111class JSONExtractScalar(JSONExtract):
4112    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
4115class JSONBExtract(JSONExtract):
4116    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
4119class JSONBExtractScalar(JSONExtract):
4120    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
4123class JSONFormat(Func):
4124    arg_types = {"this": False, "options": False}
4125    _sql_names = ["JSON_FORMAT"]
class Least(Func):
4128class Least(Func):
4129    arg_types = {"expressions": False}
4130    is_var_len_args = True
class Length(Func):
4133class Length(Func):
4134    pass
class Levenshtein(Func):
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    }
class Ln(Func):
4147class Ln(Func):
4148    pass
class Log(Func):
4151class Log(Func):
4152    arg_types = {"this": True, "expression": False}
class Log2(Func):
4155class Log2(Func):
4156    pass
class Log10(Func):
4159class Log10(Func):
4160    pass
class LogicalOr(AggFunc):
4163class LogicalOr(AggFunc):
4164    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
4167class LogicalAnd(AggFunc):
4168    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
4171class Lower(Func):
4172    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
4175class Map(Func):
4176    arg_types = {"keys": False, "values": False}
class StarMap(Func):
4179class StarMap(Func):
4180    pass
class VarMap(Func):
4183class VarMap(Func):
4184    arg_types = {"keys": True, "values": True}
4185    is_var_len_args = True
class MatchAgainst(Func):
4189class MatchAgainst(Func):
4190    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
4193class Max(AggFunc):
4194    arg_types = {"this": True, "expressions": False}
4195    is_var_len_args = True
class MD5(Func):
4198class MD5(Func):
4199    _sql_names = ["MD5"]
class Min(AggFunc):
4202class Min(AggFunc):
4203    arg_types = {"this": True, "expressions": False}
4204    is_var_len_args = True
class Month(Func):
4207class Month(Func):
4208    pass
class Nvl2(Func):
4211class Nvl2(Func):
4212    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
4215class Posexplode(Func):
4216    pass
class Pow(Binary, Func):
4219class Pow(Binary, Func):
4220    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
4223class PercentileCont(AggFunc):
4224    arg_types = {"this": True, "expression": False}
class PercentileDisc(AggFunc):
4227class PercentileDisc(AggFunc):
4228    arg_types = {"this": True, "expression": False}
class Quantile(AggFunc):
4231class Quantile(AggFunc):
4232    arg_types = {"this": True, "quantile": True}
class ApproxQuantile(Quantile):
4235class ApproxQuantile(Quantile):
4236    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
4239class RangeN(Func):
4240    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
4243class ReadCSV(Func):
4244    _sql_names = ["READ_CSV"]
4245    is_var_len_args = True
4246    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
4249class Reduce(Func):
4250    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
4253class RegexpExtract(Func):
4254    arg_types = {
4255        "this": True,
4256        "expression": True,
4257        "position": False,
4258        "occurrence": False,
4259        "group": False,
4260    }
class RegexpLike(Func):
4263class RegexpLike(Func):
4264    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
4267class RegexpILike(Func):
4268    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
4273class RegexpSplit(Func):
4274    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
4277class Repeat(Func):
4278    arg_types = {"this": True, "times": True}
class Round(Func):
4281class Round(Func):
4282    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
4285class RowNumber(Func):
4286    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
4289class SafeDivide(Func):
4290    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
4293class SetAgg(AggFunc):
4294    pass
class SHA(Func):
4297class SHA(Func):
4298    _sql_names = ["SHA", "SHA1"]
class SHA2(Func):
4301class SHA2(Func):
4302    _sql_names = ["SHA2"]
4303    arg_types = {"this": True, "length": False}
class SortArray(Func):
4306class SortArray(Func):
4307    arg_types = {"this": True, "asc": False}
class Split(Func):
4310class Split(Func):
4311    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
4316class Substring(Func):
4317    arg_types = {"this": True, "start": False, "length": False}
class StandardHash(Func):
4320class StandardHash(Func):
4321    arg_types = {"this": True, "expression": False}
class StrPosition(Func):
4324class StrPosition(Func):
4325    arg_types = {
4326        "this": True,
4327        "substr": True,
4328        "position": False,
4329        "instance": False,
4330    }
class StrToDate(Func):
4333class StrToDate(Func):
4334    arg_types = {"this": True, "format": True}
class StrToTime(Func):
4337class StrToTime(Func):
4338    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
4343class StrToUnix(Func):
4344    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
4347class NumberToStr(Func):
4348    arg_types = {"this": True, "format": True}
class Struct(Func):
4351class Struct(Func):
4352    arg_types = {"expressions": True}
4353    is_var_len_args = True
class StructExtract(Func):
4356class StructExtract(Func):
4357    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
4360class Sum(AggFunc):
4361    pass
class Sqrt(Func):
4364class Sqrt(Func):
4365    pass
class Stddev(AggFunc):
4368class Stddev(AggFunc):
4369    pass
class StddevPop(AggFunc):
4372class StddevPop(AggFunc):
4373    pass
class StddevSamp(AggFunc):
4376class StddevSamp(AggFunc):
4377    pass
class TimeToStr(Func):
4380class TimeToStr(Func):
4381    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
4384class TimeToTimeStr(Func):
4385    pass
class TimeToUnix(Func):
4388class TimeToUnix(Func):
4389    pass
class TimeStrToDate(Func):
4392class TimeStrToDate(Func):
4393    pass
class TimeStrToTime(Func):
4396class TimeStrToTime(Func):
4397    pass
class TimeStrToUnix(Func):
4400class TimeStrToUnix(Func):
4401    pass
class Trim(Func):
4404class Trim(Func):
4405    arg_types = {
4406        "this": True,
4407        "expression": False,
4408        "position": False,
4409        "collation": False,
4410    }
class TsOrDsAdd(Func, TimeUnit):
4413class TsOrDsAdd(Func, TimeUnit):
4414    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
4417class TsOrDsToDateStr(Func):
4418    pass
class TsOrDsToDate(Func):
4421class TsOrDsToDate(Func):
4422    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
4425class TsOrDiToDi(Func):
4426    pass
class Unhex(Func):
4429class Unhex(Func):
4430    pass
class UnixToStr(Func):
4433class UnixToStr(Func):
4434    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
4439class UnixToTime(Func):
4440    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4441
4442    SECONDS = Literal.string("seconds")
4443    MILLIS = Literal.string("millis")
4444    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
4447class UnixToTimeStr(Func):
4448    pass
class Upper(Func):
4451class Upper(Func):
4452    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
4455class Variance(AggFunc):
4456    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
4459class VariancePop(AggFunc):
4460    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
4463class Week(Func):
4464    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
4467class XMLTable(Func):
4468    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4471class Year(Func):
4472    pass
class Use(Expression):
4475class Use(Expression):
4476    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4479class Merge(Expression):
4480    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4483class When(Func):
4484    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
class NextValueFor(Func):
4489class NextValueFor(Func):
4490    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:
4527def maybe_parse(
4528    sql_or_expression: ExpOrStr,
4529    *,
4530    into: t.Optional[IntoType] = None,
4531    dialect: DialectType = None,
4532    prefix: t.Optional[str] = None,
4533    copy: bool = False,
4534    **opts,
4535) -> Expression:
4536    """Gracefully handle a possible string or expression.
4537
4538    Example:
4539        >>> maybe_parse("1")
4540        (LITERAL this: 1, is_string: False)
4541        >>> maybe_parse(to_identifier("x"))
4542        (IDENTIFIER this: x, quoted: False)
4543
4544    Args:
4545        sql_or_expression: the SQL code string or an expression
4546        into: the SQLGlot Expression to parse into
4547        dialect: the dialect used to parse the input expressions (in the case that an
4548            input expression is a SQL string).
4549        prefix: a string to prefix the sql with before it gets parsed
4550            (automatically includes a space)
4551        copy: whether or not to copy the expression.
4552        **opts: other options to use to parse the input expressions (again, in the case
4553            that an input expression is a SQL string).
4554
4555    Returns:
4556        Expression: the parsed or given expression.
4557    """
4558    if isinstance(sql_or_expression, Expression):
4559        if copy:
4560            return sql_or_expression.copy()
4561        return sql_or_expression
4562
4563    import sqlglot
4564
4565    sql = str(sql_or_expression)
4566    if prefix:
4567        sql = f"{prefix} {sql}"
4568    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:
4752def union(
4753    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4754) -> Union:
4755    """
4756    Initializes a syntax tree from one UNION expression.
4757
4758    Example:
4759        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4760        'SELECT * FROM foo UNION SELECT * FROM bla'
4761
4762    Args:
4763        left: the SQL code string corresponding to the left-hand side.
4764            If an `Expression` instance is passed, it will be used as-is.
4765        right: the SQL code string corresponding to the right-hand side.
4766            If an `Expression` instance is passed, it will be used as-is.
4767        distinct: set the DISTINCT flag if and only if this is true.
4768        dialect: the dialect used to parse the input expression.
4769        opts: other options to use to parse the input expressions.
4770
4771    Returns:
4772        The new Union instance.
4773    """
4774    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4775    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4776
4777    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:
4780def intersect(
4781    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4782) -> Intersect:
4783    """
4784    Initializes a syntax tree from one INTERSECT expression.
4785
4786    Example:
4787        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4788        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4789
4790    Args:
4791        left: the SQL code string corresponding to the left-hand side.
4792            If an `Expression` instance is passed, it will be used as-is.
4793        right: the SQL code string corresponding to the right-hand side.
4794            If an `Expression` instance is passed, it will be used as-is.
4795        distinct: set the DISTINCT flag if and only if this is true.
4796        dialect: the dialect used to parse the input expression.
4797        opts: other options to use to parse the input expressions.
4798
4799    Returns:
4800        The new Intersect instance.
4801    """
4802    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4803    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4804
4805    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:
4808def except_(
4809    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4810) -> Except:
4811    """
4812    Initializes a syntax tree from one EXCEPT expression.
4813
4814    Example:
4815        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4816        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4817
4818    Args:
4819        left: the SQL code string corresponding to the left-hand side.
4820            If an `Expression` instance is passed, it will be used as-is.
4821        right: the SQL code string corresponding to the right-hand side.
4822            If an `Expression` instance is passed, it will be used as-is.
4823        distinct: set the DISTINCT flag if and only if this is true.
4824        dialect: the dialect used to parse the input expression.
4825        opts: other options to use to parse the input expressions.
4826
4827    Returns:
4828        The new Except instance.
4829    """
4830    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4831    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4832
4833    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:
4836def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4837    """
4838    Initializes a syntax tree from one or multiple SELECT expressions.
4839
4840    Example:
4841        >>> select("col1", "col2").from_("tbl").sql()
4842        'SELECT col1, col2 FROM tbl'
4843
4844    Args:
4845        *expressions: the SQL code string to parse as the expressions of a
4846            SELECT statement. If an Expression instance is passed, this is used as-is.
4847        dialect: the dialect used to parse the input expressions (in the case that an
4848            input expression is a SQL string).
4849        **opts: other options to use to parse the input expressions (again, in the case
4850            that an input expression is a SQL string).
4851
4852    Returns:
4853        Select: the syntax tree for the SELECT statement.
4854    """
4855    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:
4858def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4859    """
4860    Initializes a syntax tree from a FROM expression.
4861
4862    Example:
4863        >>> from_("tbl").select("col1", "col2").sql()
4864        'SELECT col1, col2 FROM tbl'
4865
4866    Args:
4867        *expression: the SQL code string to parse as the FROM expressions of a
4868            SELECT statement. If an Expression instance is passed, this is used as-is.
4869        dialect: the dialect used to parse the input expression (in the case that the
4870            input expression is a SQL string).
4871        **opts: other options to use to parse the input expressions (again, in the case
4872            that the input expression is a SQL string).
4873
4874    Returns:
4875        Select: the syntax tree for the SELECT statement.
4876    """
4877    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:
4880def update(
4881    table: str | Table,
4882    properties: dict,
4883    where: t.Optional[ExpOrStr] = None,
4884    from_: t.Optional[ExpOrStr] = None,
4885    dialect: DialectType = None,
4886    **opts,
4887) -> Update:
4888    """
4889    Creates an update statement.
4890
4891    Example:
4892        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4893        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4894
4895    Args:
4896        *properties: dictionary of properties to set which are
4897            auto converted to sql objects eg None -> NULL
4898        where: sql conditional parsed into a WHERE statement
4899        from_: sql statement parsed into a FROM statement
4900        dialect: the dialect used to parse the input expressions.
4901        **opts: other options to use to parse the input expressions.
4902
4903    Returns:
4904        Update: the syntax tree for the UPDATE statement.
4905    """
4906    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4907    update_expr.set(
4908        "expressions",
4909        [
4910            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4911            for k, v in properties.items()
4912        ],
4913    )
4914    if from_:
4915        update_expr.set(
4916            "from",
4917            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4918        )
4919    if isinstance(where, Condition):
4920        where = Where(this=where)
4921    if where:
4922        update_expr.set(
4923            "where",
4924            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4925        )
4926    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:
4929def delete(
4930    table: ExpOrStr,
4931    where: t.Optional[ExpOrStr] = None,
4932    returning: t.Optional[ExpOrStr] = None,
4933    dialect: DialectType = None,
4934    **opts,
4935) -> Delete:
4936    """
4937    Builds a delete statement.
4938
4939    Example:
4940        >>> delete("my_table", where="id > 1").sql()
4941        'DELETE FROM my_table WHERE id > 1'
4942
4943    Args:
4944        where: sql conditional parsed into a WHERE statement
4945        returning: sql conditional parsed into a RETURNING statement
4946        dialect: the dialect used to parse the input expressions.
4947        **opts: other options to use to parse the input expressions.
4948
4949    Returns:
4950        Delete: the syntax tree for the DELETE statement.
4951    """
4952    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4953    if where:
4954        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4955    if returning:
4956        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4957    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:
4960def insert(
4961    expression: ExpOrStr,
4962    into: ExpOrStr,
4963    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
4964    overwrite: t.Optional[bool] = None,
4965    dialect: DialectType = None,
4966    copy: bool = True,
4967    **opts,
4968) -> Insert:
4969    """
4970    Builds an INSERT statement.
4971
4972    Example:
4973        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
4974        'INSERT INTO tbl VALUES (1, 2, 3)'
4975
4976    Args:
4977        expression: the sql string or expression of the INSERT statement
4978        into: the tbl to insert data to.
4979        columns: optionally the table's column names.
4980        overwrite: whether to INSERT OVERWRITE or not.
4981        dialect: the dialect used to parse the input expressions.
4982        copy: whether or not to copy the expression.
4983        **opts: other options to use to parse the input expressions.
4984
4985    Returns:
4986        Insert: the syntax tree for the INSERT statement.
4987    """
4988    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
4989    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
4990
4991    if columns:
4992        this = _apply_list_builder(
4993            *columns,
4994            instance=Schema(this=this),
4995            arg="expressions",
4996            into=Identifier,
4997            copy=False,
4998            dialect=dialect,
4999            **opts,
5000        )
5001
5002    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:
5005def condition(
5006    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5007) -> Condition:
5008    """
5009    Initialize a logical condition expression.
5010
5011    Example:
5012        >>> condition("x=1").sql()
5013        'x = 1'
5014
5015        This is helpful for composing larger logical syntax trees:
5016        >>> where = condition("x=1")
5017        >>> where = where.and_("y=1")
5018        >>> Select().from_("tbl").select("*").where(where).sql()
5019        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5020
5021    Args:
5022        *expression: the SQL code string to parse.
5023            If an Expression instance is passed, this is used as-is.
5024        dialect: the dialect used to parse the input expression (in the case that the
5025            input expression is a SQL string).
5026        copy: Whether or not to copy `expression` (only applies to expressions).
5027        **opts: other options to use to parse the input expressions (again, in the case
5028            that the input expression is a SQL string).
5029
5030    Returns:
5031        The new Condition instance
5032    """
5033    return maybe_parse(
5034        expression,
5035        into=Condition,
5036        dialect=dialect,
5037        copy=copy,
5038        **opts,
5039    )

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:
5042def and_(
5043    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5044) -> Condition:
5045    """
5046    Combine multiple conditions with an AND logical operator.
5047
5048    Example:
5049        >>> and_("x=1", and_("y=1", "z=1")).sql()
5050        'x = 1 AND (y = 1 AND z = 1)'
5051
5052    Args:
5053        *expressions: the SQL code strings to parse.
5054            If an Expression instance is passed, this is used as-is.
5055        dialect: the dialect used to parse the input expression.
5056        copy: whether or not to copy `expressions` (only applies to Expressions).
5057        **opts: other options to use to parse the input expressions.
5058
5059    Returns:
5060        And: the new condition
5061    """
5062    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:
5065def or_(
5066    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5067) -> Condition:
5068    """
5069    Combine multiple conditions with an OR logical operator.
5070
5071    Example:
5072        >>> or_("x=1", or_("y=1", "z=1")).sql()
5073        'x = 1 OR (y = 1 OR z = 1)'
5074
5075    Args:
5076        *expressions: the SQL code strings to parse.
5077            If an Expression instance is passed, this is used as-is.
5078        dialect: the dialect used to parse the input expression.
5079        copy: whether or not to copy `expressions` (only applies to Expressions).
5080        **opts: other options to use to parse the input expressions.
5081
5082    Returns:
5083        Or: the new condition
5084    """
5085    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:
5088def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5089    """
5090    Wrap a condition with a NOT operator.
5091
5092    Example:
5093        >>> not_("this_suit='black'").sql()
5094        "NOT this_suit = 'black'"
5095
5096    Args:
5097        expression: the SQL code string to parse.
5098            If an Expression instance is passed, this is used as-is.
5099        dialect: the dialect used to parse the input expression.
5100        copy: whether to copy the expression or not.
5101        **opts: other options to use to parse the input expressions.
5102
5103    Returns:
5104        The new condition.
5105    """
5106    this = condition(
5107        expression,
5108        dialect=dialect,
5109        copy=copy,
5110        **opts,
5111    )
5112    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:
5115def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5116    """
5117    Wrap an expression in parentheses.
5118
5119    Example:
5120        >>> paren("5 + 3").sql()
5121        '(5 + 3)'
5122
5123    Args:
5124        expression: the SQL code string to parse.
5125            If an Expression instance is passed, this is used as-is.
5126        copy: whether to copy the expression or not.
5127
5128    Returns:
5129        The wrapped expression.
5130    """
5131    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):
5149def to_identifier(name, quoted=None, copy=True):
5150    """Builds an identifier.
5151
5152    Args:
5153        name: The name to turn into an identifier.
5154        quoted: Whether or not force quote the identifier.
5155        copy: Whether or not to copy a passed in Identefier node.
5156
5157    Returns:
5158        The identifier ast node.
5159    """
5160
5161    if name is None:
5162        return None
5163
5164    if isinstance(name, Identifier):
5165        identifier = _maybe_copy(name, copy)
5166    elif isinstance(name, str):
5167        identifier = Identifier(
5168            this=name,
5169            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5170        )
5171    else:
5172        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5173    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:
5179def to_interval(interval: str | Literal) -> Interval:
5180    """Builds an interval expression from a string like '1 day' or '5 months'."""
5181    if isinstance(interval, Literal):
5182        if not interval.is_string:
5183            raise ValueError("Invalid interval string.")
5184
5185        interval = interval.this
5186
5187    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5188
5189    if not interval_parts:
5190        raise ValueError("Invalid interval string.")
5191
5192    return Interval(
5193        this=Literal.string(interval_parts.group(1)),
5194        unit=Var(this=interval_parts.group(2)),
5195    )

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

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:
5367def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5368    """Cast an expression to a data type.
5369
5370    Example:
5371        >>> cast('x + 1', 'int').sql()
5372        'CAST(x + 1 AS INT)'
5373
5374    Args:
5375        expression: The expression to cast.
5376        to: The datatype to cast to.
5377
5378    Returns:
5379        The new Cast instance.
5380    """
5381    expression = maybe_parse(expression, **opts)
5382    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:
5385def table_(
5386    table: Identifier | str,
5387    db: t.Optional[Identifier | str] = None,
5388    catalog: t.Optional[Identifier | str] = None,
5389    quoted: t.Optional[bool] = None,
5390    alias: t.Optional[Identifier | str] = None,
5391) -> Table:
5392    """Build a Table.
5393
5394    Args:
5395        table: Table name.
5396        db: Database name.
5397        catalog: Catalog name.
5398        quote: Whether to force quotes on the table's identifiers.
5399        alias: Table's alias.
5400
5401    Returns:
5402        The new Table instance.
5403    """
5404    return Table(
5405        this=to_identifier(table, quoted=quoted),
5406        db=to_identifier(db, quoted=quoted),
5407        catalog=to_identifier(catalog, quoted=quoted),
5408        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5409    )

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

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:
5445def var(name: t.Optional[ExpOrStr]) -> Var:
5446    """Build a SQL variable.
5447
5448    Example:
5449        >>> repr(var('x'))
5450        '(VAR this: x)'
5451
5452        >>> repr(var(column('x', table='y')))
5453        '(VAR this: x)'
5454
5455    Args:
5456        name: The name of the var or an expression who's name will become the var.
5457
5458    Returns:
5459        The new variable node.
5460    """
5461    if not name:
5462        raise ValueError("Cannot convert empty name into var.")
5463
5464    if isinstance(name, Expression):
5465        name = name.name
5466    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:
5469def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5470    """Build ALTER TABLE... RENAME... expression
5471
5472    Args:
5473        old_name: The old name of the table
5474        new_name: The new name of the table
5475
5476    Returns:
5477        Alter table expression
5478    """
5479    old_table = to_table(old_name)
5480    new_table = to_table(new_name)
5481    return AlterTable(
5482        this=old_table,
5483        actions=[
5484            RenameTable(this=new_table),
5485        ],
5486    )

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:
5489def convert(value: t.Any, copy: bool = False) -> Expression:
5490    """Convert a python value into an expression object.
5491
5492    Raises an error if a conversion is not possible.
5493
5494    Args:
5495        value: A python object.
5496        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5497
5498    Returns:
5499        Expression: the equivalent expression object.
5500    """
5501    if isinstance(value, Expression):
5502        return _maybe_copy(value, copy)
5503    if isinstance(value, str):
5504        return Literal.string(value)
5505    if isinstance(value, bool):
5506        return Boolean(this=value)
5507    if value is None or (isinstance(value, float) and math.isnan(value)):
5508        return NULL
5509    if isinstance(value, numbers.Number):
5510        return Literal.number(value)
5511    if isinstance(value, datetime.datetime):
5512        datetime_literal = Literal.string(
5513            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5514        )
5515        return TimeStrToTime(this=datetime_literal)
5516    if isinstance(value, datetime.date):
5517        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5518        return DateStrToDate(this=date_literal)
5519    if isinstance(value, tuple):
5520        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5521    if isinstance(value, list):
5522        return Array(expressions=[convert(v, copy=copy) for v in value])
5523    if isinstance(value, dict):
5524        return Map(
5525            keys=[convert(k, copy=copy) for k in value],
5526            values=[convert(v, copy=copy) for v in value.values()],
5527        )
5528    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:
5531def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5532    """
5533    Replace children of an expression with the result of a lambda fun(child) -> exp.
5534    """
5535    for k, v in expression.args.items():
5536        is_list_arg = type(v) is list
5537
5538        child_nodes = v if is_list_arg else [v]
5539        new_child_nodes = []
5540
5541        for cn in child_nodes:
5542            if isinstance(cn, Expression):
5543                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5544                    new_child_nodes.append(child_node)
5545                    child_node.parent = expression
5546                    child_node.arg_key = k
5547            else:
5548                new_child_nodes.append(cn)
5549
5550        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]:
5553def column_table_names(expression: Expression) -> t.List[str]:
5554    """
5555    Return all table names referenced through columns in an expression.
5556
5557    Example:
5558        >>> import sqlglot
5559        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
5560        ['c', 'a']
5561
5562    Args:
5563        expression: expression to find table names.
5564
5565    Returns:
5566        A list of unique names.
5567    """
5568    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:
5571def table_name(table: Table | str) -> str:
5572    """Get the full name of a table as a string.
5573
5574    Args:
5575        table: table expression node or string.
5576
5577    Examples:
5578        >>> from sqlglot import exp, parse_one
5579        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5580        'a.b.c'
5581
5582    Returns:
5583        The table name.
5584    """
5585
5586    table = maybe_parse(table, into=Table)
5587
5588    if not table:
5589        raise ValueError(f"Cannot parse {table}")
5590
5591    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:
5594def replace_tables(expression: E, mapping: t.Dict[str, str]) -> E:
5595    """Replace all tables in expression according to the mapping.
5596
5597    Args:
5598        expression: expression node to be transformed and replaced.
5599        mapping: mapping of table names.
5600
5601    Examples:
5602        >>> from sqlglot import exp, parse_one
5603        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5604        'SELECT * FROM c'
5605
5606    Returns:
5607        The mapped expression.
5608    """
5609
5610    def _replace_tables(node: Expression) -> Expression:
5611        if isinstance(node, Table):
5612            new_name = mapping.get(table_name(node))
5613            if new_name:
5614                return to_table(
5615                    new_name,
5616                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5617                )
5618        return node
5619
5620    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:
5623def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5624    """Replace placeholders in an expression.
5625
5626    Args:
5627        expression: expression node to be transformed and replaced.
5628        args: positional names that will substitute unnamed placeholders in the given order.
5629        kwargs: keyword arguments that will substitute named placeholders.
5630
5631    Examples:
5632        >>> from sqlglot import exp, parse_one
5633        >>> replace_placeholders(
5634        ...     parse_one("select * from :tbl where ? = ?"),
5635        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5636        ... ).sql()
5637        "SELECT * FROM foo WHERE str_col = 'b'"
5638
5639    Returns:
5640        The mapped expression.
5641    """
5642
5643    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5644        if isinstance(node, Placeholder):
5645            if node.name:
5646                new_name = kwargs.get(node.name)
5647                if new_name:
5648                    return convert(new_name)
5649            else:
5650                try:
5651                    return convert(next(args))
5652                except StopIteration:
5653                    pass
5654        return node
5655
5656    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:
5659def expand(
5660    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5661) -> Expression:
5662    """Transforms an expression by expanding all referenced sources into subqueries.
5663
5664    Examples:
5665        >>> from sqlglot import parse_one
5666        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5667        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5668
5669        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5670        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5671
5672    Args:
5673        expression: The expression to expand.
5674        sources: A dictionary of name to Subqueryables.
5675        copy: Whether or not to copy the expression during transformation. Defaults to True.
5676
5677    Returns:
5678        The transformed expression.
5679    """
5680
5681    def _expand(node: Expression):
5682        if isinstance(node, Table):
5683            name = table_name(node)
5684            source = sources.get(name)
5685            if source:
5686                subquery = source.subquery(node.alias or name)
5687                subquery.comments = [f"source: {name}"]
5688                return subquery.transform(_expand, copy=False)
5689        return node
5690
5691    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:
5694def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5695    """
5696    Returns a Func expression.
5697
5698    Examples:
5699        >>> func("abs", 5).sql()
5700        'ABS(5)'
5701
5702        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5703        'CAST(5 AS DOUBLE)'
5704
5705    Args:
5706        name: the name of the function to build.
5707        args: the args used to instantiate the function of interest.
5708        dialect: the source dialect.
5709        kwargs: the kwargs used to instantiate the function of interest.
5710
5711    Note:
5712        The arguments `args` and `kwargs` are mutually exclusive.
5713
5714    Returns:
5715        An instance of the function of interest, or an anonymous function, if `name` doesn't
5716        correspond to an existing `sqlglot.expressions.Func` class.
5717    """
5718    if args and kwargs:
5719        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5720
5721    from sqlglot.dialects.dialect import Dialect
5722
5723    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5724    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5725
5726    parser = Dialect.get_or_raise(dialect)().parser()
5727    from_args_list = parser.FUNCTIONS.get(name.upper())
5728
5729    if from_args_list:
5730        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5731    else:
5732        kwargs = kwargs or {"expressions": converted}
5733        function = Anonymous(this=name, **kwargs)
5734
5735    for error_message in function.error_messages(converted):
5736        raise ValueError(error_message)
5737
5738    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:
5741def true() -> Boolean:
5742    """
5743    Returns a true Boolean expression.
5744    """
5745    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5748def false() -> Boolean:
5749    """
5750    Returns a false Boolean expression.
5751    """
5752    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5755def null() -> Null:
5756    """
5757    Returns a Null expression.
5758    """
5759    return Null()

Returns a Null expression.