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

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

Returns a deep copy of the expression.

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

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
311    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
312        """Yields the key and expression for all arguments, exploding list args."""
313        for k, vs in self.args.items():
314            if type(vs) is list:
315                for v in vs:
316                    if hasattr(v, "parent"):
317                        yield k, v
318            else:
319                if hasattr(vs, "parent"):
320                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
322    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
323        """
324        Returns the first node in this tree which matches at least one of
325        the specified types.
326
327        Args:
328            expression_types: the expression type(s) to match.
329
330        Returns:
331            The node which matches the criteria or None if no such node was found.
332        """
333        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.
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs=True) -> Iterator[~E]:
335    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
336        """
337        Returns a generator object which visits all nodes in this tree and only
338        yields those that match at least one of the specified expression types.
339
340        Args:
341            expression_types: the expression type(s) to match.
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.
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
350    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
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

Returns the parent select statement.

same_parent

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):
545    def replace(self, expression):
546        """
547        Swap out this expression with a new expression.
548
549        For example::
550
551            >>> tree = Select().select("x").from_("tbl")
552            >>> tree.find(Column).replace(Column(this="y"))
553            (COLUMN this: y)
554            >>> tree.sql()
555            'SELECT y FROM tbl'
556
557        Args:
558            expression (Expression|None): new node
559
560        Returns:
561            The new expression or expressions.
562        """
563        if not self.parent:
564            return expression
565
566        parent = self.parent
567        self.parent = None
568
569        replace_children(parent, lambda child: expression if child is self else child)
570        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 (Expression|None): new node
Returns:

The new expression or expressions.

def pop(self):
572    def pop(self):
573        """
574        Remove this expression from its AST.
575
576        Returns:
577            The popped expression.
578        """
579        self.replace(None)
580        return self

Remove this expression from its AST.

Returns:

The popped expression.

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

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
641    @classmethod
642    def load(cls, obj):
643        """
644        Load a dict (as returned by `Expression.dump`) into an Expression instance.
645        """
646        from sqlglot.serde import load
647
648        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

class Condition(Expression):
659class Condition(Expression):
660    def and_(self, *expressions, dialect=None, copy=True, **opts):
661        """
662        AND this condition with one or multiple expressions.
663
664        Example:
665            >>> condition("x=1").and_("y=1").sql()
666            'x = 1 AND y = 1'
667
668        Args:
669            *expressions (str | Expression): the SQL code strings to parse.
670                If an `Expression` instance is passed, it will be used as-is.
671            dialect (str): the dialect used to parse the input expression.
672            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
673            opts (kwargs): other options to use to parse the input expressions.
674
675        Returns:
676            And: the new condition.
677        """
678        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
679
680    def or_(self, *expressions, dialect=None, copy=True, **opts):
681        """
682        OR this condition with one or multiple expressions.
683
684        Example:
685            >>> condition("x=1").or_("y=1").sql()
686            'x = 1 OR y = 1'
687
688        Args:
689            *expressions (str | Expression): the SQL code strings to parse.
690                If an `Expression` instance is passed, it will be used as-is.
691            dialect (str): the dialect used to parse the input expression.
692            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
693            opts (kwargs): other options to use to parse the input expressions.
694
695        Returns:
696            Or: the new condition.
697        """
698        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
699
700    def not_(self, copy=True):
701        """
702        Wrap this condition with NOT.
703
704        Example:
705            >>> condition("x=1").not_().sql()
706            'NOT x = 1'
707
708        Args:
709            copy (bool): whether or not to copy this object.
710
711        Returns:
712            Not: the new condition.
713        """
714        return not_(self, copy=copy)
715
716    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
717        this = self.copy()
718        other = convert(other, copy=True)
719        if not isinstance(this, klass) and not isinstance(other, klass):
720            this = _wrap(this, Binary)
721            other = _wrap(other, Binary)
722        if reverse:
723            return klass(this=other, expression=this)
724        return klass(this=this, expression=other)
725
726    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
727        return Bracket(
728            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
729        )
730
731    def isin(
732        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
733    ) -> In:
734        return In(
735            this=_maybe_copy(self, copy),
736            expressions=[convert(e, copy=copy) for e in expressions],
737            query=maybe_parse(query, copy=copy, **opts) if query else None,
738        )
739
740    def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between:
741        return Between(
742            this=_maybe_copy(self, copy),
743            low=convert(low, copy=copy, **opts),
744            high=convert(high, copy=copy, **opts),
745        )
746
747    def like(self, other: ExpOrStr) -> Like:
748        return self._binop(Like, other)
749
750    def ilike(self, other: ExpOrStr) -> ILike:
751        return self._binop(ILike, other)
752
753    def eq(self, other: t.Any) -> EQ:
754        return self._binop(EQ, other)
755
756    def neq(self, other: t.Any) -> NEQ:
757        return self._binop(NEQ, other)
758
759    def rlike(self, other: ExpOrStr) -> RegexpLike:
760        return self._binop(RegexpLike, other)
761
762    def __lt__(self, other: t.Any) -> LT:
763        return self._binop(LT, other)
764
765    def __le__(self, other: t.Any) -> LTE:
766        return self._binop(LTE, other)
767
768    def __gt__(self, other: t.Any) -> GT:
769        return self._binop(GT, other)
770
771    def __ge__(self, other: t.Any) -> GTE:
772        return self._binop(GTE, other)
773
774    def __add__(self, other: t.Any) -> Add:
775        return self._binop(Add, other)
776
777    def __radd__(self, other: t.Any) -> Add:
778        return self._binop(Add, other, reverse=True)
779
780    def __sub__(self, other: t.Any) -> Sub:
781        return self._binop(Sub, other)
782
783    def __rsub__(self, other: t.Any) -> Sub:
784        return self._binop(Sub, other, reverse=True)
785
786    def __mul__(self, other: t.Any) -> Mul:
787        return self._binop(Mul, other)
788
789    def __rmul__(self, other: t.Any) -> Mul:
790        return self._binop(Mul, other, reverse=True)
791
792    def __truediv__(self, other: t.Any) -> Div:
793        return self._binop(Div, other)
794
795    def __rtruediv__(self, other: t.Any) -> Div:
796        return self._binop(Div, other, reverse=True)
797
798    def __floordiv__(self, other: t.Any) -> IntDiv:
799        return self._binop(IntDiv, other)
800
801    def __rfloordiv__(self, other: t.Any) -> IntDiv:
802        return self._binop(IntDiv, other, reverse=True)
803
804    def __mod__(self, other: t.Any) -> Mod:
805        return self._binop(Mod, other)
806
807    def __rmod__(self, other: t.Any) -> Mod:
808        return self._binop(Mod, other, reverse=True)
809
810    def __pow__(self, other: t.Any) -> Pow:
811        return self._binop(Pow, other)
812
813    def __rpow__(self, other: t.Any) -> Pow:
814        return self._binop(Pow, other, reverse=True)
815
816    def __and__(self, other: t.Any) -> And:
817        return self._binop(And, other)
818
819    def __rand__(self, other: t.Any) -> And:
820        return self._binop(And, other, reverse=True)
821
822    def __or__(self, other: t.Any) -> Or:
823        return self._binop(Or, other)
824
825    def __ror__(self, other: t.Any) -> Or:
826        return self._binop(Or, other, reverse=True)
827
828    def __neg__(self) -> Neg:
829        return Neg(this=_wrap(self.copy(), Binary))
830
831    def __invert__(self) -> Not:
832        return not_(self.copy())
def and_(self, *expressions, dialect=None, copy=True, **opts):
660    def and_(self, *expressions, dialect=None, copy=True, **opts):
661        """
662        AND this condition with one or multiple expressions.
663
664        Example:
665            >>> condition("x=1").and_("y=1").sql()
666            'x = 1 AND y = 1'
667
668        Args:
669            *expressions (str | Expression): the SQL code strings to parse.
670                If an `Expression` instance is passed, it will be used as-is.
671            dialect (str): the dialect used to parse the input expression.
672            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
673            opts (kwargs): other options to use to parse the input expressions.
674
675        Returns:
676            And: the new condition.
677        """
678        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 (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

And: the new condition.

def or_(self, *expressions, dialect=None, copy=True, **opts):
680    def or_(self, *expressions, dialect=None, copy=True, **opts):
681        """
682        OR this condition with one or multiple expressions.
683
684        Example:
685            >>> condition("x=1").or_("y=1").sql()
686            'x = 1 OR y = 1'
687
688        Args:
689            *expressions (str | Expression): the SQL code strings to parse.
690                If an `Expression` instance is passed, it will be used as-is.
691            dialect (str): the dialect used to parse the input expression.
692            copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
693            opts (kwargs): other options to use to parse the input expressions.
694
695        Returns:
696            Or: the new condition.
697        """
698        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 (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): whether or not to copy the involved expressions (only applies to Expressions).
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Or: the new condition.

def not_(self, copy=True):
700    def not_(self, copy=True):
701        """
702        Wrap this condition with NOT.
703
704        Example:
705            >>> condition("x=1").not_().sql()
706            'NOT x = 1'
707
708        Args:
709            copy (bool): whether or not to copy this object.
710
711        Returns:
712            Not: the new condition.
713        """
714        return not_(self, copy=copy)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Arguments:
  • copy (bool): whether or not to copy this object.
Returns:

Not: the new condition.

def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy=True, **opts) -> sqlglot.expressions.In:
731    def isin(
732        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
733    ) -> In:
734        return In(
735            this=_maybe_copy(self, copy),
736            expressions=[convert(e, copy=copy) for e in expressions],
737            query=maybe_parse(query, copy=copy, **opts) if query else None,
738        )
def between( self, low: Any, high: Any, copy=True, **opts) -> sqlglot.expressions.Between:
740    def between(self, low: t.Any, high: t.Any, copy=True, **opts) -> Between:
741        return Between(
742            this=_maybe_copy(self, copy),
743            low=convert(low, copy=copy, **opts),
744            high=convert(high, copy=copy, **opts),
745        )
def like( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Like:
747    def like(self, other: ExpOrStr) -> Like:
748        return self._binop(Like, other)
def ilike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.ILike:
750    def ilike(self, other: ExpOrStr) -> ILike:
751        return self._binop(ILike, other)
def eq(self, other: Any) -> sqlglot.expressions.EQ:
753    def eq(self, other: t.Any) -> EQ:
754        return self._binop(EQ, other)
def neq(self, other: Any) -> sqlglot.expressions.NEQ:
756    def neq(self, other: t.Any) -> NEQ:
757        return self._binop(NEQ, other)
def rlike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.RegexpLike:
759    def rlike(self, other: ExpOrStr) -> RegexpLike:
760        return self._binop(RegexpLike, other)
class Predicate(Condition):
835class Predicate(Condition):
836    """Relationships like x = y, x > 1, x >= y."""

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

class DerivedTable(Expression):
839class DerivedTable(Expression):
840    @property
841    def alias_column_names(self):
842        table_alias = self.args.get("alias")
843        if not table_alias:
844            return []
845        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
846        return [c.name for c in column_list]
847
848    @property
849    def selects(self):
850        return self.this.selects if isinstance(self.this, Subqueryable) else []
851
852    @property
853    def named_selects(self):
854        return [select.output_name for select in self.selects]
class Unionable(Expression):
857class Unionable(Expression):
858    def union(self, expression, distinct=True, dialect=None, **opts):
859        """
860        Builds a UNION expression.
861
862        Example:
863            >>> import sqlglot
864            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
865            'SELECT * FROM foo UNION SELECT * FROM bla'
866
867        Args:
868            expression (str | Expression): the SQL code string.
869                If an `Expression` instance is passed, it will be used as-is.
870            distinct (bool): set the DISTINCT flag if and only if this is true.
871            dialect (str): the dialect used to parse the input expression.
872            opts (kwargs): other options to use to parse the input expressions.
873        Returns:
874            Union: the Union expression.
875        """
876        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
877
878    def intersect(self, expression, distinct=True, dialect=None, **opts):
879        """
880        Builds an INTERSECT expression.
881
882        Example:
883            >>> import sqlglot
884            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
885            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
886
887        Args:
888            expression (str | Expression): the SQL code string.
889                If an `Expression` instance is passed, it will be used as-is.
890            distinct (bool): set the DISTINCT flag if and only if this is true.
891            dialect (str): the dialect used to parse the input expression.
892            opts (kwargs): other options to use to parse the input expressions.
893        Returns:
894            Intersect: the Intersect expression
895        """
896        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
897
898    def except_(self, expression, distinct=True, dialect=None, **opts):
899        """
900        Builds an EXCEPT expression.
901
902        Example:
903            >>> import sqlglot
904            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
905            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
906
907        Args:
908            expression (str | Expression): the SQL code string.
909                If an `Expression` instance is passed, it will be used as-is.
910            distinct (bool): set the DISTINCT flag if and only if this is true.
911            dialect (str): the dialect used to parse the input expression.
912            opts (kwargs): other options to use to parse the input expressions.
913        Returns:
914            Except: the Except expression
915        """
916        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
858    def union(self, expression, distinct=True, dialect=None, **opts):
859        """
860        Builds a UNION expression.
861
862        Example:
863            >>> import sqlglot
864            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
865            'SELECT * FROM foo UNION SELECT * FROM bla'
866
867        Args:
868            expression (str | Expression): the SQL code string.
869                If an `Expression` instance is passed, it will be used as-is.
870            distinct (bool): set the DISTINCT flag if and only if this is true.
871            dialect (str): the dialect used to parse the input expression.
872            opts (kwargs): other options to use to parse the input expressions.
873        Returns:
874            Union: the Union expression.
875        """
876        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 (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the Union expression.

def intersect(self, expression, distinct=True, dialect=None, **opts):
878    def intersect(self, expression, distinct=True, dialect=None, **opts):
879        """
880        Builds an INTERSECT expression.
881
882        Example:
883            >>> import sqlglot
884            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
885            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
886
887        Args:
888            expression (str | Expression): the SQL code string.
889                If an `Expression` instance is passed, it will be used as-is.
890            distinct (bool): set the DISTINCT flag if and only if this is true.
891            dialect (str): the dialect used to parse the input expression.
892            opts (kwargs): other options to use to parse the input expressions.
893        Returns:
894            Intersect: the Intersect expression
895        """
896        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 (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the Intersect expression

def except_(self, expression, distinct=True, dialect=None, **opts):
898    def except_(self, expression, distinct=True, dialect=None, **opts):
899        """
900        Builds an EXCEPT expression.
901
902        Example:
903            >>> import sqlglot
904            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
905            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
906
907        Args:
908            expression (str | Expression): the SQL code string.
909                If an `Expression` instance is passed, it will be used as-is.
910            distinct (bool): set the DISTINCT flag if and only if this is true.
911            dialect (str): the dialect used to parse the input expression.
912            opts (kwargs): other options to use to parse the input expressions.
913        Returns:
914            Except: the Except expression
915        """
916        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 (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the Except expression

class UDTF(DerivedTable, Unionable):
919class UDTF(DerivedTable, Unionable):
920    @property
921    def selects(self):
922        alias = self.args.get("alias")
923        return alias.columns if alias else []
class Cache(Expression):
926class Cache(Expression):
927    arg_types = {
928        "with": False,
929        "this": True,
930        "lazy": False,
931        "options": False,
932        "expression": False,
933    }
class Uncache(Expression):
936class Uncache(Expression):
937    arg_types = {"this": True, "exists": False}
class Create(Expression):
940class Create(Expression):
941    arg_types = {
942        "with": False,
943        "this": True,
944        "kind": True,
945        "expression": False,
946        "exists": False,
947        "properties": False,
948        "replace": False,
949        "unique": False,
950        "indexes": False,
951        "no_schema_binding": False,
952        "begin": False,
953        "clone": False,
954    }
class Clone(Expression):
958class Clone(Expression):
959    arg_types = {
960        "this": True,
961        "when": False,
962        "kind": False,
963        "expression": False,
964    }
class Describe(Expression):
967class Describe(Expression):
968    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
971class Pragma(Expression):
972    pass
class Set(Expression):
975class Set(Expression):
976    arg_types = {"expressions": False}
class SetItem(Expression):
979class SetItem(Expression):
980    arg_types = {
981        "this": False,
982        "expressions": False,
983        "kind": False,
984        "collate": False,  # MySQL SET NAMES statement
985        "global": False,
986    }
class Show(Expression):
 989class Show(Expression):
 990    arg_types = {
 991        "this": True,
 992        "target": False,
 993        "offset": False,
 994        "limit": False,
 995        "like": False,
 996        "where": False,
 997        "db": False,
 998        "full": False,
 999        "mutex": False,
1000        "query": False,
1001        "channel": False,
1002        "global": False,
1003        "log": False,
1004        "position": False,
1005        "types": False,
1006    }
class UserDefinedFunction(Expression):
1009class UserDefinedFunction(Expression):
1010    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
1013class CharacterSet(Expression):
1014    arg_types = {"this": True, "default": False}
class With(Expression):
1017class With(Expression):
1018    arg_types = {"expressions": True, "recursive": False}
1019
1020    @property
1021    def recursive(self) -> bool:
1022        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
1025class WithinGroup(Expression):
1026    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
1029class CTE(DerivedTable):
1030    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
1033class TableAlias(Expression):
1034    arg_types = {"this": False, "columns": False}
1035
1036    @property
1037    def columns(self):
1038        return self.args.get("columns") or []
class BitString(Condition):
1041class BitString(Condition):
1042    pass
class HexString(Condition):
1045class HexString(Condition):
1046    pass
class ByteString(Condition):
1049class ByteString(Condition):
1050    pass
class Column(Condition):
1053class Column(Condition):
1054    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1055
1056    @property
1057    def table(self) -> str:
1058        return self.text("table")
1059
1060    @property
1061    def db(self) -> str:
1062        return self.text("db")
1063
1064    @property
1065    def catalog(self) -> str:
1066        return self.text("catalog")
1067
1068    @property
1069    def output_name(self) -> str:
1070        return self.name
1071
1072    @property
1073    def parts(self) -> t.List[Identifier]:
1074        """Return the parts of a column in order catalog, db, table, name."""
1075        return [
1076            t.cast(Identifier, self.args[part])
1077            for part in ("catalog", "db", "table", "this")
1078            if self.args.get(part)
1079        ]
1080
1081    def to_dot(self) -> Dot:
1082        """Converts the column into a dot expression."""
1083        parts = self.parts
1084        parent = self.parent
1085
1086        while parent:
1087            if isinstance(parent, Dot):
1088                parts.append(parent.expression)
1089            parent = parent.parent
1090
1091        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:
1081    def to_dot(self) -> Dot:
1082        """Converts the column into a dot expression."""
1083        parts = self.parts
1084        parent = self.parent
1085
1086        while parent:
1087            if isinstance(parent, Dot):
1088                parts.append(parent.expression)
1089            parent = parent.parent
1090
1091        return Dot.build(parts)

Converts the column into a dot expression.

class ColumnPosition(Expression):
1094class ColumnPosition(Expression):
1095    arg_types = {"this": False, "position": True}
class ColumnDef(Expression):
1098class ColumnDef(Expression):
1099    arg_types = {
1100        "this": True,
1101        "kind": False,
1102        "constraints": False,
1103        "exists": False,
1104        "position": False,
1105    }
1106
1107    @property
1108    def constraints(self) -> t.List[ColumnConstraint]:
1109        return self.args.get("constraints") or []
class AlterColumn(Expression):
1112class AlterColumn(Expression):
1113    arg_types = {
1114        "this": True,
1115        "dtype": False,
1116        "collate": False,
1117        "using": False,
1118        "default": False,
1119        "drop": False,
1120    }
class RenameTable(Expression):
1123class RenameTable(Expression):
1124    pass
class SetTag(Expression):
1127class SetTag(Expression):
1128    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
1131class Comment(Expression):
1132    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class MergeTreeTTLAction(Expression):
1136class MergeTreeTTLAction(Expression):
1137    arg_types = {
1138        "this": True,
1139        "delete": False,
1140        "recompress": False,
1141        "to_disk": False,
1142        "to_volume": False,
1143    }
class MergeTreeTTL(Expression):
1147class MergeTreeTTL(Expression):
1148    arg_types = {
1149        "expressions": True,
1150        "where": False,
1151        "group": False,
1152        "aggregates": False,
1153    }
class ColumnConstraint(Expression):
1156class ColumnConstraint(Expression):
1157    arg_types = {"this": False, "kind": True}
1158
1159    @property
1160    def kind(self) -> ColumnConstraintKind:
1161        return self.args["kind"]
class ColumnConstraintKind(Expression):
1164class ColumnConstraintKind(Expression):
1165    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1168class AutoIncrementColumnConstraint(ColumnConstraintKind):
1169    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1172class CaseSpecificColumnConstraint(ColumnConstraintKind):
1173    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1176class CharacterSetColumnConstraint(ColumnConstraintKind):
1177    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1180class CheckColumnConstraint(ColumnConstraintKind):
1181    pass
class CollateColumnConstraint(ColumnConstraintKind):
1184class CollateColumnConstraint(ColumnConstraintKind):
1185    pass
class CommentColumnConstraint(ColumnConstraintKind):
1188class CommentColumnConstraint(ColumnConstraintKind):
1189    pass
class CompressColumnConstraint(ColumnConstraintKind):
1192class CompressColumnConstraint(ColumnConstraintKind):
1193    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1196class DateFormatColumnConstraint(ColumnConstraintKind):
1197    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1200class DefaultColumnConstraint(ColumnConstraintKind):
1201    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1204class EncodeColumnConstraint(ColumnConstraintKind):
1205    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1208class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1209    # this: True -> ALWAYS, this: False -> BY DEFAULT
1210    arg_types = {
1211        "this": False,
1212        "on_null": False,
1213        "start": False,
1214        "increment": False,
1215        "minvalue": False,
1216        "maxvalue": False,
1217        "cycle": False,
1218    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1221class InlineLengthColumnConstraint(ColumnConstraintKind):
1222    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1225class NotNullColumnConstraint(ColumnConstraintKind):
1226    arg_types = {"allow_null": False}
class OnUpdateColumnConstraint(ColumnConstraintKind):
1230class OnUpdateColumnConstraint(ColumnConstraintKind):
1231    pass
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1234class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1235    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1238class TitleColumnConstraint(ColumnConstraintKind):
1239    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1242class UniqueColumnConstraint(ColumnConstraintKind):
1243    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1246class UppercaseColumnConstraint(ColumnConstraintKind):
1247    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1250class PathColumnConstraint(ColumnConstraintKind):
1251    pass
class Constraint(Expression):
1254class Constraint(Expression):
1255    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1258class Delete(Expression):
1259    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1260
1261    def delete(
1262        self,
1263        table: ExpOrStr,
1264        dialect: DialectType = None,
1265        copy: bool = True,
1266        **opts,
1267    ) -> Delete:
1268        """
1269        Create a DELETE expression or replace the table on an existing DELETE expression.
1270
1271        Example:
1272            >>> delete("tbl").sql()
1273            'DELETE FROM tbl'
1274
1275        Args:
1276            table: the table from which to delete.
1277            dialect: the dialect used to parse the input expression.
1278            copy: if `False`, modify this expression instance in-place.
1279            opts: other options to use to parse the input expressions.
1280
1281        Returns:
1282            Delete: the modified expression.
1283        """
1284        return _apply_builder(
1285            expression=table,
1286            instance=self,
1287            arg="this",
1288            dialect=dialect,
1289            into=Table,
1290            copy=copy,
1291            **opts,
1292        )
1293
1294    def where(
1295        self,
1296        *expressions: ExpOrStr,
1297        append: bool = True,
1298        dialect: DialectType = None,
1299        copy: bool = True,
1300        **opts,
1301    ) -> Delete:
1302        """
1303        Append to or set the WHERE expressions.
1304
1305        Example:
1306            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1307            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1308
1309        Args:
1310            *expressions: the SQL code strings to parse.
1311                If an `Expression` instance is passed, it will be used as-is.
1312                Multiple expressions are combined with an AND operator.
1313            append: if `True`, AND the new expressions to any existing expression.
1314                Otherwise, this resets the expression.
1315            dialect: the dialect used to parse the input expressions.
1316            copy: if `False`, modify this expression instance in-place.
1317            opts: other options to use to parse the input expressions.
1318
1319        Returns:
1320            Delete: the modified expression.
1321        """
1322        return _apply_conjunction_builder(
1323            *expressions,
1324            instance=self,
1325            arg="where",
1326            append=append,
1327            into=Where,
1328            dialect=dialect,
1329            copy=copy,
1330            **opts,
1331        )
1332
1333    def returning(
1334        self,
1335        expression: ExpOrStr,
1336        dialect: DialectType = None,
1337        copy: bool = True,
1338        **opts,
1339    ) -> Delete:
1340        """
1341        Set the RETURNING expression. Not supported by all dialects.
1342
1343        Example:
1344            >>> delete("tbl").returning("*", dialect="postgres").sql()
1345            'DELETE FROM tbl RETURNING *'
1346
1347        Args:
1348            expression: the SQL code strings to parse.
1349                If an `Expression` instance is passed, it will be used as-is.
1350            dialect: the dialect used to parse the input expressions.
1351            copy: if `False`, modify this expression instance in-place.
1352            opts: other options to use to parse the input expressions.
1353
1354        Returns:
1355            Delete: the modified expression.
1356        """
1357        return _apply_builder(
1358            expression=expression,
1359            instance=self,
1360            arg="returning",
1361            prefix="RETURNING",
1362            dialect=dialect,
1363            copy=copy,
1364            into=Returning,
1365            **opts,
1366        )
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:
1261    def delete(
1262        self,
1263        table: ExpOrStr,
1264        dialect: DialectType = None,
1265        copy: bool = True,
1266        **opts,
1267    ) -> Delete:
1268        """
1269        Create a DELETE expression or replace the table on an existing DELETE expression.
1270
1271        Example:
1272            >>> delete("tbl").sql()
1273            'DELETE FROM tbl'
1274
1275        Args:
1276            table: the table from which to delete.
1277            dialect: the dialect used to parse the input expression.
1278            copy: if `False`, modify this expression instance in-place.
1279            opts: other options to use to parse the input expressions.
1280
1281        Returns:
1282            Delete: the modified expression.
1283        """
1284        return _apply_builder(
1285            expression=table,
1286            instance=self,
1287            arg="this",
1288            dialect=dialect,
1289            into=Table,
1290            copy=copy,
1291            **opts,
1292        )

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], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1294    def where(
1295        self,
1296        *expressions: ExpOrStr,
1297        append: bool = True,
1298        dialect: DialectType = None,
1299        copy: bool = True,
1300        **opts,
1301    ) -> Delete:
1302        """
1303        Append to or set the WHERE expressions.
1304
1305        Example:
1306            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1307            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1308
1309        Args:
1310            *expressions: the SQL code strings to parse.
1311                If an `Expression` instance is passed, it will be used as-is.
1312                Multiple expressions are combined with an AND operator.
1313            append: if `True`, AND the new expressions to any existing expression.
1314                Otherwise, this resets the expression.
1315            dialect: the dialect used to parse the input expressions.
1316            copy: if `False`, modify this expression instance in-place.
1317            opts: other options to use to parse the input expressions.
1318
1319        Returns:
1320            Delete: the modified expression.
1321        """
1322        return _apply_conjunction_builder(
1323            *expressions,
1324            instance=self,
1325            arg="where",
1326            append=append,
1327            into=Where,
1328            dialect=dialect,
1329            copy=copy,
1330            **opts,
1331        )

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:
1333    def returning(
1334        self,
1335        expression: ExpOrStr,
1336        dialect: DialectType = None,
1337        copy: bool = True,
1338        **opts,
1339    ) -> Delete:
1340        """
1341        Set the RETURNING expression. Not supported by all dialects.
1342
1343        Example:
1344            >>> delete("tbl").returning("*", dialect="postgres").sql()
1345            'DELETE FROM tbl RETURNING *'
1346
1347        Args:
1348            expression: the SQL code strings to parse.
1349                If an `Expression` instance is passed, it will be used as-is.
1350            dialect: the dialect used to parse the input expressions.
1351            copy: if `False`, modify this expression instance in-place.
1352            opts: other options to use to parse the input expressions.
1353
1354        Returns:
1355            Delete: the modified expression.
1356        """
1357        return _apply_builder(
1358            expression=expression,
1359            instance=self,
1360            arg="returning",
1361            prefix="RETURNING",
1362            dialect=dialect,
1363            copy=copy,
1364            into=Returning,
1365            **opts,
1366        )

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):
1369class Drop(Expression):
1370    arg_types = {
1371        "this": False,
1372        "kind": False,
1373        "exists": False,
1374        "temporary": False,
1375        "materialized": False,
1376        "cascade": False,
1377        "constraints": False,
1378        "purge": False,
1379    }
class Filter(Expression):
1382class Filter(Expression):
1383    arg_types = {"this": True, "expression": True}
class Check(Expression):
1386class Check(Expression):
1387    pass
class Directory(Expression):
1390class Directory(Expression):
1391    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1392    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1395class ForeignKey(Expression):
1396    arg_types = {
1397        "expressions": True,
1398        "reference": False,
1399        "delete": False,
1400        "update": False,
1401    }
class PrimaryKey(Expression):
1404class PrimaryKey(Expression):
1405    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1408class Unique(Expression):
1409    arg_types = {"expressions": True}
class Into(Expression):
1414class Into(Expression):
1415    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1418class From(Expression):
1419    @property
1420    def name(self) -> str:
1421        return self.this.name
1422
1423    @property
1424    def alias_or_name(self) -> str:
1425        return self.this.alias_or_name
class Having(Expression):
1428class Having(Expression):
1429    pass
class Hint(Expression):
1432class Hint(Expression):
1433    arg_types = {"expressions": True}
class JoinHint(Expression):
1436class JoinHint(Expression):
1437    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1440class Identifier(Expression):
1441    arg_types = {"this": True, "quoted": False}
1442
1443    @property
1444    def quoted(self):
1445        return bool(self.args.get("quoted"))
1446
1447    @property
1448    def hashable_args(self) -> t.Any:
1449        if self.quoted and any(char.isupper() for char in self.this):
1450            return (self.this, self.quoted)
1451        return self.this.lower()
1452
1453    @property
1454    def output_name(self):
1455        return self.name
output_name

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):
1458class Index(Expression):
1459    arg_types = {
1460        "this": False,
1461        "table": False,
1462        "where": False,
1463        "columns": False,
1464        "unique": False,
1465        "primary": False,
1466        "amp": False,  # teradata
1467    }
class Insert(Expression):
1470class Insert(Expression):
1471    arg_types = {
1472        "with": False,
1473        "this": True,
1474        "expression": False,
1475        "conflict": False,
1476        "returning": False,
1477        "overwrite": False,
1478        "exists": False,
1479        "partition": False,
1480        "alternative": False,
1481    }
1482
1483    def with_(
1484        self,
1485        alias: ExpOrStr,
1486        as_: ExpOrStr,
1487        recursive: t.Optional[bool] = None,
1488        append: bool = True,
1489        dialect: DialectType = None,
1490        copy: bool = True,
1491        **opts,
1492    ) -> Insert:
1493        """
1494        Append to or set the common table expressions.
1495
1496        Example:
1497            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1498            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1499
1500        Args:
1501            alias: the SQL code string to parse as the table name.
1502                If an `Expression` instance is passed, this is used as-is.
1503            as_: the SQL code string to parse as the table expression.
1504                If an `Expression` instance is passed, it will be used as-is.
1505            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1506            append: if `True`, add to any existing expressions.
1507                Otherwise, this resets the expressions.
1508            dialect: the dialect used to parse the input expression.
1509            copy: if `False`, modify this expression instance in-place.
1510            opts: other options to use to parse the input expressions.
1511
1512        Returns:
1513            The modified expression.
1514        """
1515        return _apply_cte_builder(
1516            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1517        )
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:
1483    def with_(
1484        self,
1485        alias: ExpOrStr,
1486        as_: ExpOrStr,
1487        recursive: t.Optional[bool] = None,
1488        append: bool = True,
1489        dialect: DialectType = None,
1490        copy: bool = True,
1491        **opts,
1492    ) -> Insert:
1493        """
1494        Append to or set the common table expressions.
1495
1496        Example:
1497            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1498            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1499
1500        Args:
1501            alias: the SQL code string to parse as the table name.
1502                If an `Expression` instance is passed, this is used as-is.
1503            as_: the SQL code string to parse as the table expression.
1504                If an `Expression` instance is passed, it will be used as-is.
1505            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1506            append: if `True`, add to any existing expressions.
1507                Otherwise, this resets the expressions.
1508            dialect: the dialect used to parse the input expression.
1509            copy: if `False`, modify this expression instance in-place.
1510            opts: other options to use to parse the input expressions.
1511
1512        Returns:
1513            The modified expression.
1514        """
1515        return _apply_cte_builder(
1516            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1517        )

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):
1520class OnConflict(Expression):
1521    arg_types = {
1522        "duplicate": False,
1523        "expressions": False,
1524        "nothing": False,
1525        "key": False,
1526        "constraint": False,
1527    }
class Returning(Expression):
1530class Returning(Expression):
1531    arg_types = {"expressions": True}
class Introducer(Expression):
1535class Introducer(Expression):
1536    arg_types = {"this": True, "expression": True}
class National(Expression):
1540class National(Expression):
1541    pass
class LoadData(Expression):
1544class LoadData(Expression):
1545    arg_types = {
1546        "this": True,
1547        "local": False,
1548        "overwrite": False,
1549        "inpath": True,
1550        "partition": False,
1551        "input_format": False,
1552        "serde": False,
1553    }
class Partition(Expression):
1556class Partition(Expression):
1557    arg_types = {"expressions": True}
class Fetch(Expression):
1560class Fetch(Expression):
1561    arg_types = {
1562        "direction": False,
1563        "count": False,
1564        "percent": False,
1565        "with_ties": False,
1566    }
class Group(Expression):
1569class Group(Expression):
1570    arg_types = {
1571        "expressions": False,
1572        "grouping_sets": False,
1573        "cube": False,
1574        "rollup": False,
1575        "totals": False,
1576    }
class Lambda(Expression):
1579class Lambda(Expression):
1580    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1583class Limit(Expression):
1584    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1587class Literal(Condition):
1588    arg_types = {"this": True, "is_string": True}
1589
1590    @property
1591    def hashable_args(self) -> t.Any:
1592        return (self.this, self.args.get("is_string"))
1593
1594    @classmethod
1595    def number(cls, number) -> Literal:
1596        return cls(this=str(number), is_string=False)
1597
1598    @classmethod
1599    def string(cls, string) -> Literal:
1600        return cls(this=str(string), is_string=True)
1601
1602    @property
1603    def output_name(self):
1604        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1594    @classmethod
1595    def number(cls, number) -> Literal:
1596        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1598    @classmethod
1599    def string(cls, string) -> Literal:
1600        return cls(this=str(string), is_string=True)
output_name

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):
1607class Join(Expression):
1608    arg_types = {
1609        "this": True,
1610        "on": False,
1611        "side": False,
1612        "kind": False,
1613        "using": False,
1614        "natural": False,
1615        "global": False,
1616        "hint": False,
1617    }
1618
1619    @property
1620    def kind(self):
1621        return self.text("kind").upper()
1622
1623    @property
1624    def side(self):
1625        return self.text("side").upper()
1626
1627    @property
1628    def hint(self):
1629        return self.text("hint").upper()
1630
1631    @property
1632    def alias_or_name(self):
1633        return self.this.alias_or_name
1634
1635    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1636        """
1637        Append to or set the ON expressions.
1638
1639        Example:
1640            >>> import sqlglot
1641            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1642            'JOIN x ON y = 1'
1643
1644        Args:
1645            *expressions (str | Expression): the SQL code strings to parse.
1646                If an `Expression` instance is passed, it will be used as-is.
1647                Multiple expressions are combined with an AND operator.
1648            append (bool): if `True`, AND the new expressions to any existing expression.
1649                Otherwise, this resets the expression.
1650            dialect (str): the dialect used to parse the input expressions.
1651            copy (bool): if `False`, modify this expression instance in-place.
1652            opts (kwargs): other options to use to parse the input expressions.
1653
1654        Returns:
1655            Join: the modified join expression.
1656        """
1657        join = _apply_conjunction_builder(
1658            *expressions,
1659            instance=self,
1660            arg="on",
1661            append=append,
1662            dialect=dialect,
1663            copy=copy,
1664            **opts,
1665        )
1666
1667        if join.kind == "CROSS":
1668            join.set("kind", None)
1669
1670        return join
1671
1672    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1673        """
1674        Append to or set the USING expressions.
1675
1676        Example:
1677            >>> import sqlglot
1678            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1679            'JOIN x USING (foo, bla)'
1680
1681        Args:
1682            *expressions (str | Expression): the SQL code strings to parse.
1683                If an `Expression` instance is passed, it will be used as-is.
1684            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1685                Otherwise, this resets the expression.
1686            dialect (str): the dialect used to parse the input expressions.
1687            copy (bool): if `False`, modify this expression instance in-place.
1688            opts (kwargs): other options to use to parse the input expressions.
1689
1690        Returns:
1691            Join: the modified join expression.
1692        """
1693        join = _apply_list_builder(
1694            *expressions,
1695            instance=self,
1696            arg="using",
1697            append=append,
1698            dialect=dialect,
1699            copy=copy,
1700            **opts,
1701        )
1702
1703        if join.kind == "CROSS":
1704            join.set("kind", None)
1705
1706        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1635    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1636        """
1637        Append to or set the ON expressions.
1638
1639        Example:
1640            >>> import sqlglot
1641            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1642            'JOIN x ON y = 1'
1643
1644        Args:
1645            *expressions (str | Expression): the SQL code strings to parse.
1646                If an `Expression` instance is passed, it will be used as-is.
1647                Multiple expressions are combined with an AND operator.
1648            append (bool): if `True`, AND the new expressions to any existing expression.
1649                Otherwise, this resets the expression.
1650            dialect (str): the dialect used to parse the input expressions.
1651            copy (bool): if `False`, modify this expression instance in-place.
1652            opts (kwargs): other options to use to parse the input expressions.
1653
1654        Returns:
1655            Join: the modified join expression.
1656        """
1657        join = _apply_conjunction_builder(
1658            *expressions,
1659            instance=self,
1660            arg="on",
1661            append=append,
1662            dialect=dialect,
1663            copy=copy,
1664            **opts,
1665        )
1666
1667        if join.kind == "CROSS":
1668            join.set("kind", None)
1669
1670        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 (str | Expression): 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 (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1672    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1673        """
1674        Append to or set the USING expressions.
1675
1676        Example:
1677            >>> import sqlglot
1678            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1679            'JOIN x USING (foo, bla)'
1680
1681        Args:
1682            *expressions (str | Expression): the SQL code strings to parse.
1683                If an `Expression` instance is passed, it will be used as-is.
1684            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1685                Otherwise, this resets the expression.
1686            dialect (str): the dialect used to parse the input expressions.
1687            copy (bool): if `False`, modify this expression instance in-place.
1688            opts (kwargs): other options to use to parse the input expressions.
1689
1690        Returns:
1691            Join: the modified join expression.
1692        """
1693        join = _apply_list_builder(
1694            *expressions,
1695            instance=self,
1696            arg="using",
1697            append=append,
1698            dialect=dialect,
1699            copy=copy,
1700            **opts,
1701        )
1702
1703        if join.kind == "CROSS":
1704            join.set("kind", None)
1705
1706        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 (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

class Lateral(UDTF):
1709class Lateral(UDTF):
1710    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1713class MatchRecognize(Expression):
1714    arg_types = {
1715        "partition_by": False,
1716        "order": False,
1717        "measures": False,
1718        "rows": False,
1719        "after": False,
1720        "pattern": False,
1721        "define": False,
1722        "alias": False,
1723    }
class Final(Expression):
1728class Final(Expression):
1729    pass
class Offset(Expression):
1732class Offset(Expression):
1733    arg_types = {"this": False, "expression": True}
class Order(Expression):
1736class Order(Expression):
1737    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1742class Cluster(Order):
1743    pass
class Distribute(Order):
1746class Distribute(Order):
1747    pass
class Sort(Order):
1750class Sort(Order):
1751    pass
class Ordered(Expression):
1754class Ordered(Expression):
1755    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1758class Property(Expression):
1759    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1762class AfterJournalProperty(Property):
1763    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1766class AlgorithmProperty(Property):
1767    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1770class AutoIncrementProperty(Property):
1771    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1774class BlockCompressionProperty(Property):
1775    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1778class CharacterSetProperty(Property):
1779    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1782class ChecksumProperty(Property):
1783    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1786class CollateProperty(Property):
1787    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1790class DataBlocksizeProperty(Property):
1791    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1794class DefinerProperty(Property):
1795    arg_types = {"this": True}
class DistKeyProperty(Property):
1798class DistKeyProperty(Property):
1799    arg_types = {"this": True}
class DistStyleProperty(Property):
1802class DistStyleProperty(Property):
1803    arg_types = {"this": True}
class EngineProperty(Property):
1806class EngineProperty(Property):
1807    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1810class ExecuteAsProperty(Property):
1811    arg_types = {"this": True}
class ExternalProperty(Property):
1814class ExternalProperty(Property):
1815    arg_types = {"this": False}
class FallbackProperty(Property):
1818class FallbackProperty(Property):
1819    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1822class FileFormatProperty(Property):
1823    arg_types = {"this": True}
class FreespaceProperty(Property):
1826class FreespaceProperty(Property):
1827    arg_types = {"this": True, "percent": False}
class InputOutputFormat(Expression):
1830class InputOutputFormat(Expression):
1831    arg_types = {"input_format": False, "output_format": False}
class IsolatedLoadingProperty(Property):
1834class IsolatedLoadingProperty(Property):
1835    arg_types = {
1836        "no": True,
1837        "concurrent": True,
1838        "for_all": True,
1839        "for_insert": True,
1840        "for_none": True,
1841    }
class JournalProperty(Property):
1844class JournalProperty(Property):
1845    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1848class LanguageProperty(Property):
1849    arg_types = {"this": True}
class LikeProperty(Property):
1852class LikeProperty(Property):
1853    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1856class LocationProperty(Property):
1857    arg_types = {"this": True}
class LockingProperty(Property):
1860class LockingProperty(Property):
1861    arg_types = {
1862        "this": False,
1863        "kind": True,
1864        "for_or_in": True,
1865        "lock_type": True,
1866        "override": False,
1867    }
class LogProperty(Property):
1870class LogProperty(Property):
1871    arg_types = {"no": True}
class MaterializedProperty(Property):
1874class MaterializedProperty(Property):
1875    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1878class MergeBlockRatioProperty(Property):
1879    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1882class NoPrimaryIndexProperty(Property):
1883    arg_types = {"this": False}
class OnCommitProperty(Property):
1886class OnCommitProperty(Property):
1887    arg_type = {"this": False}
class PartitionedByProperty(Property):
1890class PartitionedByProperty(Property):
1891    arg_types = {"this": True}
class ReturnsProperty(Property):
1894class ReturnsProperty(Property):
1895    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatProperty(Property):
1898class RowFormatProperty(Property):
1899    arg_types = {"this": True}
class RowFormatDelimitedProperty(Property):
1902class RowFormatDelimitedProperty(Property):
1903    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1904    arg_types = {
1905        "fields": False,
1906        "escaped": False,
1907        "collection_items": False,
1908        "map_keys": False,
1909        "lines": False,
1910        "null": False,
1911        "serde": False,
1912    }
class RowFormatSerdeProperty(Property):
1915class RowFormatSerdeProperty(Property):
1916    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1919class SchemaCommentProperty(Property):
1920    arg_types = {"this": True}
class SerdeProperties(Property):
1923class SerdeProperties(Property):
1924    arg_types = {"expressions": True}
class SetProperty(Property):
1927class SetProperty(Property):
1928    arg_types = {"multi": True}
class SettingsProperty(Property):
1931class SettingsProperty(Property):
1932    arg_types = {"expressions": True}
class SortKeyProperty(Property):
1935class SortKeyProperty(Property):
1936    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1939class SqlSecurityProperty(Property):
1940    arg_types = {"definer": True}
class StabilityProperty(Property):
1943class StabilityProperty(Property):
1944    arg_types = {"this": True}
class TableFormatProperty(Property):
1947class TableFormatProperty(Property):
1948    arg_types = {"this": True}
class TemporaryProperty(Property):
1951class TemporaryProperty(Property):
1952    arg_types = {"global_": True}
class TransientProperty(Property):
1955class TransientProperty(Property):
1956    arg_types = {"this": False}
class VolatileProperty(Property):
1959class VolatileProperty(Property):
1960    arg_types = {"this": False}
class WithDataProperty(Property):
1963class WithDataProperty(Property):
1964    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1967class WithJournalTableProperty(Property):
1968    arg_types = {"this": True}
class Properties(Expression):
1971class Properties(Expression):
1972    arg_types = {"expressions": True}
1973
1974    NAME_TO_PROPERTY = {
1975        "ALGORITHM": AlgorithmProperty,
1976        "AUTO_INCREMENT": AutoIncrementProperty,
1977        "CHARACTER SET": CharacterSetProperty,
1978        "COLLATE": CollateProperty,
1979        "COMMENT": SchemaCommentProperty,
1980        "DEFINER": DefinerProperty,
1981        "DISTKEY": DistKeyProperty,
1982        "DISTSTYLE": DistStyleProperty,
1983        "ENGINE": EngineProperty,
1984        "EXECUTE AS": ExecuteAsProperty,
1985        "FORMAT": FileFormatProperty,
1986        "LANGUAGE": LanguageProperty,
1987        "LOCATION": LocationProperty,
1988        "PARTITIONED_BY": PartitionedByProperty,
1989        "RETURNS": ReturnsProperty,
1990        "ROW_FORMAT": RowFormatProperty,
1991        "SORTKEY": SortKeyProperty,
1992        "TABLE_FORMAT": TableFormatProperty,
1993    }
1994
1995    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1996
1997    # CREATE property locations
1998    # Form: schema specified
1999    #   create [POST_CREATE]
2000    #     table a [POST_NAME]
2001    #     (b int) [POST_SCHEMA]
2002    #     with ([POST_WITH])
2003    #     index (b) [POST_INDEX]
2004    #
2005    # Form: alias selection
2006    #   create [POST_CREATE]
2007    #     table a [POST_NAME]
2008    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2009    #     index (c) [POST_INDEX]
2010    class Location(AutoName):
2011        POST_CREATE = auto()
2012        POST_NAME = auto()
2013        POST_SCHEMA = auto()
2014        POST_WITH = auto()
2015        POST_ALIAS = auto()
2016        POST_EXPRESSION = auto()
2017        POST_INDEX = auto()
2018        UNSUPPORTED = auto()
2019
2020    @classmethod
2021    def from_dict(cls, properties_dict) -> Properties:
2022        expressions = []
2023        for key, value in properties_dict.items():
2024            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2025            if property_cls:
2026                expressions.append(property_cls(this=convert(value)))
2027            else:
2028                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2029
2030        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
2020    @classmethod
2021    def from_dict(cls, properties_dict) -> Properties:
2022        expressions = []
2023        for key, value in properties_dict.items():
2024            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2025            if property_cls:
2026                expressions.append(property_cls(this=convert(value)))
2027            else:
2028                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2029
2030        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
2010    class Location(AutoName):
2011        POST_CREATE = auto()
2012        POST_NAME = auto()
2013        POST_SCHEMA = auto()
2014        POST_WITH = auto()
2015        POST_ALIAS = auto()
2016        POST_EXPRESSION = auto()
2017        POST_INDEX = auto()
2018        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):
2033class Qualify(Expression):
2034    pass
class Return(Expression):
2038class Return(Expression):
2039    pass
class Reference(Expression):
2042class Reference(Expression):
2043    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
2046class Tuple(Expression):
2047    arg_types = {"expressions": False}
2048
2049    def isin(
2050        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
2051    ) -> In:
2052        return In(
2053            this=_maybe_copy(self, copy),
2054            expressions=[convert(e, copy=copy) for e in expressions],
2055            query=maybe_parse(query, copy=copy, **opts) if query else None,
2056        )
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy=True, **opts) -> sqlglot.expressions.In:
2049    def isin(
2050        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
2051    ) -> In:
2052        return In(
2053            this=_maybe_copy(self, copy),
2054            expressions=[convert(e, copy=copy) for e in expressions],
2055            query=maybe_parse(query, copy=copy, **opts) if query else None,
2056        )
class Subqueryable(Unionable):
2059class Subqueryable(Unionable):
2060    def subquery(self, alias=None, copy=True) -> Subquery:
2061        """
2062        Convert this expression to an aliased expression that can be used as a Subquery.
2063
2064        Example:
2065            >>> subquery = Select().select("x").from_("tbl").subquery()
2066            >>> Select().select("x").from_(subquery).sql()
2067            'SELECT x FROM (SELECT x FROM tbl)'
2068
2069        Args:
2070            alias (str | Identifier): an optional alias for the subquery
2071            copy (bool): if `False`, modify this expression instance in-place.
2072
2073        Returns:
2074            Alias: the subquery
2075        """
2076        instance = _maybe_copy(self, copy)
2077        if not isinstance(alias, Expression):
2078            alias = TableAlias(this=to_identifier(alias)) if alias else None
2079
2080        return Subquery(this=instance, alias=alias)
2081
2082    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2083        raise NotImplementedError
2084
2085    @property
2086    def ctes(self):
2087        with_ = self.args.get("with")
2088        if not with_:
2089            return []
2090        return with_.expressions
2091
2092    @property
2093    def selects(self):
2094        raise NotImplementedError("Subqueryable objects must implement `selects`")
2095
2096    @property
2097    def named_selects(self):
2098        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2099
2100    def with_(
2101        self,
2102        alias: ExpOrStr,
2103        as_: ExpOrStr,
2104        recursive: t.Optional[bool] = None,
2105        append: bool = True,
2106        dialect: DialectType = None,
2107        copy: bool = True,
2108        **opts,
2109    ) -> Subqueryable:
2110        """
2111        Append to or set the common table expressions.
2112
2113        Example:
2114            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2115            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2116
2117        Args:
2118            alias: the SQL code string to parse as the table name.
2119                If an `Expression` instance is passed, this is used as-is.
2120            as_: the SQL code string to parse as the table expression.
2121                If an `Expression` instance is passed, it will be used as-is.
2122            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2123            append: if `True`, add to any existing expressions.
2124                Otherwise, this resets the expressions.
2125            dialect: the dialect used to parse the input expression.
2126            copy: if `False`, modify this expression instance in-place.
2127            opts: other options to use to parse the input expressions.
2128
2129        Returns:
2130            The modified expression.
2131        """
2132        return _apply_cte_builder(
2133            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2134        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
2060    def subquery(self, alias=None, copy=True) -> Subquery:
2061        """
2062        Convert this expression to an aliased expression that can be used as a Subquery.
2063
2064        Example:
2065            >>> subquery = Select().select("x").from_("tbl").subquery()
2066            >>> Select().select("x").from_(subquery).sql()
2067            'SELECT x FROM (SELECT x FROM tbl)'
2068
2069        Args:
2070            alias (str | Identifier): an optional alias for the subquery
2071            copy (bool): if `False`, modify this expression instance in-place.
2072
2073        Returns:
2074            Alias: the subquery
2075        """
2076        instance = _maybe_copy(self, copy)
2077        if not isinstance(alias, Expression):
2078            alias = TableAlias(this=to_identifier(alias)) if alias else None
2079
2080        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, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2082    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2083        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:
2100    def with_(
2101        self,
2102        alias: ExpOrStr,
2103        as_: ExpOrStr,
2104        recursive: t.Optional[bool] = None,
2105        append: bool = True,
2106        dialect: DialectType = None,
2107        copy: bool = True,
2108        **opts,
2109    ) -> Subqueryable:
2110        """
2111        Append to or set the common table expressions.
2112
2113        Example:
2114            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2115            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2116
2117        Args:
2118            alias: the SQL code string to parse as the table name.
2119                If an `Expression` instance is passed, this is used as-is.
2120            as_: the SQL code string to parse as the table expression.
2121                If an `Expression` instance is passed, it will be used as-is.
2122            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2123            append: if `True`, add to any existing expressions.
2124                Otherwise, this resets the expressions.
2125            dialect: the dialect used to parse the input expression.
2126            copy: if `False`, modify this expression instance in-place.
2127            opts: other options to use to parse the input expressions.
2128
2129        Returns:
2130            The modified expression.
2131        """
2132        return _apply_cte_builder(
2133            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2134        )

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):
2160class Table(Expression):
2161    arg_types = {
2162        "this": True,
2163        "alias": False,
2164        "db": False,
2165        "catalog": False,
2166        "laterals": False,
2167        "joins": False,
2168        "pivots": False,
2169        "hints": False,
2170        "system_time": False,
2171    }
2172
2173    @property
2174    def db(self) -> str:
2175        return self.text("db")
2176
2177    @property
2178    def catalog(self) -> str:
2179        return self.text("catalog")
2180
2181    @property
2182    def parts(self) -> t.List[Identifier]:
2183        """Return the parts of a column in order catalog, db, table."""
2184        return [
2185            t.cast(Identifier, self.args[part])
2186            for part in ("catalog", "db", "this")
2187            if self.args.get(part)
2188        ]

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

class SystemTime(Expression):
2192class SystemTime(Expression):
2193    arg_types = {
2194        "this": False,
2195        "expression": False,
2196        "kind": True,
2197    }
class Union(Subqueryable):
2200class Union(Subqueryable):
2201    arg_types = {
2202        "with": False,
2203        "this": True,
2204        "expression": True,
2205        "distinct": False,
2206        **QUERY_MODIFIERS,
2207    }
2208
2209    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2210        """
2211        Set the LIMIT expression.
2212
2213        Example:
2214            >>> select("1").union(select("1")).limit(1).sql()
2215            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2216
2217        Args:
2218            expression (str | int | Expression): the SQL code string to parse.
2219                This can also be an integer.
2220                If a `Limit` instance is passed, this is used as-is.
2221                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2222            dialect (str): the dialect used to parse the input expression.
2223            copy (bool): if `False`, modify this expression instance in-place.
2224            opts (kwargs): other options to use to parse the input expressions.
2225
2226        Returns:
2227            Select: The limited subqueryable.
2228        """
2229        return (
2230            select("*")
2231            .from_(self.subquery(alias="_l_0", copy=copy))
2232            .limit(expression, dialect=dialect, copy=False, **opts)
2233        )
2234
2235    def select(
2236        self,
2237        *expressions: ExpOrStr,
2238        append: bool = True,
2239        dialect: DialectType = None,
2240        copy: bool = True,
2241        **opts,
2242    ) -> Union:
2243        """Append to or set the SELECT of the union recursively.
2244
2245        Example:
2246            >>> from sqlglot import parse_one
2247            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2248            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2249
2250        Args:
2251            *expressions: the SQL code strings to parse.
2252                If an `Expression` instance is passed, it will be used as-is.
2253            append: if `True`, add to any existing expressions.
2254                Otherwise, this resets the expressions.
2255            dialect: the dialect used to parse the input expressions.
2256            copy: if `False`, modify this expression instance in-place.
2257            opts: other options to use to parse the input expressions.
2258
2259        Returns:
2260            Union: the modified expression.
2261        """
2262        this = self.copy() if copy else self
2263        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2264        this.expression.unnest().select(
2265            *expressions, append=append, dialect=dialect, copy=False, **opts
2266        )
2267        return this
2268
2269    @property
2270    def named_selects(self):
2271        return self.this.unnest().named_selects
2272
2273    @property
2274    def is_star(self) -> bool:
2275        return self.this.is_star or self.expression.is_star
2276
2277    @property
2278    def selects(self):
2279        return self.this.unnest().selects
2280
2281    @property
2282    def left(self):
2283        return self.this
2284
2285    @property
2286    def right(self):
2287        return self.expression
def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2209    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2210        """
2211        Set the LIMIT expression.
2212
2213        Example:
2214            >>> select("1").union(select("1")).limit(1).sql()
2215            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2216
2217        Args:
2218            expression (str | int | Expression): the SQL code string to parse.
2219                This can also be an integer.
2220                If a `Limit` instance is passed, this is used as-is.
2221                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2222            dialect (str): the dialect used to parse the input expression.
2223            copy (bool): if `False`, modify this expression instance in-place.
2224            opts (kwargs): other options to use to parse the input expressions.
2225
2226        Returns:
2227            Select: The limited subqueryable.
2228        """
2229        return (
2230            select("*")
2231            .from_(self.subquery(alias="_l_0", copy=copy))
2232            .limit(expression, dialect=dialect, copy=False, **opts)
2233        )

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 (str | int | 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 (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
2235    def select(
2236        self,
2237        *expressions: ExpOrStr,
2238        append: bool = True,
2239        dialect: DialectType = None,
2240        copy: bool = True,
2241        **opts,
2242    ) -> Union:
2243        """Append to or set the SELECT of the union recursively.
2244
2245        Example:
2246            >>> from sqlglot import parse_one
2247            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2248            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2249
2250        Args:
2251            *expressions: the SQL code strings to parse.
2252                If an `Expression` instance is passed, it will be used as-is.
2253            append: if `True`, add to any existing expressions.
2254                Otherwise, this resets the expressions.
2255            dialect: the dialect used to parse the input expressions.
2256            copy: if `False`, modify this expression instance in-place.
2257            opts: other options to use to parse the input expressions.
2258
2259        Returns:
2260            Union: the modified expression.
2261        """
2262        this = self.copy() if copy else self
2263        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2264        this.expression.unnest().select(
2265            *expressions, append=append, dialect=dialect, copy=False, **opts
2266        )
2267        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):
2290class Except(Union):
2291    pass
class Intersect(Union):
2294class Intersect(Union):
2295    pass
class Unnest(UDTF):
2298class Unnest(UDTF):
2299    arg_types = {
2300        "expressions": True,
2301        "ordinality": False,
2302        "alias": False,
2303        "offset": False,
2304    }
class Update(Expression):
2307class Update(Expression):
2308    arg_types = {
2309        "with": False,
2310        "this": False,
2311        "expressions": True,
2312        "from": False,
2313        "where": False,
2314        "returning": False,
2315    }
class Values(UDTF):
2318class Values(UDTF):
2319    arg_types = {
2320        "expressions": True,
2321        "ordinality": False,
2322        "alias": False,
2323    }
class Var(Expression):
2326class Var(Expression):
2327    pass
class Schema(Expression):
2330class Schema(Expression):
2331    arg_types = {"this": False, "expressions": False}
class Lock(Expression):
2336class Lock(Expression):
2337    arg_types = {"update": True}
class Select(Subqueryable):
2340class Select(Subqueryable):
2341    arg_types = {
2342        "with": False,
2343        "kind": False,
2344        "expressions": False,
2345        "hint": False,
2346        "distinct": False,
2347        "struct": False,  # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax#return_query_results_as_a_value_table
2348        "value": False,
2349        "into": False,
2350        "from": False,
2351        **QUERY_MODIFIERS,
2352    }
2353
2354    def from_(
2355        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2356    ) -> Select:
2357        """
2358        Set the FROM expression.
2359
2360        Example:
2361            >>> Select().from_("tbl").select("x").sql()
2362            'SELECT x FROM tbl'
2363
2364        Args:
2365            expression : the SQL code strings to parse.
2366                If a `From` instance is passed, this is used as-is.
2367                If another `Expression` instance is passed, it will be wrapped in a `From`.
2368            dialect: the dialect used to parse the input expression.
2369            copy: if `False`, modify this expression instance in-place.
2370            opts: other options to use to parse the input expressions.
2371
2372        Returns:
2373            Select: the modified expression.
2374        """
2375        return _apply_builder(
2376            expression=expression,
2377            instance=self,
2378            arg="from",
2379            into=From,
2380            prefix="FROM",
2381            dialect=dialect,
2382            copy=copy,
2383            **opts,
2384        )
2385
2386    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2387        """
2388        Set the GROUP BY expression.
2389
2390        Example:
2391            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2392            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2393
2394        Args:
2395            *expressions (str | Expression): the SQL code strings to parse.
2396                If a `Group` instance is passed, this is used as-is.
2397                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2398                If nothing is passed in then a group by is not applied to the expression
2399            append (bool): if `True`, add to any existing expressions.
2400                Otherwise, this flattens all the `Group` expression into a single expression.
2401            dialect (str): the dialect used to parse the input expression.
2402            copy (bool): if `False`, modify this expression instance in-place.
2403            opts (kwargs): other options to use to parse the input expressions.
2404
2405        Returns:
2406            Select: the modified expression.
2407        """
2408        if not expressions:
2409            return self if not copy else self.copy()
2410        return _apply_child_list_builder(
2411            *expressions,
2412            instance=self,
2413            arg="group",
2414            append=append,
2415            copy=copy,
2416            prefix="GROUP BY",
2417            into=Group,
2418            dialect=dialect,
2419            **opts,
2420        )
2421
2422    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2423        """
2424        Set the ORDER BY expression.
2425
2426        Example:
2427            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2428            'SELECT x FROM tbl ORDER BY x DESC'
2429
2430        Args:
2431            *expressions (str | Expression): the SQL code strings to parse.
2432                If a `Group` instance is passed, this is used as-is.
2433                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2434            append (bool): if `True`, add to any existing expressions.
2435                Otherwise, this flattens all the `Order` expression into a single expression.
2436            dialect (str): the dialect used to parse the input expression.
2437            copy (bool): if `False`, modify this expression instance in-place.
2438            opts (kwargs): other options to use to parse the input expressions.
2439
2440        Returns:
2441            Select: the modified expression.
2442        """
2443        return _apply_child_list_builder(
2444            *expressions,
2445            instance=self,
2446            arg="order",
2447            append=append,
2448            copy=copy,
2449            prefix="ORDER BY",
2450            into=Order,
2451            dialect=dialect,
2452            **opts,
2453        )
2454
2455    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2456        """
2457        Set the SORT BY expression.
2458
2459        Example:
2460            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2461            'SELECT x FROM tbl SORT BY x DESC'
2462
2463        Args:
2464            *expressions (str | Expression): the SQL code strings to parse.
2465                If a `Group` instance is passed, this is used as-is.
2466                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2467            append (bool): if `True`, add to any existing expressions.
2468                Otherwise, this flattens all the `Order` expression into a single expression.
2469            dialect (str): the dialect used to parse the input expression.
2470            copy (bool): if `False`, modify this expression instance in-place.
2471            opts (kwargs): other options to use to parse the input expressions.
2472
2473        Returns:
2474            Select: the modified expression.
2475        """
2476        return _apply_child_list_builder(
2477            *expressions,
2478            instance=self,
2479            arg="sort",
2480            append=append,
2481            copy=copy,
2482            prefix="SORT BY",
2483            into=Sort,
2484            dialect=dialect,
2485            **opts,
2486        )
2487
2488    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2489        """
2490        Set the CLUSTER BY expression.
2491
2492        Example:
2493            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2494            'SELECT x FROM tbl CLUSTER BY x DESC'
2495
2496        Args:
2497            *expressions (str | Expression): the SQL code strings to parse.
2498                If a `Group` instance is passed, this is used as-is.
2499                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2500            append (bool): if `True`, add to any existing expressions.
2501                Otherwise, this flattens all the `Order` expression into a single expression.
2502            dialect (str): the dialect used to parse the input expression.
2503            copy (bool): if `False`, modify this expression instance in-place.
2504            opts (kwargs): other options to use to parse the input expressions.
2505
2506        Returns:
2507            Select: the modified expression.
2508        """
2509        return _apply_child_list_builder(
2510            *expressions,
2511            instance=self,
2512            arg="cluster",
2513            append=append,
2514            copy=copy,
2515            prefix="CLUSTER BY",
2516            into=Cluster,
2517            dialect=dialect,
2518            **opts,
2519        )
2520
2521    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2522        """
2523        Set the LIMIT expression.
2524
2525        Example:
2526            >>> Select().from_("tbl").select("x").limit(10).sql()
2527            'SELECT x FROM tbl LIMIT 10'
2528
2529        Args:
2530            expression (str | int | Expression): the SQL code string to parse.
2531                This can also be an integer.
2532                If a `Limit` instance is passed, this is used as-is.
2533                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2534            dialect (str): the dialect used to parse the input expression.
2535            copy (bool): if `False`, modify this expression instance in-place.
2536            opts (kwargs): other options to use to parse the input expressions.
2537
2538        Returns:
2539            Select: the modified expression.
2540        """
2541        return _apply_builder(
2542            expression=expression,
2543            instance=self,
2544            arg="limit",
2545            into=Limit,
2546            prefix="LIMIT",
2547            dialect=dialect,
2548            copy=copy,
2549            **opts,
2550        )
2551
2552    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2553        """
2554        Set the OFFSET expression.
2555
2556        Example:
2557            >>> Select().from_("tbl").select("x").offset(10).sql()
2558            'SELECT x FROM tbl OFFSET 10'
2559
2560        Args:
2561            expression (str | int | Expression): the SQL code string to parse.
2562                This can also be an integer.
2563                If a `Offset` instance is passed, this is used as-is.
2564                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2565            dialect (str): the dialect used to parse the input expression.
2566            copy (bool): if `False`, modify this expression instance in-place.
2567            opts (kwargs): other options to use to parse the input expressions.
2568
2569        Returns:
2570            Select: the modified expression.
2571        """
2572        return _apply_builder(
2573            expression=expression,
2574            instance=self,
2575            arg="offset",
2576            into=Offset,
2577            prefix="OFFSET",
2578            dialect=dialect,
2579            copy=copy,
2580            **opts,
2581        )
2582
2583    def select(
2584        self,
2585        *expressions: ExpOrStr,
2586        append: bool = True,
2587        dialect: DialectType = None,
2588        copy: bool = True,
2589        **opts,
2590    ) -> Select:
2591        """
2592        Append to or set the SELECT expressions.
2593
2594        Example:
2595            >>> Select().select("x", "y").sql()
2596            'SELECT x, y'
2597
2598        Args:
2599            *expressions: the SQL code strings to parse.
2600                If an `Expression` instance is passed, it will be used as-is.
2601            append: if `True`, add to any existing expressions.
2602                Otherwise, this resets the expressions.
2603            dialect: the dialect used to parse the input expressions.
2604            copy: if `False`, modify this expression instance in-place.
2605            opts: other options to use to parse the input expressions.
2606
2607        Returns:
2608            Select: the modified expression.
2609        """
2610        return _apply_list_builder(
2611            *expressions,
2612            instance=self,
2613            arg="expressions",
2614            append=append,
2615            dialect=dialect,
2616            copy=copy,
2617            **opts,
2618        )
2619
2620    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2621        """
2622        Append to or set the LATERAL expressions.
2623
2624        Example:
2625            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2626            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2627
2628        Args:
2629            *expressions (str | Expression): the SQL code strings to parse.
2630                If an `Expression` instance is passed, it will be used as-is.
2631            append (bool): if `True`, add to any existing expressions.
2632                Otherwise, this resets the expressions.
2633            dialect (str): the dialect used to parse the input expressions.
2634            copy (bool): if `False`, modify this expression instance in-place.
2635            opts (kwargs): other options to use to parse the input expressions.
2636
2637        Returns:
2638            Select: the modified expression.
2639        """
2640        return _apply_list_builder(
2641            *expressions,
2642            instance=self,
2643            arg="laterals",
2644            append=append,
2645            into=Lateral,
2646            prefix="LATERAL VIEW",
2647            dialect=dialect,
2648            copy=copy,
2649            **opts,
2650        )
2651
2652    def join(
2653        self,
2654        expression,
2655        on=None,
2656        using=None,
2657        append=True,
2658        join_type=None,
2659        join_alias=None,
2660        dialect=None,
2661        copy=True,
2662        **opts,
2663    ) -> Select:
2664        """
2665        Append to or set the JOIN expressions.
2666
2667        Example:
2668            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2669            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2670
2671            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2672            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2673
2674            Use `join_type` to change the type of join:
2675
2676            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2677            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2678
2679        Args:
2680            expression (str | Expression): the SQL code string to parse.
2681                If an `Expression` instance is passed, it will be used as-is.
2682            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2683                If an `Expression` instance is passed, it will be used as-is.
2684            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2685                If an `Expression` instance is passed, it will be used as-is.
2686            append (bool): if `True`, add to any existing expressions.
2687                Otherwise, this resets the expressions.
2688            join_type (str): If set, alter the parsed join type
2689            dialect (str): the dialect used to parse the input expressions.
2690            copy (bool): if `False`, modify this expression instance in-place.
2691            opts (kwargs): other options to use to parse the input expressions.
2692
2693        Returns:
2694            Select: the modified expression.
2695        """
2696        parse_args = {"dialect": dialect, **opts}
2697
2698        try:
2699            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2700        except ParseError:
2701            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2702
2703        join = expression if isinstance(expression, Join) else Join(this=expression)
2704
2705        if isinstance(join.this, Select):
2706            join.this.replace(join.this.subquery())
2707
2708        if join_type:
2709            natural: t.Optional[Token]
2710            side: t.Optional[Token]
2711            kind: t.Optional[Token]
2712
2713            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2714
2715            if natural:
2716                join.set("natural", True)
2717            if side:
2718                join.set("side", side.text)
2719            if kind:
2720                join.set("kind", kind.text)
2721
2722        if on:
2723            on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts)
2724            join.set("on", on)
2725
2726        if using:
2727            join = _apply_list_builder(
2728                *ensure_collection(using),
2729                instance=join,
2730                arg="using",
2731                append=append,
2732                copy=copy,
2733                **opts,
2734            )
2735
2736        if join_alias:
2737            join.set("this", alias_(join.this, join_alias, table=True))
2738        return _apply_list_builder(
2739            join,
2740            instance=self,
2741            arg="joins",
2742            append=append,
2743            copy=copy,
2744            **opts,
2745        )
2746
2747    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2748        """
2749        Append to or set the WHERE expressions.
2750
2751        Example:
2752            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2753            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2754
2755        Args:
2756            *expressions (str | Expression): the SQL code strings to parse.
2757                If an `Expression` instance is passed, it will be used as-is.
2758                Multiple expressions are combined with an AND operator.
2759            append (bool): if `True`, AND the new expressions to any existing expression.
2760                Otherwise, this resets the expression.
2761            dialect (str): the dialect used to parse the input expressions.
2762            copy (bool): if `False`, modify this expression instance in-place.
2763            opts (kwargs): other options to use to parse the input expressions.
2764
2765        Returns:
2766            Select: the modified expression.
2767        """
2768        return _apply_conjunction_builder(
2769            *expressions,
2770            instance=self,
2771            arg="where",
2772            append=append,
2773            into=Where,
2774            dialect=dialect,
2775            copy=copy,
2776            **opts,
2777        )
2778
2779    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2780        """
2781        Append to or set the HAVING expressions.
2782
2783        Example:
2784            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2785            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2786
2787        Args:
2788            *expressions (str | Expression): the SQL code strings to parse.
2789                If an `Expression` instance is passed, it will be used as-is.
2790                Multiple expressions are combined with an AND operator.
2791            append (bool): if `True`, AND the new expressions to any existing expression.
2792                Otherwise, this resets the expression.
2793            dialect (str): the dialect used to parse the input expressions.
2794            copy (bool): if `False`, modify this expression instance in-place.
2795            opts (kwargs): other options to use to parse the input expressions.
2796
2797        Returns:
2798            Select: the modified expression.
2799        """
2800        return _apply_conjunction_builder(
2801            *expressions,
2802            instance=self,
2803            arg="having",
2804            append=append,
2805            into=Having,
2806            dialect=dialect,
2807            copy=copy,
2808            **opts,
2809        )
2810
2811    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2812        return _apply_list_builder(
2813            *expressions,
2814            instance=self,
2815            arg="windows",
2816            append=append,
2817            into=Window,
2818            dialect=dialect,
2819            copy=copy,
2820            **opts,
2821        )
2822
2823    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2824        return _apply_conjunction_builder(
2825            *expressions,
2826            instance=self,
2827            arg="qualify",
2828            append=append,
2829            into=Qualify,
2830            dialect=dialect,
2831            copy=copy,
2832            **opts,
2833        )
2834
2835    def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select:
2836        """
2837        Set the OFFSET expression.
2838
2839        Example:
2840            >>> Select().from_("tbl").select("x").distinct().sql()
2841            'SELECT DISTINCT x FROM tbl'
2842
2843        Args:
2844            ons: the expressions to distinct on
2845            distinct: whether the Select should be distinct
2846            copy: if `False`, modify this expression instance in-place.
2847
2848        Returns:
2849            Select: the modified expression.
2850        """
2851        instance = _maybe_copy(self, copy)
2852        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None
2853        instance.set("distinct", Distinct(on=on) if distinct else None)
2854        return instance
2855
2856    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2857        """
2858        Convert this expression to a CREATE TABLE AS statement.
2859
2860        Example:
2861            >>> Select().select("*").from_("tbl").ctas("x").sql()
2862            'CREATE TABLE x AS SELECT * FROM tbl'
2863
2864        Args:
2865            table (str | Expression): the SQL code string to parse as the table name.
2866                If another `Expression` instance is passed, it will be used as-is.
2867            properties (dict): an optional mapping of table properties
2868            dialect (str): the dialect used to parse the input table.
2869            copy (bool): if `False`, modify this expression instance in-place.
2870            opts (kwargs): other options to use to parse the input table.
2871
2872        Returns:
2873            Create: the CREATE TABLE AS expression
2874        """
2875        instance = _maybe_copy(self, copy)
2876        table_expression = maybe_parse(
2877            table,
2878            into=Table,
2879            dialect=dialect,
2880            **opts,
2881        )
2882        properties_expression = None
2883        if properties:
2884            properties_expression = Properties.from_dict(properties)
2885
2886        return Create(
2887            this=table_expression,
2888            kind="table",
2889            expression=instance,
2890            properties=properties_expression,
2891        )
2892
2893    def lock(self, update: bool = True, copy: bool = True) -> Select:
2894        """
2895        Set the locking read mode for this expression.
2896
2897        Examples:
2898            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2899            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2900
2901            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2902            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2903
2904        Args:
2905            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2906            copy: if `False`, modify this expression instance in-place.
2907
2908        Returns:
2909            The modified expression.
2910        """
2911
2912        inst = _maybe_copy(self, copy)
2913        inst.set("lock", Lock(update=update))
2914
2915        return inst
2916
2917    @property
2918    def named_selects(self) -> t.List[str]:
2919        return [e.output_name for e in self.expressions if e.alias_or_name]
2920
2921    @property
2922    def is_star(self) -> bool:
2923        return any(expression.is_star for expression in self.expressions)
2924
2925    @property
2926    def selects(self) -> t.List[Expression]:
2927        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:
2354    def from_(
2355        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2356    ) -> Select:
2357        """
2358        Set the FROM expression.
2359
2360        Example:
2361            >>> Select().from_("tbl").select("x").sql()
2362            'SELECT x FROM tbl'
2363
2364        Args:
2365            expression : the SQL code strings to parse.
2366                If a `From` instance is passed, this is used as-is.
2367                If another `Expression` instance is passed, it will be wrapped in a `From`.
2368            dialect: the dialect used to parse the input expression.
2369            copy: if `False`, modify this expression instance in-place.
2370            opts: other options to use to parse the input expressions.
2371
2372        Returns:
2373            Select: the modified expression.
2374        """
2375        return _apply_builder(
2376            expression=expression,
2377            instance=self,
2378            arg="from",
2379            into=From,
2380            prefix="FROM",
2381            dialect=dialect,
2382            copy=copy,
2383            **opts,
2384        )

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:

Select: the modified expression.

def group_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2386    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2387        """
2388        Set the GROUP BY expression.
2389
2390        Example:
2391            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2392            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2393
2394        Args:
2395            *expressions (str | Expression): the SQL code strings to parse.
2396                If a `Group` instance is passed, this is used as-is.
2397                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2398                If nothing is passed in then a group by is not applied to the expression
2399            append (bool): if `True`, add to any existing expressions.
2400                Otherwise, this flattens all the `Group` expression into a single expression.
2401            dialect (str): the dialect used to parse the input expression.
2402            copy (bool): if `False`, modify this expression instance in-place.
2403            opts (kwargs): other options to use to parse the input expressions.
2404
2405        Returns:
2406            Select: the modified expression.
2407        """
2408        if not expressions:
2409            return self if not copy else self.copy()
2410        return _apply_child_list_builder(
2411            *expressions,
2412            instance=self,
2413            arg="group",
2414            append=append,
2415            copy=copy,
2416            prefix="GROUP BY",
2417            into=Group,
2418            dialect=dialect,
2419            **opts,
2420        )

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 (str | Expression): 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 (bool): if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def order_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2422    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2423        """
2424        Set the ORDER BY expression.
2425
2426        Example:
2427            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2428            'SELECT x FROM tbl ORDER BY x DESC'
2429
2430        Args:
2431            *expressions (str | Expression): the SQL code strings to parse.
2432                If a `Group` instance is passed, this is used as-is.
2433                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2434            append (bool): if `True`, add to any existing expressions.
2435                Otherwise, this flattens all the `Order` expression into a single expression.
2436            dialect (str): the dialect used to parse the input expression.
2437            copy (bool): if `False`, modify this expression instance in-place.
2438            opts (kwargs): other options to use to parse the input expressions.
2439
2440        Returns:
2441            Select: the modified expression.
2442        """
2443        return _apply_child_list_builder(
2444            *expressions,
2445            instance=self,
2446            arg="order",
2447            append=append,
2448            copy=copy,
2449            prefix="ORDER BY",
2450            into=Order,
2451            dialect=dialect,
2452            **opts,
2453        )

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 (str | Expression): 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 (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def sort_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2455    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2456        """
2457        Set the SORT BY expression.
2458
2459        Example:
2460            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2461            'SELECT x FROM tbl SORT BY x DESC'
2462
2463        Args:
2464            *expressions (str | Expression): the SQL code strings to parse.
2465                If a `Group` instance is passed, this is used as-is.
2466                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2467            append (bool): if `True`, add to any existing expressions.
2468                Otherwise, this flattens all the `Order` expression into a single expression.
2469            dialect (str): the dialect used to parse the input expression.
2470            copy (bool): if `False`, modify this expression instance in-place.
2471            opts (kwargs): other options to use to parse the input expressions.
2472
2473        Returns:
2474            Select: the modified expression.
2475        """
2476        return _apply_child_list_builder(
2477            *expressions,
2478            instance=self,
2479            arg="sort",
2480            append=append,
2481            copy=copy,
2482            prefix="SORT BY",
2483            into=Sort,
2484            dialect=dialect,
2485            **opts,
2486        )

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 (str | Expression): 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 (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def cluster_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2488    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2489        """
2490        Set the CLUSTER BY expression.
2491
2492        Example:
2493            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2494            'SELECT x FROM tbl CLUSTER BY x DESC'
2495
2496        Args:
2497            *expressions (str | Expression): the SQL code strings to parse.
2498                If a `Group` instance is passed, this is used as-is.
2499                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2500            append (bool): if `True`, add to any existing expressions.
2501                Otherwise, this flattens all the `Order` expression into a single expression.
2502            dialect (str): the dialect used to parse the input expression.
2503            copy (bool): if `False`, modify this expression instance in-place.
2504            opts (kwargs): other options to use to parse the input expressions.
2505
2506        Returns:
2507            Select: the modified expression.
2508        """
2509        return _apply_child_list_builder(
2510            *expressions,
2511            instance=self,
2512            arg="cluster",
2513            append=append,
2514            copy=copy,
2515            prefix="CLUSTER BY",
2516            into=Cluster,
2517            dialect=dialect,
2518            **opts,
2519        )

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 (str | Expression): 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 (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2521    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2522        """
2523        Set the LIMIT expression.
2524
2525        Example:
2526            >>> Select().from_("tbl").select("x").limit(10).sql()
2527            'SELECT x FROM tbl LIMIT 10'
2528
2529        Args:
2530            expression (str | int | Expression): the SQL code string to parse.
2531                This can also be an integer.
2532                If a `Limit` instance is passed, this is used as-is.
2533                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2534            dialect (str): the dialect used to parse the input expression.
2535            copy (bool): if `False`, modify this expression instance in-place.
2536            opts (kwargs): other options to use to parse the input expressions.
2537
2538        Returns:
2539            Select: the modified expression.
2540        """
2541        return _apply_builder(
2542            expression=expression,
2543            instance=self,
2544            arg="limit",
2545            into=Limit,
2546            prefix="LIMIT",
2547            dialect=dialect,
2548            copy=copy,
2549            **opts,
2550        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression (str | int | 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 (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2552    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2553        """
2554        Set the OFFSET expression.
2555
2556        Example:
2557            >>> Select().from_("tbl").select("x").offset(10).sql()
2558            'SELECT x FROM tbl OFFSET 10'
2559
2560        Args:
2561            expression (str | int | Expression): the SQL code string to parse.
2562                This can also be an integer.
2563                If a `Offset` instance is passed, this is used as-is.
2564                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2565            dialect (str): the dialect used to parse the input expression.
2566            copy (bool): if `False`, modify this expression instance in-place.
2567            opts (kwargs): other options to use to parse the input expressions.
2568
2569        Returns:
2570            Select: the modified expression.
2571        """
2572        return _apply_builder(
2573            expression=expression,
2574            instance=self,
2575            arg="offset",
2576            into=Offset,
2577            prefix="OFFSET",
2578            dialect=dialect,
2579            copy=copy,
2580            **opts,
2581        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression (str | int | 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 (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2583    def select(
2584        self,
2585        *expressions: ExpOrStr,
2586        append: bool = True,
2587        dialect: DialectType = None,
2588        copy: bool = True,
2589        **opts,
2590    ) -> Select:
2591        """
2592        Append to or set the SELECT expressions.
2593
2594        Example:
2595            >>> Select().select("x", "y").sql()
2596            'SELECT x, y'
2597
2598        Args:
2599            *expressions: the SQL code strings to parse.
2600                If an `Expression` instance is passed, it will be used as-is.
2601            append: if `True`, add to any existing expressions.
2602                Otherwise, this resets the expressions.
2603            dialect: the dialect used to parse the input expressions.
2604            copy: if `False`, modify this expression instance in-place.
2605            opts: other options to use to parse the input expressions.
2606
2607        Returns:
2608            Select: the modified expression.
2609        """
2610        return _apply_list_builder(
2611            *expressions,
2612            instance=self,
2613            arg="expressions",
2614            append=append,
2615            dialect=dialect,
2616            copy=copy,
2617            **opts,
2618        )

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:

Select: the modified expression.

def lateral( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2620    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2621        """
2622        Append to or set the LATERAL expressions.
2623
2624        Example:
2625            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2626            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2627
2628        Args:
2629            *expressions (str | Expression): the SQL code strings to parse.
2630                If an `Expression` instance is passed, it will be used as-is.
2631            append (bool): if `True`, add to any existing expressions.
2632                Otherwise, this resets the expressions.
2633            dialect (str): the dialect used to parse the input expressions.
2634            copy (bool): if `False`, modify this expression instance in-place.
2635            opts (kwargs): other options to use to parse the input expressions.
2636
2637        Returns:
2638            Select: the modified expression.
2639        """
2640        return _apply_list_builder(
2641            *expressions,
2642            instance=self,
2643            arg="laterals",
2644            append=append,
2645            into=Lateral,
2646            prefix="LATERAL VIEW",
2647            dialect=dialect,
2648            copy=copy,
2649            **opts,
2650        )

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 (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def join( self, expression, on=None, using=None, append=True, join_type=None, join_alias=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2652    def join(
2653        self,
2654        expression,
2655        on=None,
2656        using=None,
2657        append=True,
2658        join_type=None,
2659        join_alias=None,
2660        dialect=None,
2661        copy=True,
2662        **opts,
2663    ) -> Select:
2664        """
2665        Append to or set the JOIN expressions.
2666
2667        Example:
2668            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2669            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2670
2671            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2672            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2673
2674            Use `join_type` to change the type of join:
2675
2676            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2677            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2678
2679        Args:
2680            expression (str | Expression): the SQL code string to parse.
2681                If an `Expression` instance is passed, it will be used as-is.
2682            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2683                If an `Expression` instance is passed, it will be used as-is.
2684            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2685                If an `Expression` instance is passed, it will be used as-is.
2686            append (bool): if `True`, add to any existing expressions.
2687                Otherwise, this resets the expressions.
2688            join_type (str): If set, alter the parsed join type
2689            dialect (str): the dialect used to parse the input expressions.
2690            copy (bool): if `False`, modify this expression instance in-place.
2691            opts (kwargs): other options to use to parse the input expressions.
2692
2693        Returns:
2694            Select: the modified expression.
2695        """
2696        parse_args = {"dialect": dialect, **opts}
2697
2698        try:
2699            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2700        except ParseError:
2701            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2702
2703        join = expression if isinstance(expression, Join) else Join(this=expression)
2704
2705        if isinstance(join.this, Select):
2706            join.this.replace(join.this.subquery())
2707
2708        if join_type:
2709            natural: t.Optional[Token]
2710            side: t.Optional[Token]
2711            kind: t.Optional[Token]
2712
2713            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2714
2715            if natural:
2716                join.set("natural", True)
2717            if side:
2718                join.set("side", side.text)
2719            if kind:
2720                join.set("kind", kind.text)
2721
2722        if on:
2723            on = and_(*ensure_collection(on), dialect=dialect, copy=copy, **opts)
2724            join.set("on", on)
2725
2726        if using:
2727            join = _apply_list_builder(
2728                *ensure_collection(using),
2729                instance=join,
2730                arg="using",
2731                append=append,
2732                copy=copy,
2733                **opts,
2734            )
2735
2736        if join_alias:
2737            join.set("this", alias_(join.this, join_alias, table=True))
2738        return _apply_list_builder(
2739            join,
2740            instance=self,
2741            arg="joins",
2742            append=append,
2743            copy=copy,
2744            **opts,
2745        )

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 (str | Expression): the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on (str | Expression): optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using (str | Expression): optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type (str): If set, alter the parsed join type
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2747    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2748        """
2749        Append to or set the WHERE expressions.
2750
2751        Example:
2752            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2753            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2754
2755        Args:
2756            *expressions (str | Expression): the SQL code strings to parse.
2757                If an `Expression` instance is passed, it will be used as-is.
2758                Multiple expressions are combined with an AND operator.
2759            append (bool): if `True`, AND the new expressions to any existing expression.
2760                Otherwise, this resets the expression.
2761            dialect (str): the dialect used to parse the input expressions.
2762            copy (bool): if `False`, modify this expression instance in-place.
2763            opts (kwargs): other options to use to parse the input expressions.
2764
2765        Returns:
2766            Select: the modified expression.
2767        """
2768        return _apply_conjunction_builder(
2769            *expressions,
2770            instance=self,
2771            arg="where",
2772            append=append,
2773            into=Where,
2774            dialect=dialect,
2775            copy=copy,
2776            **opts,
2777        )

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 (str | Expression): 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 (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2779    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2780        """
2781        Append to or set the HAVING expressions.
2782
2783        Example:
2784            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2785            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2786
2787        Args:
2788            *expressions (str | Expression): the SQL code strings to parse.
2789                If an `Expression` instance is passed, it will be used as-is.
2790                Multiple expressions are combined with an AND operator.
2791            append (bool): if `True`, AND the new expressions to any existing expression.
2792                Otherwise, this resets the expression.
2793            dialect (str): the dialect used to parse the input expressions.
2794            copy (bool): if `False`, modify this expression instance in-place.
2795            opts (kwargs): other options to use to parse the input expressions.
2796
2797        Returns:
2798            Select: the modified expression.
2799        """
2800        return _apply_conjunction_builder(
2801            *expressions,
2802            instance=self,
2803            arg="having",
2804            append=append,
2805            into=Having,
2806            dialect=dialect,
2807            copy=copy,
2808            **opts,
2809        )

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 (str | Expression): 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 (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def window( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2811    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2812        return _apply_list_builder(
2813            *expressions,
2814            instance=self,
2815            arg="windows",
2816            append=append,
2817            into=Window,
2818            dialect=dialect,
2819            copy=copy,
2820            **opts,
2821        )
def qualify( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2823    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2824        return _apply_conjunction_builder(
2825            *expressions,
2826            instance=self,
2827            arg="qualify",
2828            append=append,
2829            into=Qualify,
2830            dialect=dialect,
2831            copy=copy,
2832            **opts,
2833        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2835    def distinct(self, *ons: ExpOrStr, distinct: bool = True, copy: bool = True) -> Select:
2836        """
2837        Set the OFFSET expression.
2838
2839        Example:
2840            >>> Select().from_("tbl").select("x").distinct().sql()
2841            'SELECT DISTINCT x FROM tbl'
2842
2843        Args:
2844            ons: the expressions to distinct on
2845            distinct: whether the Select should be distinct
2846            copy: if `False`, modify this expression instance in-place.
2847
2848        Returns:
2849            Select: the modified expression.
2850        """
2851        instance = _maybe_copy(self, copy)
2852        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons]) if ons else None
2853        instance.set("distinct", Distinct(on=on) if distinct else None)
2854        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, properties=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Create:
2856    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2857        """
2858        Convert this expression to a CREATE TABLE AS statement.
2859
2860        Example:
2861            >>> Select().select("*").from_("tbl").ctas("x").sql()
2862            'CREATE TABLE x AS SELECT * FROM tbl'
2863
2864        Args:
2865            table (str | Expression): the SQL code string to parse as the table name.
2866                If another `Expression` instance is passed, it will be used as-is.
2867            properties (dict): an optional mapping of table properties
2868            dialect (str): the dialect used to parse the input table.
2869            copy (bool): if `False`, modify this expression instance in-place.
2870            opts (kwargs): other options to use to parse the input table.
2871
2872        Returns:
2873            Create: the CREATE TABLE AS expression
2874        """
2875        instance = _maybe_copy(self, copy)
2876        table_expression = maybe_parse(
2877            table,
2878            into=Table,
2879            dialect=dialect,
2880            **opts,
2881        )
2882        properties_expression = None
2883        if properties:
2884            properties_expression = Properties.from_dict(properties)
2885
2886        return Create(
2887            this=table_expression,
2888            kind="table",
2889            expression=instance,
2890            properties=properties_expression,
2891        )

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 (str | Expression): the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties (dict): an optional mapping of table properties
  • dialect (str): the dialect used to parse the input table.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input table.
Returns:

Create: the CREATE TABLE AS expression

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2893    def lock(self, update: bool = True, copy: bool = True) -> Select:
2894        """
2895        Set the locking read mode for this expression.
2896
2897        Examples:
2898            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2899            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2900
2901            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2902            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2903
2904        Args:
2905            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2906            copy: if `False`, modify this expression instance in-place.
2907
2908        Returns:
2909            The modified expression.
2910        """
2911
2912        inst = _maybe_copy(self, copy)
2913        inst.set("lock", Lock(update=update))
2914
2915        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):
2930class Subquery(DerivedTable, Unionable):
2931    arg_types = {
2932        "this": True,
2933        "alias": False,
2934        "with": False,
2935        **QUERY_MODIFIERS,
2936    }
2937
2938    def unnest(self):
2939        """
2940        Returns the first non subquery.
2941        """
2942        expression = self
2943        while isinstance(expression, Subquery):
2944            expression = expression.this
2945        return expression
2946
2947    @property
2948    def is_star(self) -> bool:
2949        return self.this.is_star
2950
2951    @property
2952    def output_name(self):
2953        return self.alias
def unnest(self):
2938    def unnest(self):
2939        """
2940        Returns the first non subquery.
2941        """
2942        expression = self
2943        while isinstance(expression, Subquery):
2944            expression = expression.this
2945        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name

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):
2956class TableSample(Expression):
2957    arg_types = {
2958        "this": False,
2959        "method": False,
2960        "bucket_numerator": False,
2961        "bucket_denominator": False,
2962        "bucket_field": False,
2963        "percent": False,
2964        "rows": False,
2965        "size": False,
2966        "seed": False,
2967        "kind": False,
2968    }
class Tag(Expression):
2971class Tag(Expression):
2972    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2973
2974    arg_types = {
2975        "this": False,
2976        "prefix": False,
2977        "postfix": False,
2978    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2981class Pivot(Expression):
2982    arg_types = {
2983        "alias": False,
2984        "expressions": True,
2985        "field": True,
2986        "unpivot": True,
2987        "columns": False,
2988    }
class Window(Expression):
2991class Window(Expression):
2992    arg_types = {
2993        "this": True,
2994        "partition_by": False,
2995        "order": False,
2996        "spec": False,
2997        "alias": False,
2998        "over": False,
2999        "first": False,
3000    }
class WindowSpec(Expression):
3003class WindowSpec(Expression):
3004    arg_types = {
3005        "kind": False,
3006        "start": False,
3007        "start_side": False,
3008        "end": False,
3009        "end_side": False,
3010    }
class Where(Expression):
3013class Where(Expression):
3014    pass
class Star(Expression):
3017class Star(Expression):
3018    arg_types = {"except": False, "replace": False}
3019
3020    @property
3021    def name(self) -> str:
3022        return "*"
3023
3024    @property
3025    def output_name(self):
3026        return self.name
output_name

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):
3029class Parameter(Expression):
3030    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
3033class SessionParameter(Expression):
3034    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
3037class Placeholder(Expression):
3038    arg_types = {"this": False, "kind": False}
class Null(Condition):
3041class Null(Condition):
3042    arg_types: t.Dict[str, t.Any] = {}
3043
3044    @property
3045    def name(self) -> str:
3046        return "NULL"
class Boolean(Condition):
3049class Boolean(Condition):
3050    pass
class DataTypeSize(Expression):
3053class DataTypeSize(Expression):
3054    arg_types = {"this": True, "expression": False}
class DataType(Expression):
3057class DataType(Expression):
3058    arg_types = {
3059        "this": True,
3060        "expressions": False,
3061        "nested": False,
3062        "values": False,
3063        "prefix": False,
3064    }
3065
3066    class Type(AutoName):
3067        ARRAY = auto()
3068        BIGDECIMAL = auto()
3069        BIGINT = auto()
3070        BIGSERIAL = auto()
3071        BINARY = auto()
3072        BIT = auto()
3073        BOOLEAN = auto()
3074        CHAR = auto()
3075        DATE = auto()
3076        DATETIME = auto()
3077        DATETIME64 = auto()
3078        DECIMAL = auto()
3079        DOUBLE = auto()
3080        FLOAT = auto()
3081        GEOGRAPHY = auto()
3082        GEOMETRY = auto()
3083        HLLSKETCH = auto()
3084        HSTORE = auto()
3085        IMAGE = auto()
3086        INET = auto()
3087        INT = auto()
3088        INT128 = auto()
3089        INT256 = auto()
3090        INTERVAL = auto()
3091        JSON = auto()
3092        JSONB = auto()
3093        LONGBLOB = auto()
3094        LONGTEXT = auto()
3095        MAP = auto()
3096        MEDIUMBLOB = auto()
3097        MEDIUMTEXT = auto()
3098        MONEY = auto()
3099        NCHAR = auto()
3100        NULL = auto()
3101        NULLABLE = auto()
3102        NVARCHAR = auto()
3103        OBJECT = auto()
3104        ROWVERSION = auto()
3105        SERIAL = auto()
3106        SMALLINT = auto()
3107        SMALLMONEY = auto()
3108        SMALLSERIAL = auto()
3109        STRUCT = auto()
3110        SUPER = auto()
3111        TEXT = auto()
3112        TIME = auto()
3113        TIMESTAMP = auto()
3114        TIMESTAMPTZ = auto()
3115        TIMESTAMPLTZ = auto()
3116        TINYINT = auto()
3117        UBIGINT = auto()
3118        UINT = auto()
3119        USMALLINT = auto()
3120        UTINYINT = auto()
3121        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3122        UINT128 = auto()
3123        UINT256 = auto()
3124        UNIQUEIDENTIFIER = auto()
3125        UUID = auto()
3126        VARBINARY = auto()
3127        VARCHAR = auto()
3128        VARIANT = auto()
3129        XML = auto()
3130
3131    TEXT_TYPES = {
3132        Type.CHAR,
3133        Type.NCHAR,
3134        Type.VARCHAR,
3135        Type.NVARCHAR,
3136        Type.TEXT,
3137    }
3138
3139    INTEGER_TYPES = {
3140        Type.INT,
3141        Type.TINYINT,
3142        Type.SMALLINT,
3143        Type.BIGINT,
3144        Type.INT128,
3145        Type.INT256,
3146    }
3147
3148    FLOAT_TYPES = {
3149        Type.FLOAT,
3150        Type.DOUBLE,
3151    }
3152
3153    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3154
3155    TEMPORAL_TYPES = {
3156        Type.TIMESTAMP,
3157        Type.TIMESTAMPTZ,
3158        Type.TIMESTAMPLTZ,
3159        Type.DATE,
3160        Type.DATETIME,
3161        Type.DATETIME64,
3162    }
3163
3164    @classmethod
3165    def build(
3166        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3167    ) -> DataType:
3168        from sqlglot import parse_one
3169
3170        if isinstance(dtype, str):
3171            if dtype.upper() in cls.Type.__members__:
3172                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3173            else:
3174                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3175            if data_type_exp is None:
3176                raise ValueError(f"Unparsable data type value: {dtype}")
3177        elif isinstance(dtype, DataType.Type):
3178            data_type_exp = DataType(this=dtype)
3179        elif isinstance(dtype, DataType):
3180            return dtype
3181        else:
3182            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3183        return DataType(**{**data_type_exp.args, **kwargs})
3184
3185    def is_type(self, dtype: DataType.Type) -> bool:
3186        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:
3164    @classmethod
3165    def build(
3166        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3167    ) -> DataType:
3168        from sqlglot import parse_one
3169
3170        if isinstance(dtype, str):
3171            if dtype.upper() in cls.Type.__members__:
3172                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3173            else:
3174                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3175            if data_type_exp is None:
3176                raise ValueError(f"Unparsable data type value: {dtype}")
3177        elif isinstance(dtype, DataType.Type):
3178            data_type_exp = DataType(this=dtype)
3179        elif isinstance(dtype, DataType):
3180            return dtype
3181        else:
3182            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3183        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3185    def is_type(self, dtype: DataType.Type) -> bool:
3186        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
3066    class Type(AutoName):
3067        ARRAY = auto()
3068        BIGDECIMAL = auto()
3069        BIGINT = auto()
3070        BIGSERIAL = auto()
3071        BINARY = auto()
3072        BIT = auto()
3073        BOOLEAN = auto()
3074        CHAR = auto()
3075        DATE = auto()
3076        DATETIME = auto()
3077        DATETIME64 = auto()
3078        DECIMAL = auto()
3079        DOUBLE = auto()
3080        FLOAT = auto()
3081        GEOGRAPHY = auto()
3082        GEOMETRY = auto()
3083        HLLSKETCH = auto()
3084        HSTORE = auto()
3085        IMAGE = auto()
3086        INET = auto()
3087        INT = auto()
3088        INT128 = auto()
3089        INT256 = auto()
3090        INTERVAL = auto()
3091        JSON = auto()
3092        JSONB = auto()
3093        LONGBLOB = auto()
3094        LONGTEXT = auto()
3095        MAP = auto()
3096        MEDIUMBLOB = auto()
3097        MEDIUMTEXT = auto()
3098        MONEY = auto()
3099        NCHAR = auto()
3100        NULL = auto()
3101        NULLABLE = auto()
3102        NVARCHAR = auto()
3103        OBJECT = auto()
3104        ROWVERSION = auto()
3105        SERIAL = auto()
3106        SMALLINT = auto()
3107        SMALLMONEY = auto()
3108        SMALLSERIAL = auto()
3109        STRUCT = auto()
3110        SUPER = auto()
3111        TEXT = auto()
3112        TIME = auto()
3113        TIMESTAMP = auto()
3114        TIMESTAMPTZ = auto()
3115        TIMESTAMPLTZ = auto()
3116        TINYINT = auto()
3117        UBIGINT = auto()
3118        UINT = auto()
3119        USMALLINT = auto()
3120        UTINYINT = auto()
3121        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3122        UINT128 = auto()
3123        UINT256 = auto()
3124        UNIQUEIDENTIFIER = auto()
3125        UUID = auto()
3126        VARBINARY = auto()
3127        VARCHAR = auto()
3128        VARIANT = auto()
3129        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):
3190class PseudoType(Expression):
3191    pass
class SubqueryPredicate(Predicate):
3195class SubqueryPredicate(Predicate):
3196    pass
class All(SubqueryPredicate):
3199class All(SubqueryPredicate):
3200    pass
class Any(SubqueryPredicate):
3203class Any(SubqueryPredicate):
3204    pass
class Exists(SubqueryPredicate):
3207class Exists(SubqueryPredicate):
3208    pass
class Command(Expression):
3213class Command(Expression):
3214    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
3217class Transaction(Expression):
3218    arg_types = {"this": False, "modes": False}
class Commit(Expression):
3221class Commit(Expression):
3222    arg_types = {"chain": False}
class Rollback(Expression):
3225class Rollback(Expression):
3226    arg_types = {"savepoint": False}
class AlterTable(Expression):
3229class AlterTable(Expression):
3230    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
3233class AddConstraint(Expression):
3234    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
3237class DropPartition(Expression):
3238    arg_types = {"expressions": True, "exists": False}
class Binary(Condition):
3242class Binary(Condition):
3243    arg_types = {"this": True, "expression": True}
3244
3245    @property
3246    def left(self):
3247        return self.this
3248
3249    @property
3250    def right(self):
3251        return self.expression
class Add(Binary):
3254class Add(Binary):
3255    pass
class Connector(Binary):
3258class Connector(Binary):
3259    pass
class And(Connector):
3262class And(Connector):
3263    pass
class Or(Connector):
3266class Or(Connector):
3267    pass
class BitwiseAnd(Binary):
3270class BitwiseAnd(Binary):
3271    pass
class BitwiseLeftShift(Binary):
3274class BitwiseLeftShift(Binary):
3275    pass
class BitwiseOr(Binary):
3278class BitwiseOr(Binary):
3279    pass
class BitwiseRightShift(Binary):
3282class BitwiseRightShift(Binary):
3283    pass
class BitwiseXor(Binary):
3286class BitwiseXor(Binary):
3287    pass
class Div(Binary):
3290class Div(Binary):
3291    pass
class Overlaps(Binary):
3294class Overlaps(Binary):
3295    pass
class Dot(Binary):
3298class Dot(Binary):
3299    @property
3300    def name(self) -> str:
3301        return self.expression.name
3302
3303    @classmethod
3304    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3305        """Build a Dot object with a sequence of expressions."""
3306        if len(expressions) < 2:
3307            raise ValueError(f"Dot requires >= 2 expressions.")
3308
3309        a, b, *expressions = expressions
3310        dot = Dot(this=a, expression=b)
3311
3312        for expression in expressions:
3313            dot = Dot(this=dot, expression=expression)
3314
3315        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3303    @classmethod
3304    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3305        """Build a Dot object with a sequence of expressions."""
3306        if len(expressions) < 2:
3307            raise ValueError(f"Dot requires >= 2 expressions.")
3308
3309        a, b, *expressions = expressions
3310        dot = Dot(this=a, expression=b)
3311
3312        for expression in expressions:
3313            dot = Dot(this=dot, expression=expression)
3314
3315        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3318class DPipe(Binary):
3319    pass
class EQ(Binary, Predicate):
3322class EQ(Binary, Predicate):
3323    pass
class NullSafeEQ(Binary, Predicate):
3326class NullSafeEQ(Binary, Predicate):
3327    pass
class NullSafeNEQ(Binary, Predicate):
3330class NullSafeNEQ(Binary, Predicate):
3331    pass
class Distance(Binary):
3334class Distance(Binary):
3335    pass
class Escape(Binary):
3338class Escape(Binary):
3339    pass
class Glob(Binary, Predicate):
3342class Glob(Binary, Predicate):
3343    pass
class GT(Binary, Predicate):
3346class GT(Binary, Predicate):
3347    pass
class GTE(Binary, Predicate):
3350class GTE(Binary, Predicate):
3351    pass
class ILike(Binary, Predicate):
3354class ILike(Binary, Predicate):
3355    pass
class ILikeAny(Binary, Predicate):
3358class ILikeAny(Binary, Predicate):
3359    pass
class IntDiv(Binary):
3362class IntDiv(Binary):
3363    pass
class Is(Binary, Predicate):
3366class Is(Binary, Predicate):
3367    pass
class Kwarg(Binary):
3370class Kwarg(Binary):
3371    """Kwarg in special functions like func(kwarg => y)."""

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

class Like(Binary, Predicate):
3374class Like(Binary, Predicate):
3375    pass
class LikeAny(Binary, Predicate):
3378class LikeAny(Binary, Predicate):
3379    pass
class LT(Binary, Predicate):
3382class LT(Binary, Predicate):
3383    pass
class LTE(Binary, Predicate):
3386class LTE(Binary, Predicate):
3387    pass
class Mod(Binary):
3390class Mod(Binary):
3391    pass
class Mul(Binary):
3394class Mul(Binary):
3395    pass
class NEQ(Binary, Predicate):
3398class NEQ(Binary, Predicate):
3399    pass
class SimilarTo(Binary, Predicate):
3402class SimilarTo(Binary, Predicate):
3403    pass
class Slice(Binary):
3406class Slice(Binary):
3407    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3410class Sub(Binary):
3411    pass
class ArrayOverlaps(Binary):
3414class ArrayOverlaps(Binary):
3415    pass
class Unary(Condition):
3420class Unary(Condition):
3421    pass
class BitwiseNot(Unary):
3424class BitwiseNot(Unary):
3425    pass
class Not(Unary):
3428class Not(Unary):
3429    pass
class Paren(Unary):
3432class Paren(Unary):
3433    arg_types = {"this": True, "with": False}
class Neg(Unary):
3436class Neg(Unary):
3437    pass
class Alias(Expression):
3440class Alias(Expression):
3441    arg_types = {"this": True, "alias": False}
3442
3443    @property
3444    def output_name(self):
3445        return self.alias
output_name

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):
3448class Aliases(Expression):
3449    arg_types = {"this": True, "expressions": True}
3450
3451    @property
3452    def aliases(self):
3453        return self.expressions
class AtTimeZone(Expression):
3456class AtTimeZone(Expression):
3457    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3460class Between(Predicate):
3461    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3464class Bracket(Condition):
3465    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3468class Distinct(Expression):
3469    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3472class In(Predicate):
3473    arg_types = {
3474        "this": True,
3475        "expressions": False,
3476        "query": False,
3477        "unnest": False,
3478        "field": False,
3479        "is_global": False,
3480    }
class TimeUnit(Expression):
3483class TimeUnit(Expression):
3484    """Automatically converts unit arg into a var."""
3485
3486    arg_types = {"unit": False}
3487
3488    def __init__(self, **args):
3489        unit = args.get("unit")
3490        if isinstance(unit, (Column, Literal)):
3491            args["unit"] = Var(this=unit.name)
3492        elif isinstance(unit, Week):
3493            unit.set("this", Var(this=unit.this.name))
3494        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3488    def __init__(self, **args):
3489        unit = args.get("unit")
3490        if isinstance(unit, (Column, Literal)):
3491            args["unit"] = Var(this=unit.name)
3492        elif isinstance(unit, Week):
3493            unit.set("this", Var(this=unit.this.name))
3494        super().__init__(**args)
class Interval(TimeUnit):
3497class Interval(TimeUnit):
3498    arg_types = {"this": False, "unit": False}
class IgnoreNulls(Expression):
3501class IgnoreNulls(Expression):
3502    pass
class RespectNulls(Expression):
3505class RespectNulls(Expression):
3506    pass
class Func(Condition):
3510class Func(Condition):
3511    """
3512    The base class for all function expressions.
3513
3514    Attributes:
3515        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3516            treated as a variable length argument and the argument's value will be stored as a list.
3517        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3518            for this function expression. These values are used to map this node to a name during parsing
3519            as well as to provide the function's name during SQL string generation. By default the SQL
3520            name is set to the expression's class name transformed to snake case.
3521    """
3522
3523    is_var_len_args = False
3524
3525    @classmethod
3526    def from_arg_list(cls, args):
3527        if cls.is_var_len_args:
3528            all_arg_keys = list(cls.arg_types)
3529            # If this function supports variable length argument treat the last argument as such.
3530            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3531            num_non_var = len(non_var_len_arg_keys)
3532
3533            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3534            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3535        else:
3536            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3537
3538        return cls(**args_dict)
3539
3540    @classmethod
3541    def sql_names(cls):
3542        if cls is Func:
3543            raise NotImplementedError(
3544                "SQL name is only supported by concrete function implementations"
3545            )
3546        if "_sql_names" not in cls.__dict__:
3547            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3548        return cls._sql_names
3549
3550    @classmethod
3551    def sql_name(cls):
3552        return cls.sql_names()[0]
3553
3554    @classmethod
3555    def default_parser_mappings(cls):
3556        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):
3525    @classmethod
3526    def from_arg_list(cls, args):
3527        if cls.is_var_len_args:
3528            all_arg_keys = list(cls.arg_types)
3529            # If this function supports variable length argument treat the last argument as such.
3530            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3531            num_non_var = len(non_var_len_arg_keys)
3532
3533            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3534            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3535        else:
3536            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3537
3538        return cls(**args_dict)
@classmethod
def sql_names(cls):
3540    @classmethod
3541    def sql_names(cls):
3542        if cls is Func:
3543            raise NotImplementedError(
3544                "SQL name is only supported by concrete function implementations"
3545            )
3546        if "_sql_names" not in cls.__dict__:
3547            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3548        return cls._sql_names
@classmethod
def sql_name(cls):
3550    @classmethod
3551    def sql_name(cls):
3552        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3554    @classmethod
3555    def default_parser_mappings(cls):
3556        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3559class AggFunc(Func):
3560    pass
class ParameterizedAgg(AggFunc):
3563class ParameterizedAgg(AggFunc):
3564    arg_types = {"this": True, "expressions": True, "params": True}
class Abs(Func):
3567class Abs(Func):
3568    pass
class Anonymous(Func):
3571class Anonymous(Func):
3572    arg_types = {"this": True, "expressions": False}
3573    is_var_len_args = True
class Hll(AggFunc):
3578class Hll(AggFunc):
3579    arg_types = {"this": True, "expressions": False}
3580    is_var_len_args = True
class ApproxDistinct(AggFunc):
3583class ApproxDistinct(AggFunc):
3584    arg_types = {"this": True, "accuracy": False}
3585    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
class Array(Func):
3588class Array(Func):
3589    arg_types = {"expressions": False}
3590    is_var_len_args = True
class ToChar(Func):
3594class ToChar(Func):
3595    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3598class GenerateSeries(Func):
3599    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3602class ArrayAgg(AggFunc):
3603    pass
class ArrayAll(Func):
3606class ArrayAll(Func):
3607    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3610class ArrayAny(Func):
3611    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3614class ArrayConcat(Func):
3615    arg_types = {"this": True, "expressions": False}
3616    is_var_len_args = True
class ArrayContains(Binary, Func):
3619class ArrayContains(Binary, Func):
3620    pass
class ArrayContained(Binary):
3623class ArrayContained(Binary):
3624    pass
class ArrayFilter(Func):
3627class ArrayFilter(Func):
3628    arg_types = {"this": True, "expression": True}
3629    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3632class ArrayJoin(Func):
3633    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3636class ArraySize(Func):
3637    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3640class ArraySort(Func):
3641    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3644class ArraySum(Func):
3645    pass
class ArrayUnionAgg(AggFunc):
3648class ArrayUnionAgg(AggFunc):
3649    pass
class Avg(AggFunc):
3652class Avg(AggFunc):
3653    pass
class AnyValue(AggFunc):
3656class AnyValue(AggFunc):
3657    pass
class Case(Func):
3660class Case(Func):
3661    arg_types = {"this": False, "ifs": True, "default": False}
3662
3663    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3664        instance = _maybe_copy(self, copy)
3665        instance.append(
3666            "ifs",
3667            If(
3668                this=maybe_parse(condition, copy=copy, **opts),
3669                true=maybe_parse(then, copy=copy, **opts),
3670            ),
3671        )
3672        return instance
3673
3674    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3675        instance = _maybe_copy(self, copy)
3676        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3677        return instance
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3663    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3664        instance = _maybe_copy(self, copy)
3665        instance.append(
3666            "ifs",
3667            If(
3668                this=maybe_parse(condition, copy=copy, **opts),
3669                true=maybe_parse(then, copy=copy, **opts),
3670            ),
3671        )
3672        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3674    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3675        instance = _maybe_copy(self, copy)
3676        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3677        return instance
class Cast(Func):
3680class Cast(Func):
3681    arg_types = {"this": True, "to": True}
3682
3683    @property
3684    def name(self) -> str:
3685        return self.this.name
3686
3687    @property
3688    def to(self):
3689        return self.args["to"]
3690
3691    @property
3692    def output_name(self):
3693        return self.name
3694
3695    def is_type(self, dtype: DataType.Type) -> bool:
3696        return self.to.is_type(dtype)
output_name

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:
3695    def is_type(self, dtype: DataType.Type) -> bool:
3696        return self.to.is_type(dtype)
class CastToStrType(Func):
3699class CastToStrType(Func):
3700    arg_types = {"this": True, "expression": True}
class Collate(Binary):
3703class Collate(Binary):
3704    pass
class TryCast(Cast):
3707class TryCast(Cast):
3708    pass
class Ceil(Func):
3711class Ceil(Func):
3712    arg_types = {"this": True, "decimals": False}
3713    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3716class Coalesce(Func):
3717    arg_types = {"this": True, "expressions": False}
3718    is_var_len_args = True
class Concat(Func):
3721class Concat(Func):
3722    arg_types = {"expressions": True}
3723    is_var_len_args = True
class ConcatWs(Concat):
3726class ConcatWs(Concat):
3727    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3730class Count(AggFunc):
3731    arg_types = {"this": False}
class CountIf(AggFunc):
3734class CountIf(AggFunc):
3735    pass
class CurrentDate(Func):
3738class CurrentDate(Func):
3739    arg_types = {"this": False}
class CurrentDatetime(Func):
3742class CurrentDatetime(Func):
3743    arg_types = {"this": False}
class CurrentTime(Func):
3746class CurrentTime(Func):
3747    arg_types = {"this": False}
class CurrentTimestamp(Func):
3750class CurrentTimestamp(Func):
3751    arg_types = {"this": False}
class CurrentUser(Func):
3754class CurrentUser(Func):
3755    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3758class DateAdd(Func, TimeUnit):
3759    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3762class DateSub(Func, TimeUnit):
3763    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3766class DateDiff(Func, TimeUnit):
3767    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3768    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3771class DateTrunc(Func):
3772    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3775class DatetimeAdd(Func, TimeUnit):
3776    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3779class DatetimeSub(Func, TimeUnit):
3780    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3783class DatetimeDiff(Func, TimeUnit):
3784    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3787class DatetimeTrunc(Func, TimeUnit):
3788    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3791class DayOfWeek(Func):
3792    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3795class DayOfMonth(Func):
3796    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3799class DayOfYear(Func):
3800    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3803class WeekOfYear(Func):
3804    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3807class LastDateOfMonth(Func):
3808    pass
class Extract(Func):
3811class Extract(Func):
3812    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3815class TimestampAdd(Func, TimeUnit):
3816    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3819class TimestampSub(Func, TimeUnit):
3820    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3823class TimestampDiff(Func, TimeUnit):
3824    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3827class TimestampTrunc(Func, TimeUnit):
3828    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3831class TimeAdd(Func, TimeUnit):
3832    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3835class TimeSub(Func, TimeUnit):
3836    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3839class TimeDiff(Func, TimeUnit):
3840    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3843class TimeTrunc(Func, TimeUnit):
3844    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3847class DateFromParts(Func):
3848    _sql_names = ["DATEFROMPARTS"]
3849    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3852class DateStrToDate(Func):
3853    pass
class DateToDateStr(Func):
3856class DateToDateStr(Func):
3857    pass
class DateToDi(Func):
3860class DateToDi(Func):
3861    pass
class Day(Func):
3864class Day(Func):
3865    pass
class Decode(Func):
3868class Decode(Func):
3869    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3872class DiToDate(Func):
3873    pass
class Encode(Func):
3876class Encode(Func):
3877    arg_types = {"this": True, "charset": True}
class Exp(Func):
3880class Exp(Func):
3881    pass
class Explode(Func):
3884class Explode(Func):
3885    pass
class Floor(Func):
3888class Floor(Func):
3889    arg_types = {"this": True, "decimals": False}
class FromBase64(Func):
3892class FromBase64(Func):
3893    pass
class ToBase64(Func):
3896class ToBase64(Func):
3897    pass
class Greatest(Func):
3900class Greatest(Func):
3901    arg_types = {"this": True, "expressions": False}
3902    is_var_len_args = True
class GroupConcat(Func):
3905class GroupConcat(Func):
3906    arg_types = {"this": True, "separator": False}
class Hex(Func):
3909class Hex(Func):
3910    pass
class If(Func):
3913class If(Func):
3914    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3917class IfNull(Func):
3918    arg_types = {"this": True, "expression": False}
3919    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3922class Initcap(Func):
3923    pass
class JSONKeyValue(Expression):
3926class JSONKeyValue(Expression):
3927    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
3930class JSONObject(Func):
3931    arg_types = {
3932        "expressions": False,
3933        "null_handling": False,
3934        "unique_keys": False,
3935        "return_type": False,
3936        "format_json": False,
3937        "encoding": False,
3938    }
class OpenJSONColumnDef(Expression):
3941class OpenJSONColumnDef(Expression):
3942    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
class OpenJSON(Func):
3945class OpenJSON(Func):
3946    arg_types = {"this": True, "path": False, "expressions": False}
class JSONBContains(Binary):
3949class JSONBContains(Binary):
3950    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3953class JSONExtract(Binary, Func):
3954    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3957class JSONExtractScalar(JSONExtract):
3958    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3961class JSONBExtract(JSONExtract):
3962    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3965class JSONBExtractScalar(JSONExtract):
3966    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
3969class JSONFormat(Func):
3970    arg_types = {"this": False, "options": False}
3971    _sql_names = ["JSON_FORMAT"]
class Least(Func):
3974class Least(Func):
3975    arg_types = {"expressions": False}
3976    is_var_len_args = True
class Length(Func):
3979class Length(Func):
3980    pass
class Levenshtein(Func):
3983class Levenshtein(Func):
3984    arg_types = {
3985        "this": True,
3986        "expression": False,
3987        "ins_cost": False,
3988        "del_cost": False,
3989        "sub_cost": False,
3990    }
class Ln(Func):
3993class Ln(Func):
3994    pass
class Log(Func):
3997class Log(Func):
3998    arg_types = {"this": True, "expression": False}
class Log2(Func):
4001class Log2(Func):
4002    pass
class Log10(Func):
4005class Log10(Func):
4006    pass
class LogicalOr(AggFunc):
4009class LogicalOr(AggFunc):
4010    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
4013class LogicalAnd(AggFunc):
4014    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
4017class Lower(Func):
4018    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
4021class Map(Func):
4022    arg_types = {"keys": False, "values": False}
class StarMap(Func):
4025class StarMap(Func):
4026    pass
class VarMap(Func):
4029class VarMap(Func):
4030    arg_types = {"keys": True, "values": True}
4031    is_var_len_args = True
class MatchAgainst(Func):
4035class MatchAgainst(Func):
4036    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
4039class Max(AggFunc):
4040    arg_types = {"this": True, "expressions": False}
4041    is_var_len_args = True
class MD5(Func):
4044class MD5(Func):
4045    _sql_names = ["MD5"]
class Min(AggFunc):
4048class Min(AggFunc):
4049    arg_types = {"this": True, "expressions": False}
4050    is_var_len_args = True
class Month(Func):
4053class Month(Func):
4054    pass
class Nvl2(Func):
4057class Nvl2(Func):
4058    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
4061class Posexplode(Func):
4062    pass
class Pow(Binary, Func):
4065class Pow(Binary, Func):
4066    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
4069class PercentileCont(AggFunc):
4070    arg_types = {"this": True, "expression": False}
class PercentileDisc(AggFunc):
4073class PercentileDisc(AggFunc):
4074    arg_types = {"this": True, "expression": False}
class Quantile(AggFunc):
4077class Quantile(AggFunc):
4078    arg_types = {"this": True, "quantile": True}
class ApproxQuantile(Quantile):
4081class ApproxQuantile(Quantile):
4082    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
4085class RangeN(Func):
4086    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
4089class ReadCSV(Func):
4090    _sql_names = ["READ_CSV"]
4091    is_var_len_args = True
4092    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
4095class Reduce(Func):
4096    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
4099class RegexpExtract(Func):
4100    arg_types = {
4101        "this": True,
4102        "expression": True,
4103        "position": False,
4104        "occurrence": False,
4105        "group": False,
4106    }
class RegexpLike(Func):
4109class RegexpLike(Func):
4110    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
4113class RegexpILike(Func):
4114    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
4119class RegexpSplit(Func):
4120    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
4123class Repeat(Func):
4124    arg_types = {"this": True, "times": True}
class Round(Func):
4127class Round(Func):
4128    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
4131class RowNumber(Func):
4132    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
4135class SafeDivide(Func):
4136    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
4139class SetAgg(AggFunc):
4140    pass
class SHA(Func):
4143class SHA(Func):
4144    _sql_names = ["SHA", "SHA1"]
class SHA2(Func):
4147class SHA2(Func):
4148    _sql_names = ["SHA2"]
4149    arg_types = {"this": True, "length": False}
class SortArray(Func):
4152class SortArray(Func):
4153    arg_types = {"this": True, "asc": False}
class Split(Func):
4156class Split(Func):
4157    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
4162class Substring(Func):
4163    arg_types = {"this": True, "start": False, "length": False}
class StandardHash(Func):
4166class StandardHash(Func):
4167    arg_types = {"this": True, "expression": False}
class StrPosition(Func):
4170class StrPosition(Func):
4171    arg_types = {
4172        "this": True,
4173        "substr": True,
4174        "position": False,
4175        "instance": False,
4176    }
class StrToDate(Func):
4179class StrToDate(Func):
4180    arg_types = {"this": True, "format": True}
class StrToTime(Func):
4183class StrToTime(Func):
4184    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
4189class StrToUnix(Func):
4190    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
4193class NumberToStr(Func):
4194    arg_types = {"this": True, "format": True}
class Struct(Func):
4197class Struct(Func):
4198    arg_types = {"expressions": True}
4199    is_var_len_args = True
class StructExtract(Func):
4202class StructExtract(Func):
4203    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
4206class Sum(AggFunc):
4207    pass
class Sqrt(Func):
4210class Sqrt(Func):
4211    pass
class Stddev(AggFunc):
4214class Stddev(AggFunc):
4215    pass
class StddevPop(AggFunc):
4218class StddevPop(AggFunc):
4219    pass
class StddevSamp(AggFunc):
4222class StddevSamp(AggFunc):
4223    pass
class TimeToStr(Func):
4226class TimeToStr(Func):
4227    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
4230class TimeToTimeStr(Func):
4231    pass
class TimeToUnix(Func):
4234class TimeToUnix(Func):
4235    pass
class TimeStrToDate(Func):
4238class TimeStrToDate(Func):
4239    pass
class TimeStrToTime(Func):
4242class TimeStrToTime(Func):
4243    pass
class TimeStrToUnix(Func):
4246class TimeStrToUnix(Func):
4247    pass
class Trim(Func):
4250class Trim(Func):
4251    arg_types = {
4252        "this": True,
4253        "expression": False,
4254        "position": False,
4255        "collation": False,
4256    }
class TsOrDsAdd(Func, TimeUnit):
4259class TsOrDsAdd(Func, TimeUnit):
4260    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
4263class TsOrDsToDateStr(Func):
4264    pass
class TsOrDsToDate(Func):
4267class TsOrDsToDate(Func):
4268    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
4271class TsOrDiToDi(Func):
4272    pass
class Unhex(Func):
4275class Unhex(Func):
4276    pass
class UnixToStr(Func):
4279class UnixToStr(Func):
4280    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
4285class UnixToTime(Func):
4286    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4287
4288    SECONDS = Literal.string("seconds")
4289    MILLIS = Literal.string("millis")
4290    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
4293class UnixToTimeStr(Func):
4294    pass
class Upper(Func):
4297class Upper(Func):
4298    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
4301class Variance(AggFunc):
4302    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
4305class VariancePop(AggFunc):
4306    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
4309class Week(Func):
4310    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
4313class XMLTable(Func):
4314    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4317class Year(Func):
4318    pass
class Use(Expression):
4321class Use(Expression):
4322    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4325class Merge(Expression):
4326    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4329class When(Func):
4330    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
class NextValueFor(Func):
4335class NextValueFor(Func):
4336    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:
4373def maybe_parse(
4374    sql_or_expression: ExpOrStr,
4375    *,
4376    into: t.Optional[IntoType] = None,
4377    dialect: DialectType = None,
4378    prefix: t.Optional[str] = None,
4379    copy: bool = False,
4380    **opts,
4381) -> Expression:
4382    """Gracefully handle a possible string or expression.
4383
4384    Example:
4385        >>> maybe_parse("1")
4386        (LITERAL this: 1, is_string: False)
4387        >>> maybe_parse(to_identifier("x"))
4388        (IDENTIFIER this: x, quoted: False)
4389
4390    Args:
4391        sql_or_expression: the SQL code string or an expression
4392        into: the SQLGlot Expression to parse into
4393        dialect: the dialect used to parse the input expressions (in the case that an
4394            input expression is a SQL string).
4395        prefix: a string to prefix the sql with before it gets parsed
4396            (automatically includes a space)
4397        copy: whether or not to copy the expression.
4398        **opts: other options to use to parse the input expressions (again, in the case
4399            that an input expression is a SQL string).
4400
4401    Returns:
4402        Expression: the parsed or given expression.
4403    """
4404    if isinstance(sql_or_expression, Expression):
4405        if copy:
4406            return sql_or_expression.copy()
4407        return sql_or_expression
4408
4409    import sqlglot
4410
4411    sql = str(sql_or_expression)
4412    if prefix:
4413        sql = f"{prefix} {sql}"
4414    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, right, distinct=True, dialect=None, **opts):
4586def union(left, right, distinct=True, dialect=None, **opts):
4587    """
4588    Initializes a syntax tree from one UNION expression.
4589
4590    Example:
4591        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4592        'SELECT * FROM foo UNION SELECT * FROM bla'
4593
4594    Args:
4595        left (str | Expression): the SQL code string corresponding to the left-hand side.
4596            If an `Expression` instance is passed, it will be used as-is.
4597        right (str | Expression): the SQL code string corresponding to the right-hand side.
4598            If an `Expression` instance is passed, it will be used as-is.
4599        distinct (bool): set the DISTINCT flag if and only if this is true.
4600        dialect (str): the dialect used to parse the input expression.
4601        opts (kwargs): other options to use to parse the input expressions.
4602    Returns:
4603        Union: the syntax tree for the UNION expression.
4604    """
4605    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4606    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4607
4608    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 (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the syntax tree for the UNION expression.

def intersect(left, right, distinct=True, dialect=None, **opts):
4611def intersect(left, right, distinct=True, dialect=None, **opts):
4612    """
4613    Initializes a syntax tree from one INTERSECT expression.
4614
4615    Example:
4616        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4617        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4618
4619    Args:
4620        left (str | Expression): the SQL code string corresponding to the left-hand side.
4621            If an `Expression` instance is passed, it will be used as-is.
4622        right (str | Expression): the SQL code string corresponding to the right-hand side.
4623            If an `Expression` instance is passed, it will be used as-is.
4624        distinct (bool): set the DISTINCT flag if and only if this is true.
4625        dialect (str): the dialect used to parse the input expression.
4626        opts (kwargs): other options to use to parse the input expressions.
4627    Returns:
4628        Intersect: the syntax tree for the INTERSECT expression.
4629    """
4630    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4631    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4632
4633    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 (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the syntax tree for the INTERSECT expression.

def except_(left, right, distinct=True, dialect=None, **opts):
4636def except_(left, right, distinct=True, dialect=None, **opts):
4637    """
4638    Initializes a syntax tree from one EXCEPT expression.
4639
4640    Example:
4641        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4642        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4643
4644    Args:
4645        left (str | Expression): the SQL code string corresponding to the left-hand side.
4646            If an `Expression` instance is passed, it will be used as-is.
4647        right (str | Expression): the SQL code string corresponding to the right-hand side.
4648            If an `Expression` instance is passed, it will be used as-is.
4649        distinct (bool): set the DISTINCT flag if and only if this is true.
4650        dialect (str): the dialect used to parse the input expression.
4651        opts (kwargs): other options to use to parse the input expressions.
4652    Returns:
4653        Except: the syntax tree for the EXCEPT statement.
4654    """
4655    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4656    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4657
4658    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 (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the syntax tree for the EXCEPT statement.

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:
4661def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4662    """
4663    Initializes a syntax tree from one or multiple SELECT expressions.
4664
4665    Example:
4666        >>> select("col1", "col2").from_("tbl").sql()
4667        'SELECT col1, col2 FROM tbl'
4668
4669    Args:
4670        *expressions: the SQL code string to parse as the expressions of a
4671            SELECT statement. If an Expression instance is passed, this is used as-is.
4672        dialect: the dialect used to parse the input expressions (in the case that an
4673            input expression is a SQL string).
4674        **opts: other options to use to parse the input expressions (again, in the case
4675            that an input expression is a SQL string).
4676
4677    Returns:
4678        Select: the syntax tree for the SELECT statement.
4679    """
4680    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:
4683def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4684    """
4685    Initializes a syntax tree from a FROM expression.
4686
4687    Example:
4688        >>> from_("tbl").select("col1", "col2").sql()
4689        'SELECT col1, col2 FROM tbl'
4690
4691    Args:
4692        *expression: the SQL code string to parse as the FROM expressions of a
4693            SELECT statement. If an Expression instance is passed, this is used as-is.
4694        dialect: the dialect used to parse the input expression (in the case that the
4695            input expression is a SQL string).
4696        **opts: other options to use to parse the input expressions (again, in the case
4697            that the input expression is a SQL string).
4698
4699    Returns:
4700        Select: the syntax tree for the SELECT statement.
4701    """
4702    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:
4705def update(
4706    table: str | Table,
4707    properties: dict,
4708    where: t.Optional[ExpOrStr] = None,
4709    from_: t.Optional[ExpOrStr] = None,
4710    dialect: DialectType = None,
4711    **opts,
4712) -> Update:
4713    """
4714    Creates an update statement.
4715
4716    Example:
4717        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4718        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4719
4720    Args:
4721        *properties: dictionary of properties to set which are
4722            auto converted to sql objects eg None -> NULL
4723        where: sql conditional parsed into a WHERE statement
4724        from_: sql statement parsed into a FROM statement
4725        dialect: the dialect used to parse the input expressions.
4726        **opts: other options to use to parse the input expressions.
4727
4728    Returns:
4729        Update: the syntax tree for the UPDATE statement.
4730    """
4731    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4732    update_expr.set(
4733        "expressions",
4734        [
4735            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4736            for k, v in properties.items()
4737        ],
4738    )
4739    if from_:
4740        update_expr.set(
4741            "from",
4742            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4743        )
4744    if isinstance(where, Condition):
4745        where = Where(this=where)
4746    if where:
4747        update_expr.set(
4748            "where",
4749            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4750        )
4751    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:
4754def delete(
4755    table: ExpOrStr,
4756    where: t.Optional[ExpOrStr] = None,
4757    returning: t.Optional[ExpOrStr] = None,
4758    dialect: DialectType = None,
4759    **opts,
4760) -> Delete:
4761    """
4762    Builds a delete statement.
4763
4764    Example:
4765        >>> delete("my_table", where="id > 1").sql()
4766        'DELETE FROM my_table WHERE id > 1'
4767
4768    Args:
4769        where: sql conditional parsed into a WHERE statement
4770        returning: sql conditional parsed into a RETURNING statement
4771        dialect: the dialect used to parse the input expressions.
4772        **opts: other options to use to parse the input expressions.
4773
4774    Returns:
4775        Delete: the syntax tree for the DELETE statement.
4776    """
4777    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4778    if where:
4779        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4780    if returning:
4781        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4782    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:
4785def insert(
4786    expression: ExpOrStr,
4787    into: ExpOrStr,
4788    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
4789    overwrite: t.Optional[bool] = None,
4790    dialect: DialectType = None,
4791    copy: bool = True,
4792    **opts,
4793) -> Insert:
4794    """
4795    Builds an INSERT statement.
4796
4797    Example:
4798        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
4799        'INSERT INTO tbl VALUES (1, 2, 3)'
4800
4801    Args:
4802        expression: the sql string or expression of the INSERT statement
4803        into: the tbl to insert data to.
4804        columns: optionally the table's column names.
4805        overwrite: whether to INSERT OVERWRITE or not.
4806        dialect: the dialect used to parse the input expressions.
4807        copy: whether or not to copy the expression.
4808        **opts: other options to use to parse the input expressions.
4809
4810    Returns:
4811        Insert: the syntax tree for the INSERT statement.
4812    """
4813    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
4814    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
4815
4816    if columns:
4817        this = _apply_list_builder(
4818            *columns,
4819            instance=Schema(this=this),
4820            arg="expressions",
4821            into=Identifier,
4822            copy=False,
4823            dialect=dialect,
4824            **opts,
4825        )
4826
4827    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, dialect=None, copy=True, **opts) -> sqlglot.expressions.Condition:
4830def condition(expression, dialect=None, copy=True, **opts) -> Condition:
4831    """
4832    Initialize a logical condition expression.
4833
4834    Example:
4835        >>> condition("x=1").sql()
4836        'x = 1'
4837
4838        This is helpful for composing larger logical syntax trees:
4839        >>> where = condition("x=1")
4840        >>> where = where.and_("y=1")
4841        >>> Select().from_("tbl").select("*").where(where).sql()
4842        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4843
4844    Args:
4845        *expression (str | Expression): the SQL code string to parse.
4846            If an Expression instance is passed, this is used as-is.
4847        dialect (str): the dialect used to parse the input expression (in the case that the
4848            input expression is a SQL string).
4849        copy (bool): Whether or not to copy `expression` (only applies to expressions).
4850        **opts: other options to use to parse the input expressions (again, in the case
4851            that the input expression is a SQL string).
4852
4853    Returns:
4854        Condition: the expression
4855    """
4856    return maybe_parse(  # type: ignore
4857        expression,
4858        into=Condition,
4859        dialect=dialect,
4860        copy=copy,
4861        **opts,
4862    )

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 (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • copy (bool): 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:

Condition: the expression

def and_(*expressions, dialect=None, copy=True, **opts) -> sqlglot.expressions.And:
4865def and_(*expressions, dialect=None, copy=True, **opts) -> And:
4866    """
4867    Combine multiple conditions with an AND logical operator.
4868
4869    Example:
4870        >>> and_("x=1", and_("y=1", "z=1")).sql()
4871        'x = 1 AND (y = 1 AND z = 1)'
4872
4873    Args:
4874        *expressions (str | Expression): the SQL code strings to parse.
4875            If an Expression instance is passed, this is used as-is.
4876        dialect (str): the dialect used to parse the input expression.
4877        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4878        **opts: other options to use to parse the input expressions.
4879
4880    Returns:
4881        And: the new condition
4882    """
4883    return _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 (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): 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, dialect=None, copy=True, **opts) -> sqlglot.expressions.Or:
4886def or_(*expressions, dialect=None, copy=True, **opts) -> Or:
4887    """
4888    Combine multiple conditions with an OR logical operator.
4889
4890    Example:
4891        >>> or_("x=1", or_("y=1", "z=1")).sql()
4892        'x = 1 OR (y = 1 OR z = 1)'
4893
4894    Args:
4895        *expressions (str | Expression): the SQL code strings to parse.
4896            If an Expression instance is passed, this is used as-is.
4897        dialect (str): the dialect used to parse the input expression.
4898        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4899        **opts: other options to use to parse the input expressions.
4900
4901    Returns:
4902        Or: the new condition
4903    """
4904    return _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 (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): 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, dialect=None, copy=True, **opts) -> sqlglot.expressions.Not:
4907def not_(expression, dialect=None, copy=True, **opts) -> Not:
4908    """
4909    Wrap a condition with a NOT operator.
4910
4911    Example:
4912        >>> not_("this_suit='black'").sql()
4913        "NOT this_suit = 'black'"
4914
4915    Args:
4916        expression (str | Expression): the SQL code strings to parse.
4917            If an Expression instance is passed, this is used as-is.
4918        dialect (str): the dialect used to parse the input expression.
4919        **opts: other options to use to parse the input expressions.
4920
4921    Returns:
4922        Not: the new condition
4923    """
4924    this = condition(
4925        expression,
4926        dialect=dialect,
4927        copy=copy,
4928        **opts,
4929    )
4930    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 (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Not: the new condition

def paren(expression, copy=True) -> sqlglot.expressions.Paren:
4933def paren(expression, copy=True) -> Paren:
4934    return Paren(this=_maybe_copy(expression, copy))
def to_identifier(name, quoted=None, copy=True):
4952def to_identifier(name, quoted=None, copy=True):
4953    """Builds an identifier.
4954
4955    Args:
4956        name: The name to turn into an identifier.
4957        quoted: Whether or not force quote the identifier.
4958        copy: Whether or not to copy a passed in Identefier node.
4959
4960    Returns:
4961        The identifier ast node.
4962    """
4963
4964    if name is None:
4965        return None
4966
4967    if isinstance(name, Identifier):
4968        identifier = _maybe_copy(name, copy)
4969    elif isinstance(name, str):
4970        identifier = Identifier(
4971            this=name,
4972            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4973        )
4974    else:
4975        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4976    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:
4982def to_interval(interval: str | Literal) -> Interval:
4983    """Builds an interval expression from a string like '1 day' or '5 months'."""
4984    if isinstance(interval, Literal):
4985        if not interval.is_string:
4986            raise ValueError("Invalid interval string.")
4987
4988        interval = interval.this
4989
4990    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4991
4992    if not interval_parts:
4993        raise ValueError("Invalid interval string.")
4994
4995    return Interval(
4996        this=Literal.string(interval_parts.group(1)),
4997        unit=Var(this=interval_parts.group(2)),
4998    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], **kwargs) -> Optional[sqlglot.expressions.Table]:
5011def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
5012    """
5013    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5014    If a table is passed in then that table is returned.
5015
5016    Args:
5017        sql_path: a `[catalog].[schema].[table]` string.
5018
5019    Returns:
5020        A table expression.
5021    """
5022    if sql_path is None or isinstance(sql_path, Table):
5023        return sql_path
5024    if not isinstance(sql_path, str):
5025        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5026
5027    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
5028    return Table(this=table_name, db=db, catalog=catalog, **kwargs)

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

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
5031def to_column(sql_path: str | Column, **kwargs) -> Column:
5032    """
5033    Create a column from a `[table].[column]` sql path. Schema is optional.
5034
5035    If a column is passed in then that column is returned.
5036
5037    Args:
5038        sql_path: `[table].[column]` string
5039    Returns:
5040        Table: A column expression
5041    """
5042    if sql_path is None or isinstance(sql_path, Column):
5043        return sql_path
5044    if not isinstance(sql_path, str):
5045        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5046    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):
5049def alias_(
5050    expression: ExpOrStr,
5051    alias: str | Identifier,
5052    table: bool | t.Sequence[str | Identifier] = False,
5053    quoted: t.Optional[bool] = None,
5054    dialect: DialectType = None,
5055    copy: bool = True,
5056    **opts,
5057):
5058    """Create an Alias expression.
5059
5060    Example:
5061        >>> alias_('foo', 'bar').sql()
5062        'foo AS bar'
5063
5064        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5065        '(SELECT 1, 2) AS bar(a, b)'
5066
5067    Args:
5068        expression: the SQL code strings to parse.
5069            If an Expression instance is passed, this is used as-is.
5070        alias: the alias name to use. If the name has
5071            special characters it is quoted.
5072        table: Whether or not to create a table alias, can also be a list of columns.
5073        quoted: whether or not to quote the alias
5074        dialect: the dialect used to parse the input expression.
5075        copy: Whether or not to copy the expression.
5076        **opts: other options to use to parse the input expressions.
5077
5078    Returns:
5079        Alias: the aliased expression
5080    """
5081    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5082    alias = to_identifier(alias, quoted=quoted)
5083
5084    if table:
5085        table_alias = TableAlias(this=alias)
5086        exp.set("alias", table_alias)
5087
5088        if not isinstance(table, bool):
5089            for column in table:
5090                table_alias.append("columns", to_identifier(column, quoted=quoted))
5091
5092        return exp
5093
5094    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5095    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5096    # for the complete Window expression.
5097    #
5098    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5099
5100    if "alias" in exp.arg_types and not isinstance(exp, Window):
5101        exp.set("alias", alias)
5102        return exp
5103    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, alias=None, dialect=None, **opts):
5106def subquery(expression, alias=None, dialect=None, **opts):
5107    """
5108    Build a subquery expression.
5109
5110    Example:
5111        >>> subquery('select x from tbl', 'bar').select('x').sql()
5112        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5113
5114    Args:
5115        expression (str | Expression): the SQL code strings to parse.
5116            If an Expression instance is passed, this is used as-is.
5117        alias (str | Expression): the alias name to use.
5118        dialect (str): the dialect used to parse the input expression.
5119        **opts: other options to use to parse the input expressions.
5120
5121    Returns:
5122        Select: a new select with the subquery expression included
5123    """
5124
5125    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5126    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 (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias (str | Expression): the alias name to use.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Select: a new select with the subquery expression included

def column( col: str | sqlglot.expressions.Identifier, table: Union[str, sqlglot.expressions.Identifier, NoneType] = None, db: Union[str, sqlglot.expressions.Identifier, NoneType] = None, catalog: Union[str, sqlglot.expressions.Identifier, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
5129def column(
5130    col: str | Identifier,
5131    table: t.Optional[str | Identifier] = None,
5132    db: t.Optional[str | Identifier] = None,
5133    catalog: t.Optional[str | Identifier] = None,
5134    quoted: t.Optional[bool] = None,
5135) -> Column:
5136    """
5137    Build a Column.
5138
5139    Args:
5140        col: column name
5141        table: table name
5142        db: db name
5143        catalog: catalog name
5144        quoted: whether or not to force quote each part
5145    Returns:
5146        Column: column instance
5147    """
5148    return Column(
5149        this=to_identifier(col, quoted=quoted),
5150        table=to_identifier(table, quoted=quoted),
5151        db=to_identifier(db, quoted=quoted),
5152        catalog=to_identifier(catalog, quoted=quoted),
5153    )

Build a Column.

Arguments:
  • col: column name
  • table: table name
  • db: db name
  • catalog: catalog name
  • quoted: whether or not to force quote each part
Returns:

Column: column instance

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
5156def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5157    """Cast an expression to a data type.
5158
5159    Example:
5160        >>> cast('x + 1', 'int').sql()
5161        'CAST(x + 1 AS INT)'
5162
5163    Args:
5164        expression: The expression to cast.
5165        to: The datatype to cast to.
5166
5167    Returns:
5168        A cast node.
5169    """
5170    expression = maybe_parse(expression, **opts)
5171    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:

A cast node.

def table_( table, db=None, catalog=None, quoted=None, alias=None) -> sqlglot.expressions.Table:
5174def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
5175    """Build a Table.
5176
5177    Args:
5178        table (str | Expression): column name
5179        db (str | Expression): db name
5180        catalog (str | Expression): catalog name
5181
5182    Returns:
5183        Table: table instance
5184    """
5185    return Table(
5186        this=to_identifier(table, quoted=quoted),
5187        db=to_identifier(db, quoted=quoted),
5188        catalog=to_identifier(catalog, quoted=quoted),
5189        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5190    )

Build a Table.

Arguments:
  • table (str | Expression): column name
  • db (str | Expression): db name
  • catalog (str | Expression): catalog name
Returns:

Table: 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:
5193def values(
5194    values: t.Iterable[t.Tuple[t.Any, ...]],
5195    alias: t.Optional[str] = None,
5196    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5197) -> Values:
5198    """Build VALUES statement.
5199
5200    Example:
5201        >>> values([(1, '2')]).sql()
5202        "VALUES (1, '2')"
5203
5204    Args:
5205        values: values statements that will be converted to SQL
5206        alias: optional alias
5207        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5208         If either are provided then an alias is also required.
5209
5210    Returns:
5211        Values: the Values expression object
5212    """
5213    if columns and not alias:
5214        raise ValueError("Alias is required when providing columns")
5215
5216    return Values(
5217        expressions=[convert(tup) for tup in values],
5218        alias=(
5219            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5220            if columns
5221            else (TableAlias(this=to_identifier(alias)) if alias else None)
5222        ),
5223    )

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:
5226def var(name: t.Optional[ExpOrStr]) -> Var:
5227    """Build a SQL variable.
5228
5229    Example:
5230        >>> repr(var('x'))
5231        '(VAR this: x)'
5232
5233        >>> repr(var(column('x', table='y')))
5234        '(VAR this: x)'
5235
5236    Args:
5237        name: The name of the var or an expression who's name will become the var.
5238
5239    Returns:
5240        The new variable node.
5241    """
5242    if not name:
5243        raise ValueError("Cannot convert empty name into var.")
5244
5245    if isinstance(name, Expression):
5246        name = name.name
5247    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:
5250def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5251    """Build ALTER TABLE... RENAME... expression
5252
5253    Args:
5254        old_name: The old name of the table
5255        new_name: The new name of the table
5256
5257    Returns:
5258        Alter table expression
5259    """
5260    old_table = to_table(old_name)
5261    new_table = to_table(new_name)
5262    return AlterTable(
5263        this=old_table,
5264        actions=[
5265            RenameTable(this=new_table),
5266        ],
5267    )

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:
5270def convert(value: t.Any, copy: bool = False) -> Expression:
5271    """Convert a python value into an expression object.
5272
5273    Raises an error if a conversion is not possible.
5274
5275    Args:
5276        value: A python object.
5277        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5278
5279    Returns:
5280        Expression: the equivalent expression object.
5281    """
5282    if isinstance(value, Expression):
5283        return _maybe_copy(value, copy)
5284    if isinstance(value, str):
5285        return Literal.string(value)
5286    if isinstance(value, bool):
5287        return Boolean(this=value)
5288    if value is None or (isinstance(value, float) and math.isnan(value)):
5289        return NULL
5290    if isinstance(value, numbers.Number):
5291        return Literal.number(value)
5292    if isinstance(value, datetime.datetime):
5293        datetime_literal = Literal.string(
5294            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5295        )
5296        return TimeStrToTime(this=datetime_literal)
5297    if isinstance(value, datetime.date):
5298        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5299        return DateStrToDate(this=date_literal)
5300    if isinstance(value, tuple):
5301        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5302    if isinstance(value, list):
5303        return Array(expressions=[convert(v, copy=copy) for v in value])
5304    if isinstance(value, dict):
5305        return Map(
5306            keys=[convert(k, copy=copy) for k in value],
5307            values=[convert(v, copy=copy) for v in value.values()],
5308        )
5309    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, fun, *args, **kwargs):
5312def replace_children(expression, fun, *args, **kwargs):
5313    """
5314    Replace children of an expression with the result of a lambda fun(child) -> exp.
5315    """
5316    for k, v in expression.args.items():
5317        is_list_arg = type(v) is list
5318
5319        child_nodes = v if is_list_arg else [v]
5320        new_child_nodes = []
5321
5322        for cn in child_nodes:
5323            if isinstance(cn, Expression):
5324                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5325                    new_child_nodes.append(child_node)
5326                    child_node.parent = expression
5327                    child_node.arg_key = k
5328            else:
5329                new_child_nodes.append(cn)
5330
5331        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):
5334def column_table_names(expression):
5335    """
5336    Return all table names referenced through columns in an expression.
5337
5338    Example:
5339        >>> import sqlglot
5340        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
5341        ['c', 'a']
5342
5343    Args:
5344        expression (sqlglot.Expression): expression to find table names
5345
5346    Returns:
5347        list: A list of unique names
5348    """
5349    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 (sqlglot.Expression): expression to find table names
Returns:

list: A list of unique names

def table_name(table) -> str:
5352def table_name(table) -> str:
5353    """Get the full name of a table as a string.
5354
5355    Args:
5356        table (exp.Table | str): table expression node or string.
5357
5358    Examples:
5359        >>> from sqlglot import exp, parse_one
5360        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5361        'a.b.c'
5362
5363    Returns:
5364        The table name.
5365    """
5366
5367    table = maybe_parse(table, into=Table)
5368
5369    if not table:
5370        raise ValueError(f"Cannot parse {table}")
5371
5372    return ".".join(
5373        part
5374        for part in (
5375            table.text("catalog"),
5376            table.text("db"),
5377            table.name,
5378        )
5379        if part
5380    )

Get the full name of a table as a string.

Arguments:
  • table (exp.Table | str): 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, mapping):
5383def replace_tables(expression, mapping):
5384    """Replace all tables in expression according to the mapping.
5385
5386    Args:
5387        expression (sqlglot.Expression): expression node to be transformed and replaced.
5388        mapping (Dict[str, str]): mapping of table names.
5389
5390    Examples:
5391        >>> from sqlglot import exp, parse_one
5392        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5393        'SELECT * FROM c'
5394
5395    Returns:
5396        The mapped expression.
5397    """
5398
5399    def _replace_tables(node):
5400        if isinstance(node, Table):
5401            new_name = mapping.get(table_name(node))
5402            if new_name:
5403                return to_table(
5404                    new_name,
5405                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5406                )
5407        return node
5408
5409    return expression.transform(_replace_tables)

Replace all tables in expression according to the mapping.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • mapping (Dict[str, str]): 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, *args, **kwargs):
5412def replace_placeholders(expression, *args, **kwargs):
5413    """Replace placeholders in an expression.
5414
5415    Args:
5416        expression (sqlglot.Expression): expression node to be transformed and replaced.
5417        args: positional names that will substitute unnamed placeholders in the given order.
5418        kwargs: keyword arguments that will substitute named placeholders.
5419
5420    Examples:
5421        >>> from sqlglot import exp, parse_one
5422        >>> replace_placeholders(
5423        ...     parse_one("select * from :tbl where ? = ?"),
5424        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5425        ... ).sql()
5426        "SELECT * FROM foo WHERE str_col = 'b'"
5427
5428    Returns:
5429        The mapped expression.
5430    """
5431
5432    def _replace_placeholders(node, args, **kwargs):
5433        if isinstance(node, Placeholder):
5434            if node.name:
5435                new_name = kwargs.get(node.name)
5436                if new_name:
5437                    return convert(new_name)
5438            else:
5439                try:
5440                    return convert(next(args))
5441                except StopIteration:
5442                    pass
5443        return node
5444
5445    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression (sqlglot.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:
5448def expand(
5449    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5450) -> Expression:
5451    """Transforms an expression by expanding all referenced sources into subqueries.
5452
5453    Examples:
5454        >>> from sqlglot import parse_one
5455        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5456        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5457
5458        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5459        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5460
5461    Args:
5462        expression: The expression to expand.
5463        sources: A dictionary of name to Subqueryables.
5464        copy: Whether or not to copy the expression during transformation. Defaults to True.
5465
5466    Returns:
5467        The transformed expression.
5468    """
5469
5470    def _expand(node: Expression):
5471        if isinstance(node, Table):
5472            name = table_name(node)
5473            source = sources.get(name)
5474            if source:
5475                subquery = source.subquery(node.alias or name)
5476                subquery.comments = [f"source: {name}"]
5477                return subquery.transform(_expand, copy=False)
5478        return node
5479
5480    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:
5483def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5484    """
5485    Returns a Func expression.
5486
5487    Examples:
5488        >>> func("abs", 5).sql()
5489        'ABS(5)'
5490
5491        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5492        'CAST(5 AS DOUBLE)'
5493
5494    Args:
5495        name: the name of the function to build.
5496        args: the args used to instantiate the function of interest.
5497        dialect: the source dialect.
5498        kwargs: the kwargs used to instantiate the function of interest.
5499
5500    Note:
5501        The arguments `args` and `kwargs` are mutually exclusive.
5502
5503    Returns:
5504        An instance of the function of interest, or an anonymous function, if `name` doesn't
5505        correspond to an existing `sqlglot.expressions.Func` class.
5506    """
5507    if args and kwargs:
5508        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5509
5510    from sqlglot.dialects.dialect import Dialect
5511
5512    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5513    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5514
5515    parser = Dialect.get_or_raise(dialect)().parser()
5516    from_args_list = parser.FUNCTIONS.get(name.upper())
5517
5518    if from_args_list:
5519        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5520    else:
5521        kwargs = kwargs or {"expressions": converted}
5522        function = Anonymous(this=name, **kwargs)
5523
5524    for error_message in function.error_messages(converted):
5525        raise ValueError(error_message)
5526
5527    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():
5530def true():
5531    """
5532    Returns a true Boolean expression.
5533    """
5534    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5537def false():
5538    """
5539    Returns a false Boolean expression.
5540    """
5541    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5544def null():
5545    """
5546    Returns a Null expression.
5547    """
5548    return Null()

Returns a Null expression.