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

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

class DerivedTable(Expression):
852class DerivedTable(Expression):
853    @property
854    def alias_column_names(self):
855        table_alias = self.args.get("alias")
856        if not table_alias:
857            return []
858        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
859        return [c.name for c in column_list]
860
861    @property
862    def selects(self):
863        return self.this.selects if isinstance(self.this, Subqueryable) else []
864
865    @property
866    def named_selects(self):
867        return [select.output_name for select in self.selects]
class Unionable(Expression):
870class Unionable(Expression):
871    def union(self, expression, distinct=True, dialect=None, **opts):
872        """
873        Builds a UNION expression.
874
875        Example:
876            >>> import sqlglot
877            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
878            'SELECT * FROM foo UNION SELECT * FROM bla'
879
880        Args:
881            expression (str | Expression): the SQL code string.
882                If an `Expression` instance is passed, it will be used as-is.
883            distinct (bool): set the DISTINCT flag if and only if this is true.
884            dialect (str): the dialect used to parse the input expression.
885            opts (kwargs): other options to use to parse the input expressions.
886        Returns:
887            Union: the Union expression.
888        """
889        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
890
891    def intersect(self, expression, distinct=True, dialect=None, **opts):
892        """
893        Builds an INTERSECT expression.
894
895        Example:
896            >>> import sqlglot
897            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
898            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
899
900        Args:
901            expression (str | Expression): the SQL code string.
902                If an `Expression` instance is passed, it will be used as-is.
903            distinct (bool): set the DISTINCT flag if and only if this is true.
904            dialect (str): the dialect used to parse the input expression.
905            opts (kwargs): other options to use to parse the input expressions.
906        Returns:
907            Intersect: the Intersect expression
908        """
909        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
910
911    def except_(self, expression, distinct=True, dialect=None, **opts):
912        """
913        Builds an EXCEPT expression.
914
915        Example:
916            >>> import sqlglot
917            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
918            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
919
920        Args:
921            expression (str | Expression): the SQL code string.
922                If an `Expression` instance is passed, it will be used as-is.
923            distinct (bool): set the DISTINCT flag if and only if this is true.
924            dialect (str): the dialect used to parse the input expression.
925            opts (kwargs): other options to use to parse the input expressions.
926        Returns:
927            Except: the Except expression
928        """
929        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
871    def union(self, expression, distinct=True, dialect=None, **opts):
872        """
873        Builds a UNION expression.
874
875        Example:
876            >>> import sqlglot
877            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
878            'SELECT * FROM foo UNION SELECT * FROM bla'
879
880        Args:
881            expression (str | Expression): the SQL code string.
882                If an `Expression` instance is passed, it will be used as-is.
883            distinct (bool): set the DISTINCT flag if and only if this is true.
884            dialect (str): the dialect used to parse the input expression.
885            opts (kwargs): other options to use to parse the input expressions.
886        Returns:
887            Union: the Union expression.
888        """
889        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):
891    def intersect(self, expression, distinct=True, dialect=None, **opts):
892        """
893        Builds an INTERSECT expression.
894
895        Example:
896            >>> import sqlglot
897            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
898            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
899
900        Args:
901            expression (str | Expression): the SQL code string.
902                If an `Expression` instance is passed, it will be used as-is.
903            distinct (bool): set the DISTINCT flag if and only if this is true.
904            dialect (str): the dialect used to parse the input expression.
905            opts (kwargs): other options to use to parse the input expressions.
906        Returns:
907            Intersect: the Intersect expression
908        """
909        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):
911    def except_(self, expression, distinct=True, dialect=None, **opts):
912        """
913        Builds an EXCEPT expression.
914
915        Example:
916            >>> import sqlglot
917            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
918            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
919
920        Args:
921            expression (str | Expression): the SQL code string.
922                If an `Expression` instance is passed, it will be used as-is.
923            distinct (bool): set the DISTINCT flag if and only if this is true.
924            dialect (str): the dialect used to parse the input expression.
925            opts (kwargs): other options to use to parse the input expressions.
926        Returns:
927            Except: the Except expression
928        """
929        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):
932class UDTF(DerivedTable, Unionable):
933    @property
934    def selects(self):
935        alias = self.args.get("alias")
936        return alias.columns if alias else []
class Cache(Expression):
939class Cache(Expression):
940    arg_types = {
941        "with": False,
942        "this": True,
943        "lazy": False,
944        "options": False,
945        "expression": False,
946    }
class Uncache(Expression):
949class Uncache(Expression):
950    arg_types = {"this": True, "exists": False}
class Create(Expression):
953class Create(Expression):
954    arg_types = {
955        "with": False,
956        "this": True,
957        "kind": True,
958        "expression": False,
959        "exists": False,
960        "properties": False,
961        "replace": False,
962        "unique": False,
963        "indexes": False,
964        "no_schema_binding": False,
965        "begin": False,
966        "clone": False,
967    }
class Clone(Expression):
971class Clone(Expression):
972    arg_types = {
973        "this": True,
974        "when": False,
975        "kind": False,
976        "expression": False,
977    }
class Describe(Expression):
980class Describe(Expression):
981    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
984class Pragma(Expression):
985    pass
class Set(Expression):
988class Set(Expression):
989    arg_types = {"expressions": False}
class SetItem(Expression):
992class SetItem(Expression):
993    arg_types = {
994        "this": False,
995        "expressions": False,
996        "kind": False,
997        "collate": False,  # MySQL SET NAMES statement
998        "global": False,
999    }
class Show(Expression):
1002class Show(Expression):
1003    arg_types = {
1004        "this": True,
1005        "target": False,
1006        "offset": False,
1007        "limit": False,
1008        "like": False,
1009        "where": False,
1010        "db": False,
1011        "full": False,
1012        "mutex": False,
1013        "query": False,
1014        "channel": False,
1015        "global": False,
1016        "log": False,
1017        "position": False,
1018        "types": False,
1019    }
class UserDefinedFunction(Expression):
1022class UserDefinedFunction(Expression):
1023    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
1026class CharacterSet(Expression):
1027    arg_types = {"this": True, "default": False}
class With(Expression):
1030class With(Expression):
1031    arg_types = {"expressions": True, "recursive": False}
1032
1033    @property
1034    def recursive(self) -> bool:
1035        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
1038class WithinGroup(Expression):
1039    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
1042class CTE(DerivedTable):
1043    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
1046class TableAlias(Expression):
1047    arg_types = {"this": False, "columns": False}
1048
1049    @property
1050    def columns(self):
1051        return self.args.get("columns") or []
class BitString(Condition):
1054class BitString(Condition):
1055    pass
class HexString(Condition):
1058class HexString(Condition):
1059    pass
class ByteString(Condition):
1062class ByteString(Condition):
1063    pass
class Column(Condition):
1066class Column(Condition):
1067    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1068
1069    @property
1070    def table(self) -> str:
1071        return self.text("table")
1072
1073    @property
1074    def db(self) -> str:
1075        return self.text("db")
1076
1077    @property
1078    def catalog(self) -> str:
1079        return self.text("catalog")
1080
1081    @property
1082    def output_name(self) -> str:
1083        return self.name
1084
1085    @property
1086    def parts(self) -> t.List[Identifier]:
1087        """Return the parts of a column in order catalog, db, table, name."""
1088        return [
1089            t.cast(Identifier, self.args[part])
1090            for part in ("catalog", "db", "table", "this")
1091            if self.args.get(part)
1092        ]
1093
1094    def to_dot(self) -> Dot:
1095        """Converts the column into a dot expression."""
1096        parts = self.parts
1097        parent = self.parent
1098
1099        while parent:
1100            if isinstance(parent, Dot):
1101                parts.append(parent.expression)
1102            parent = parent.parent
1103
1104        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:
1094    def to_dot(self) -> Dot:
1095        """Converts the column into a dot expression."""
1096        parts = self.parts
1097        parent = self.parent
1098
1099        while parent:
1100            if isinstance(parent, Dot):
1101                parts.append(parent.expression)
1102            parent = parent.parent
1103
1104        return Dot.build(parts)

Converts the column into a dot expression.

class ColumnPosition(Expression):
1107class ColumnPosition(Expression):
1108    arg_types = {"this": False, "position": True}
class ColumnDef(Expression):
1111class ColumnDef(Expression):
1112    arg_types = {
1113        "this": True,
1114        "kind": False,
1115        "constraints": False,
1116        "exists": False,
1117        "position": False,
1118    }
1119
1120    @property
1121    def constraints(self) -> t.List[ColumnConstraint]:
1122        return self.args.get("constraints") or []
class AlterColumn(Expression):
1125class AlterColumn(Expression):
1126    arg_types = {
1127        "this": True,
1128        "dtype": False,
1129        "collate": False,
1130        "using": False,
1131        "default": False,
1132        "drop": False,
1133    }
class RenameTable(Expression):
1136class RenameTable(Expression):
1137    pass
class SetTag(Expression):
1140class SetTag(Expression):
1141    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
1144class Comment(Expression):
1145    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class MergeTreeTTLAction(Expression):
1149class MergeTreeTTLAction(Expression):
1150    arg_types = {
1151        "this": True,
1152        "delete": False,
1153        "recompress": False,
1154        "to_disk": False,
1155        "to_volume": False,
1156    }
class MergeTreeTTL(Expression):
1160class MergeTreeTTL(Expression):
1161    arg_types = {
1162        "expressions": True,
1163        "where": False,
1164        "group": False,
1165        "aggregates": False,
1166    }
class ColumnConstraint(Expression):
1169class ColumnConstraint(Expression):
1170    arg_types = {"this": False, "kind": True}
1171
1172    @property
1173    def kind(self) -> ColumnConstraintKind:
1174        return self.args["kind"]
class ColumnConstraintKind(Expression):
1177class ColumnConstraintKind(Expression):
1178    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1181class AutoIncrementColumnConstraint(ColumnConstraintKind):
1182    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1185class CaseSpecificColumnConstraint(ColumnConstraintKind):
1186    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1189class CharacterSetColumnConstraint(ColumnConstraintKind):
1190    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1193class CheckColumnConstraint(ColumnConstraintKind):
1194    pass
class CollateColumnConstraint(ColumnConstraintKind):
1197class CollateColumnConstraint(ColumnConstraintKind):
1198    pass
class CommentColumnConstraint(ColumnConstraintKind):
1201class CommentColumnConstraint(ColumnConstraintKind):
1202    pass
class CompressColumnConstraint(ColumnConstraintKind):
1205class CompressColumnConstraint(ColumnConstraintKind):
1206    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1209class DateFormatColumnConstraint(ColumnConstraintKind):
1210    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1213class DefaultColumnConstraint(ColumnConstraintKind):
1214    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1217class EncodeColumnConstraint(ColumnConstraintKind):
1218    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1221class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1222    # this: True -> ALWAYS, this: False -> BY DEFAULT
1223    arg_types = {
1224        "this": False,
1225        "on_null": False,
1226        "start": False,
1227        "increment": False,
1228        "minvalue": False,
1229        "maxvalue": False,
1230        "cycle": False,
1231    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1234class InlineLengthColumnConstraint(ColumnConstraintKind):
1235    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1238class NotNullColumnConstraint(ColumnConstraintKind):
1239    arg_types = {"allow_null": False}
class OnUpdateColumnConstraint(ColumnConstraintKind):
1243class OnUpdateColumnConstraint(ColumnConstraintKind):
1244    pass
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1247class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1248    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1251class TitleColumnConstraint(ColumnConstraintKind):
1252    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1255class UniqueColumnConstraint(ColumnConstraintKind):
1256    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1259class UppercaseColumnConstraint(ColumnConstraintKind):
1260    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1263class PathColumnConstraint(ColumnConstraintKind):
1264    pass
class Constraint(Expression):
1267class Constraint(Expression):
1268    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1271class Delete(Expression):
1272    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1273
1274    def delete(
1275        self,
1276        table: ExpOrStr,
1277        dialect: DialectType = None,
1278        copy: bool = True,
1279        **opts,
1280    ) -> Delete:
1281        """
1282        Create a DELETE expression or replace the table on an existing DELETE expression.
1283
1284        Example:
1285            >>> delete("tbl").sql()
1286            'DELETE FROM tbl'
1287
1288        Args:
1289            table: the table from which to delete.
1290            dialect: the dialect used to parse the input expression.
1291            copy: if `False`, modify this expression instance in-place.
1292            opts: other options to use to parse the input expressions.
1293
1294        Returns:
1295            Delete: the modified expression.
1296        """
1297        return _apply_builder(
1298            expression=table,
1299            instance=self,
1300            arg="this",
1301            dialect=dialect,
1302            into=Table,
1303            copy=copy,
1304            **opts,
1305        )
1306
1307    def where(
1308        self,
1309        *expressions: ExpOrStr,
1310        append: bool = True,
1311        dialect: DialectType = None,
1312        copy: bool = True,
1313        **opts,
1314    ) -> Delete:
1315        """
1316        Append to or set the WHERE expressions.
1317
1318        Example:
1319            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1320            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1321
1322        Args:
1323            *expressions: the SQL code strings to parse.
1324                If an `Expression` instance is passed, it will be used as-is.
1325                Multiple expressions are combined with an AND operator.
1326            append: if `True`, AND the new expressions to any existing expression.
1327                Otherwise, this resets the expression.
1328            dialect: the dialect used to parse the input expressions.
1329            copy: if `False`, modify this expression instance in-place.
1330            opts: other options to use to parse the input expressions.
1331
1332        Returns:
1333            Delete: the modified expression.
1334        """
1335        return _apply_conjunction_builder(
1336            *expressions,
1337            instance=self,
1338            arg="where",
1339            append=append,
1340            into=Where,
1341            dialect=dialect,
1342            copy=copy,
1343            **opts,
1344        )
1345
1346    def returning(
1347        self,
1348        expression: ExpOrStr,
1349        dialect: DialectType = None,
1350        copy: bool = True,
1351        **opts,
1352    ) -> Delete:
1353        """
1354        Set the RETURNING expression. Not supported by all dialects.
1355
1356        Example:
1357            >>> delete("tbl").returning("*", dialect="postgres").sql()
1358            'DELETE FROM tbl RETURNING *'
1359
1360        Args:
1361            expression: the SQL code strings to parse.
1362                If an `Expression` instance is passed, it will be used as-is.
1363            dialect: the dialect used to parse the input expressions.
1364            copy: if `False`, modify this expression instance in-place.
1365            opts: other options to use to parse the input expressions.
1366
1367        Returns:
1368            Delete: the modified expression.
1369        """
1370        return _apply_builder(
1371            expression=expression,
1372            instance=self,
1373            arg="returning",
1374            prefix="RETURNING",
1375            dialect=dialect,
1376            copy=copy,
1377            into=Returning,
1378            **opts,
1379        )
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:
1274    def delete(
1275        self,
1276        table: ExpOrStr,
1277        dialect: DialectType = None,
1278        copy: bool = True,
1279        **opts,
1280    ) -> Delete:
1281        """
1282        Create a DELETE expression or replace the table on an existing DELETE expression.
1283
1284        Example:
1285            >>> delete("tbl").sql()
1286            'DELETE FROM tbl'
1287
1288        Args:
1289            table: the table from which to delete.
1290            dialect: the dialect used to parse the input expression.
1291            copy: if `False`, modify this expression instance in-place.
1292            opts: other options to use to parse the input expressions.
1293
1294        Returns:
1295            Delete: the modified expression.
1296        """
1297        return _apply_builder(
1298            expression=table,
1299            instance=self,
1300            arg="this",
1301            dialect=dialect,
1302            into=Table,
1303            copy=copy,
1304            **opts,
1305        )

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:
1307    def where(
1308        self,
1309        *expressions: ExpOrStr,
1310        append: bool = True,
1311        dialect: DialectType = None,
1312        copy: bool = True,
1313        **opts,
1314    ) -> Delete:
1315        """
1316        Append to or set the WHERE expressions.
1317
1318        Example:
1319            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1320            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1321
1322        Args:
1323            *expressions: the SQL code strings to parse.
1324                If an `Expression` instance is passed, it will be used as-is.
1325                Multiple expressions are combined with an AND operator.
1326            append: if `True`, AND the new expressions to any existing expression.
1327                Otherwise, this resets the expression.
1328            dialect: the dialect used to parse the input expressions.
1329            copy: if `False`, modify this expression instance in-place.
1330            opts: other options to use to parse the input expressions.
1331
1332        Returns:
1333            Delete: the modified expression.
1334        """
1335        return _apply_conjunction_builder(
1336            *expressions,
1337            instance=self,
1338            arg="where",
1339            append=append,
1340            into=Where,
1341            dialect=dialect,
1342            copy=copy,
1343            **opts,
1344        )

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:
1346    def returning(
1347        self,
1348        expression: ExpOrStr,
1349        dialect: DialectType = None,
1350        copy: bool = True,
1351        **opts,
1352    ) -> Delete:
1353        """
1354        Set the RETURNING expression. Not supported by all dialects.
1355
1356        Example:
1357            >>> delete("tbl").returning("*", dialect="postgres").sql()
1358            'DELETE FROM tbl RETURNING *'
1359
1360        Args:
1361            expression: the SQL code strings to parse.
1362                If an `Expression` instance is passed, it will be used as-is.
1363            dialect: the dialect used to parse the input expressions.
1364            copy: if `False`, modify this expression instance in-place.
1365            opts: other options to use to parse the input expressions.
1366
1367        Returns:
1368            Delete: the modified expression.
1369        """
1370        return _apply_builder(
1371            expression=expression,
1372            instance=self,
1373            arg="returning",
1374            prefix="RETURNING",
1375            dialect=dialect,
1376            copy=copy,
1377            into=Returning,
1378            **opts,
1379        )

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):
1382class Drop(Expression):
1383    arg_types = {
1384        "this": False,
1385        "kind": False,
1386        "exists": False,
1387        "temporary": False,
1388        "materialized": False,
1389        "cascade": False,
1390        "constraints": False,
1391        "purge": False,
1392    }
class Filter(Expression):
1395class Filter(Expression):
1396    arg_types = {"this": True, "expression": True}
class Check(Expression):
1399class Check(Expression):
1400    pass
class Directory(Expression):
1403class Directory(Expression):
1404    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1405    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1408class ForeignKey(Expression):
1409    arg_types = {
1410        "expressions": True,
1411        "reference": False,
1412        "delete": False,
1413        "update": False,
1414    }
class PrimaryKey(Expression):
1417class PrimaryKey(Expression):
1418    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1421class Unique(Expression):
1422    arg_types = {"expressions": True}
class Into(Expression):
1427class Into(Expression):
1428    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1431class From(Expression):
1432    @property
1433    def name(self) -> str:
1434        return self.this.name
1435
1436    @property
1437    def alias_or_name(self) -> str:
1438        return self.this.alias_or_name
class Having(Expression):
1441class Having(Expression):
1442    pass
class Hint(Expression):
1445class Hint(Expression):
1446    arg_types = {"expressions": True}
class JoinHint(Expression):
1449class JoinHint(Expression):
1450    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1453class Identifier(Expression):
1454    arg_types = {"this": True, "quoted": False}
1455
1456    @property
1457    def quoted(self):
1458        return bool(self.args.get("quoted"))
1459
1460    @property
1461    def hashable_args(self) -> t.Any:
1462        if self.quoted and any(char.isupper() for char in self.this):
1463            return (self.this, self.quoted)
1464        return self.this.lower()
1465
1466    @property
1467    def output_name(self):
1468        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):
1471class Index(Expression):
1472    arg_types = {
1473        "this": False,
1474        "table": False,
1475        "where": False,
1476        "columns": False,
1477        "unique": False,
1478        "primary": False,
1479        "amp": False,  # teradata
1480    }
class Insert(Expression):
1483class Insert(Expression):
1484    arg_types = {
1485        "with": False,
1486        "this": True,
1487        "expression": False,
1488        "conflict": False,
1489        "returning": False,
1490        "overwrite": False,
1491        "exists": False,
1492        "partition": False,
1493        "alternative": False,
1494    }
1495
1496    def with_(
1497        self,
1498        alias: ExpOrStr,
1499        as_: ExpOrStr,
1500        recursive: t.Optional[bool] = None,
1501        append: bool = True,
1502        dialect: DialectType = None,
1503        copy: bool = True,
1504        **opts,
1505    ) -> Insert:
1506        """
1507        Append to or set the common table expressions.
1508
1509        Example:
1510            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1511            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1512
1513        Args:
1514            alias: the SQL code string to parse as the table name.
1515                If an `Expression` instance is passed, this is used as-is.
1516            as_: the SQL code string to parse as the table expression.
1517                If an `Expression` instance is passed, it will be used as-is.
1518            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1519            append: if `True`, add to any existing expressions.
1520                Otherwise, this resets the expressions.
1521            dialect: the dialect used to parse the input expression.
1522            copy: if `False`, modify this expression instance in-place.
1523            opts: other options to use to parse the input expressions.
1524
1525        Returns:
1526            The modified expression.
1527        """
1528        return _apply_cte_builder(
1529            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1530        )
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:
1496    def with_(
1497        self,
1498        alias: ExpOrStr,
1499        as_: ExpOrStr,
1500        recursive: t.Optional[bool] = None,
1501        append: bool = True,
1502        dialect: DialectType = None,
1503        copy: bool = True,
1504        **opts,
1505    ) -> Insert:
1506        """
1507        Append to or set the common table expressions.
1508
1509        Example:
1510            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1511            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1512
1513        Args:
1514            alias: the SQL code string to parse as the table name.
1515                If an `Expression` instance is passed, this is used as-is.
1516            as_: the SQL code string to parse as the table expression.
1517                If an `Expression` instance is passed, it will be used as-is.
1518            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1519            append: if `True`, add to any existing expressions.
1520                Otherwise, this resets the expressions.
1521            dialect: the dialect used to parse the input expression.
1522            copy: if `False`, modify this expression instance in-place.
1523            opts: other options to use to parse the input expressions.
1524
1525        Returns:
1526            The modified expression.
1527        """
1528        return _apply_cte_builder(
1529            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1530        )

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):
1533class OnConflict(Expression):
1534    arg_types = {
1535        "duplicate": False,
1536        "expressions": False,
1537        "nothing": False,
1538        "key": False,
1539        "constraint": False,
1540    }
class Returning(Expression):
1543class Returning(Expression):
1544    arg_types = {"expressions": True}
class Introducer(Expression):
1548class Introducer(Expression):
1549    arg_types = {"this": True, "expression": True}
class National(Expression):
1553class National(Expression):
1554    pass
class LoadData(Expression):
1557class LoadData(Expression):
1558    arg_types = {
1559        "this": True,
1560        "local": False,
1561        "overwrite": False,
1562        "inpath": True,
1563        "partition": False,
1564        "input_format": False,
1565        "serde": False,
1566    }
class Partition(Expression):
1569class Partition(Expression):
1570    arg_types = {"expressions": True}
class Fetch(Expression):
1573class Fetch(Expression):
1574    arg_types = {
1575        "direction": False,
1576        "count": False,
1577        "percent": False,
1578        "with_ties": False,
1579    }
class Group(Expression):
1582class Group(Expression):
1583    arg_types = {
1584        "expressions": False,
1585        "grouping_sets": False,
1586        "cube": False,
1587        "rollup": False,
1588        "totals": False,
1589    }
class Lambda(Expression):
1592class Lambda(Expression):
1593    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1596class Limit(Expression):
1597    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1600class Literal(Condition):
1601    arg_types = {"this": True, "is_string": True}
1602
1603    @property
1604    def hashable_args(self) -> t.Any:
1605        return (self.this, self.args.get("is_string"))
1606
1607    @classmethod
1608    def number(cls, number) -> Literal:
1609        return cls(this=str(number), is_string=False)
1610
1611    @classmethod
1612    def string(cls, string) -> Literal:
1613        return cls(this=str(string), is_string=True)
1614
1615    @property
1616    def output_name(self):
1617        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1607    @classmethod
1608    def number(cls, number) -> Literal:
1609        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1611    @classmethod
1612    def string(cls, string) -> Literal:
1613        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):
1620class Join(Expression):
1621    arg_types = {
1622        "this": True,
1623        "on": False,
1624        "side": False,
1625        "kind": False,
1626        "using": False,
1627        "natural": False,
1628        "global": False,
1629        "hint": False,
1630    }
1631
1632    @property
1633    def kind(self):
1634        return self.text("kind").upper()
1635
1636    @property
1637    def side(self):
1638        return self.text("side").upper()
1639
1640    @property
1641    def hint(self):
1642        return self.text("hint").upper()
1643
1644    @property
1645    def alias_or_name(self):
1646        return self.this.alias_or_name
1647
1648    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1649        """
1650        Append to or set the ON expressions.
1651
1652        Example:
1653            >>> import sqlglot
1654            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1655            'JOIN x ON y = 1'
1656
1657        Args:
1658            *expressions (str | Expression): the SQL code strings to parse.
1659                If an `Expression` instance is passed, it will be used as-is.
1660                Multiple expressions are combined with an AND operator.
1661            append (bool): if `True`, AND the new expressions to any existing expression.
1662                Otherwise, this resets the expression.
1663            dialect (str): the dialect used to parse the input expressions.
1664            copy (bool): if `False`, modify this expression instance in-place.
1665            opts (kwargs): other options to use to parse the input expressions.
1666
1667        Returns:
1668            Join: the modified join expression.
1669        """
1670        join = _apply_conjunction_builder(
1671            *expressions,
1672            instance=self,
1673            arg="on",
1674            append=append,
1675            dialect=dialect,
1676            copy=copy,
1677            **opts,
1678        )
1679
1680        if join.kind == "CROSS":
1681            join.set("kind", None)
1682
1683        return join
1684
1685    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1686        """
1687        Append to or set the USING expressions.
1688
1689        Example:
1690            >>> import sqlglot
1691            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1692            'JOIN x USING (foo, bla)'
1693
1694        Args:
1695            *expressions (str | Expression): the SQL code strings to parse.
1696                If an `Expression` instance is passed, it will be used as-is.
1697            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1698                Otherwise, this resets the expression.
1699            dialect (str): the dialect used to parse the input expressions.
1700            copy (bool): if `False`, modify this expression instance in-place.
1701            opts (kwargs): other options to use to parse the input expressions.
1702
1703        Returns:
1704            Join: the modified join expression.
1705        """
1706        join = _apply_list_builder(
1707            *expressions,
1708            instance=self,
1709            arg="using",
1710            append=append,
1711            dialect=dialect,
1712            copy=copy,
1713            **opts,
1714        )
1715
1716        if join.kind == "CROSS":
1717            join.set("kind", None)
1718
1719        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1648    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1649        """
1650        Append to or set the ON expressions.
1651
1652        Example:
1653            >>> import sqlglot
1654            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1655            'JOIN x ON y = 1'
1656
1657        Args:
1658            *expressions (str | Expression): the SQL code strings to parse.
1659                If an `Expression` instance is passed, it will be used as-is.
1660                Multiple expressions are combined with an AND operator.
1661            append (bool): if `True`, AND the new expressions to any existing expression.
1662                Otherwise, this resets the expression.
1663            dialect (str): the dialect used to parse the input expressions.
1664            copy (bool): if `False`, modify this expression instance in-place.
1665            opts (kwargs): other options to use to parse the input expressions.
1666
1667        Returns:
1668            Join: the modified join expression.
1669        """
1670        join = _apply_conjunction_builder(
1671            *expressions,
1672            instance=self,
1673            arg="on",
1674            append=append,
1675            dialect=dialect,
1676            copy=copy,
1677            **opts,
1678        )
1679
1680        if join.kind == "CROSS":
1681            join.set("kind", None)
1682
1683        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):
1685    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1686        """
1687        Append to or set the USING expressions.
1688
1689        Example:
1690            >>> import sqlglot
1691            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1692            'JOIN x USING (foo, bla)'
1693
1694        Args:
1695            *expressions (str | Expression): the SQL code strings to parse.
1696                If an `Expression` instance is passed, it will be used as-is.
1697            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1698                Otherwise, this resets the expression.
1699            dialect (str): the dialect used to parse the input expressions.
1700            copy (bool): if `False`, modify this expression instance in-place.
1701            opts (kwargs): other options to use to parse the input expressions.
1702
1703        Returns:
1704            Join: the modified join expression.
1705        """
1706        join = _apply_list_builder(
1707            *expressions,
1708            instance=self,
1709            arg="using",
1710            append=append,
1711            dialect=dialect,
1712            copy=copy,
1713            **opts,
1714        )
1715
1716        if join.kind == "CROSS":
1717            join.set("kind", None)
1718
1719        return join

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):
1722class Lateral(UDTF):
1723    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1726class MatchRecognize(Expression):
1727    arg_types = {
1728        "partition_by": False,
1729        "order": False,
1730        "measures": False,
1731        "rows": False,
1732        "after": False,
1733        "pattern": False,
1734        "define": False,
1735        "alias": False,
1736    }
class Final(Expression):
1741class Final(Expression):
1742    pass
class Offset(Expression):
1745class Offset(Expression):
1746    arg_types = {"this": False, "expression": True}
class Order(Expression):
1749class Order(Expression):
1750    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1755class Cluster(Order):
1756    pass
class Distribute(Order):
1759class Distribute(Order):
1760    pass
class Sort(Order):
1763class Sort(Order):
1764    pass
class Ordered(Expression):
1767class Ordered(Expression):
1768    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1771class Property(Expression):
1772    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1775class AfterJournalProperty(Property):
1776    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1779class AlgorithmProperty(Property):
1780    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1783class AutoIncrementProperty(Property):
1784    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1787class BlockCompressionProperty(Property):
1788    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1791class CharacterSetProperty(Property):
1792    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1795class ChecksumProperty(Property):
1796    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1799class CollateProperty(Property):
1800    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1803class DataBlocksizeProperty(Property):
1804    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1807class DefinerProperty(Property):
1808    arg_types = {"this": True}
class DistKeyProperty(Property):
1811class DistKeyProperty(Property):
1812    arg_types = {"this": True}
class DistStyleProperty(Property):
1815class DistStyleProperty(Property):
1816    arg_types = {"this": True}
class EngineProperty(Property):
1819class EngineProperty(Property):
1820    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1823class ExecuteAsProperty(Property):
1824    arg_types = {"this": True}
class ExternalProperty(Property):
1827class ExternalProperty(Property):
1828    arg_types = {"this": False}
class FallbackProperty(Property):
1831class FallbackProperty(Property):
1832    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1835class FileFormatProperty(Property):
1836    arg_types = {"this": True}
class FreespaceProperty(Property):
1839class FreespaceProperty(Property):
1840    arg_types = {"this": True, "percent": False}
class InputOutputFormat(Expression):
1843class InputOutputFormat(Expression):
1844    arg_types = {"input_format": False, "output_format": False}
class IsolatedLoadingProperty(Property):
1847class IsolatedLoadingProperty(Property):
1848    arg_types = {
1849        "no": True,
1850        "concurrent": True,
1851        "for_all": True,
1852        "for_insert": True,
1853        "for_none": True,
1854    }
class JournalProperty(Property):
1857class JournalProperty(Property):
1858    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1861class LanguageProperty(Property):
1862    arg_types = {"this": True}
class LikeProperty(Property):
1865class LikeProperty(Property):
1866    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1869class LocationProperty(Property):
1870    arg_types = {"this": True}
class LockingProperty(Property):
1873class LockingProperty(Property):
1874    arg_types = {
1875        "this": False,
1876        "kind": True,
1877        "for_or_in": True,
1878        "lock_type": True,
1879        "override": False,
1880    }
class LogProperty(Property):
1883class LogProperty(Property):
1884    arg_types = {"no": True}
class MaterializedProperty(Property):
1887class MaterializedProperty(Property):
1888    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1891class MergeBlockRatioProperty(Property):
1892    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1895class NoPrimaryIndexProperty(Property):
1896    arg_types = {"this": False}
class OnCommitProperty(Property):
1899class OnCommitProperty(Property):
1900    arg_type = {"this": False}
class PartitionedByProperty(Property):
1903class PartitionedByProperty(Property):
1904    arg_types = {"this": True}
class ReturnsProperty(Property):
1907class ReturnsProperty(Property):
1908    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatProperty(Property):
1911class RowFormatProperty(Property):
1912    arg_types = {"this": True}
class RowFormatDelimitedProperty(Property):
1915class RowFormatDelimitedProperty(Property):
1916    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1917    arg_types = {
1918        "fields": False,
1919        "escaped": False,
1920        "collection_items": False,
1921        "map_keys": False,
1922        "lines": False,
1923        "null": False,
1924        "serde": False,
1925    }
class RowFormatSerdeProperty(Property):
1928class RowFormatSerdeProperty(Property):
1929    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1932class SchemaCommentProperty(Property):
1933    arg_types = {"this": True}
class SerdeProperties(Property):
1936class SerdeProperties(Property):
1937    arg_types = {"expressions": True}
class SetProperty(Property):
1940class SetProperty(Property):
1941    arg_types = {"multi": True}
class SettingsProperty(Property):
1944class SettingsProperty(Property):
1945    arg_types = {"expressions": True}
class SortKeyProperty(Property):
1948class SortKeyProperty(Property):
1949    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1952class SqlSecurityProperty(Property):
1953    arg_types = {"definer": True}
class StabilityProperty(Property):
1956class StabilityProperty(Property):
1957    arg_types = {"this": True}
class TemporaryProperty(Property):
1960class TemporaryProperty(Property):
1961    arg_types = {"global_": True}
class TransientProperty(Property):
1964class TransientProperty(Property):
1965    arg_types = {"this": False}
class VolatileProperty(Property):
1968class VolatileProperty(Property):
1969    arg_types = {"this": False}
class WithDataProperty(Property):
1972class WithDataProperty(Property):
1973    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1976class WithJournalTableProperty(Property):
1977    arg_types = {"this": True}
class Properties(Expression):
1980class Properties(Expression):
1981    arg_types = {"expressions": True}
1982
1983    NAME_TO_PROPERTY = {
1984        "ALGORITHM": AlgorithmProperty,
1985        "AUTO_INCREMENT": AutoIncrementProperty,
1986        "CHARACTER SET": CharacterSetProperty,
1987        "COLLATE": CollateProperty,
1988        "COMMENT": SchemaCommentProperty,
1989        "DEFINER": DefinerProperty,
1990        "DISTKEY": DistKeyProperty,
1991        "DISTSTYLE": DistStyleProperty,
1992        "ENGINE": EngineProperty,
1993        "EXECUTE AS": ExecuteAsProperty,
1994        "FORMAT": FileFormatProperty,
1995        "LANGUAGE": LanguageProperty,
1996        "LOCATION": LocationProperty,
1997        "PARTITIONED_BY": PartitionedByProperty,
1998        "RETURNS": ReturnsProperty,
1999        "ROW_FORMAT": RowFormatProperty,
2000        "SORTKEY": SortKeyProperty,
2001    }
2002
2003    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2004
2005    # CREATE property locations
2006    # Form: schema specified
2007    #   create [POST_CREATE]
2008    #     table a [POST_NAME]
2009    #     (b int) [POST_SCHEMA]
2010    #     with ([POST_WITH])
2011    #     index (b) [POST_INDEX]
2012    #
2013    # Form: alias selection
2014    #   create [POST_CREATE]
2015    #     table a [POST_NAME]
2016    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2017    #     index (c) [POST_INDEX]
2018    class Location(AutoName):
2019        POST_CREATE = auto()
2020        POST_NAME = auto()
2021        POST_SCHEMA = auto()
2022        POST_WITH = auto()
2023        POST_ALIAS = auto()
2024        POST_EXPRESSION = auto()
2025        POST_INDEX = auto()
2026        UNSUPPORTED = auto()
2027
2028    @classmethod
2029    def from_dict(cls, properties_dict) -> Properties:
2030        expressions = []
2031        for key, value in properties_dict.items():
2032            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2033            if property_cls:
2034                expressions.append(property_cls(this=convert(value)))
2035            else:
2036                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2037
2038        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
2028    @classmethod
2029    def from_dict(cls, properties_dict) -> Properties:
2030        expressions = []
2031        for key, value in properties_dict.items():
2032            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2033            if property_cls:
2034                expressions.append(property_cls(this=convert(value)))
2035            else:
2036                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2037
2038        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
2018    class Location(AutoName):
2019        POST_CREATE = auto()
2020        POST_NAME = auto()
2021        POST_SCHEMA = auto()
2022        POST_WITH = auto()
2023        POST_ALIAS = auto()
2024        POST_EXPRESSION = auto()
2025        POST_INDEX = auto()
2026        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):
2041class Qualify(Expression):
2042    pass
class Return(Expression):
2046class Return(Expression):
2047    pass
class Reference(Expression):
2050class Reference(Expression):
2051    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
2054class Tuple(Expression):
2055    arg_types = {"expressions": False}
2056
2057    def isin(
2058        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
2059    ) -> In:
2060        return In(
2061            this=_maybe_copy(self, copy),
2062            expressions=[convert(e, copy=copy) for e in expressions],
2063            query=maybe_parse(query, copy=copy, **opts) if query else None,
2064        )
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy=True, **opts) -> sqlglot.expressions.In:
2057    def isin(
2058        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
2059    ) -> In:
2060        return In(
2061            this=_maybe_copy(self, copy),
2062            expressions=[convert(e, copy=copy) for e in expressions],
2063            query=maybe_parse(query, copy=copy, **opts) if query else None,
2064        )
class Subqueryable(Unionable):
2067class Subqueryable(Unionable):
2068    def subquery(self, alias=None, copy=True) -> Subquery:
2069        """
2070        Convert this expression to an aliased expression that can be used as a Subquery.
2071
2072        Example:
2073            >>> subquery = Select().select("x").from_("tbl").subquery()
2074            >>> Select().select("x").from_(subquery).sql()
2075            'SELECT x FROM (SELECT x FROM tbl)'
2076
2077        Args:
2078            alias (str | Identifier): an optional alias for the subquery
2079            copy (bool): if `False`, modify this expression instance in-place.
2080
2081        Returns:
2082            Alias: the subquery
2083        """
2084        instance = _maybe_copy(self, copy)
2085        if not isinstance(alias, Expression):
2086            alias = TableAlias(this=to_identifier(alias)) if alias else None
2087
2088        return Subquery(this=instance, alias=alias)
2089
2090    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2091        raise NotImplementedError
2092
2093    @property
2094    def ctes(self):
2095        with_ = self.args.get("with")
2096        if not with_:
2097            return []
2098        return with_.expressions
2099
2100    @property
2101    def selects(self):
2102        raise NotImplementedError("Subqueryable objects must implement `selects`")
2103
2104    @property
2105    def named_selects(self):
2106        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2107
2108    def with_(
2109        self,
2110        alias: ExpOrStr,
2111        as_: ExpOrStr,
2112        recursive: t.Optional[bool] = None,
2113        append: bool = True,
2114        dialect: DialectType = None,
2115        copy: bool = True,
2116        **opts,
2117    ) -> Subqueryable:
2118        """
2119        Append to or set the common table expressions.
2120
2121        Example:
2122            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2123            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2124
2125        Args:
2126            alias: the SQL code string to parse as the table name.
2127                If an `Expression` instance is passed, this is used as-is.
2128            as_: the SQL code string to parse as the table expression.
2129                If an `Expression` instance is passed, it will be used as-is.
2130            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2131            append: if `True`, add to any existing expressions.
2132                Otherwise, this resets the expressions.
2133            dialect: the dialect used to parse the input expression.
2134            copy: if `False`, modify this expression instance in-place.
2135            opts: other options to use to parse the input expressions.
2136
2137        Returns:
2138            The modified expression.
2139        """
2140        return _apply_cte_builder(
2141            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2142        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
2068    def subquery(self, alias=None, copy=True) -> Subquery:
2069        """
2070        Convert this expression to an aliased expression that can be used as a Subquery.
2071
2072        Example:
2073            >>> subquery = Select().select("x").from_("tbl").subquery()
2074            >>> Select().select("x").from_(subquery).sql()
2075            'SELECT x FROM (SELECT x FROM tbl)'
2076
2077        Args:
2078            alias (str | Identifier): an optional alias for the subquery
2079            copy (bool): if `False`, modify this expression instance in-place.
2080
2081        Returns:
2082            Alias: the subquery
2083        """
2084        instance = _maybe_copy(self, copy)
2085        if not isinstance(alias, Expression):
2086            alias = TableAlias(this=to_identifier(alias)) if alias else None
2087
2088        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:
2090    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2091        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:
2108    def with_(
2109        self,
2110        alias: ExpOrStr,
2111        as_: ExpOrStr,
2112        recursive: t.Optional[bool] = None,
2113        append: bool = True,
2114        dialect: DialectType = None,
2115        copy: bool = True,
2116        **opts,
2117    ) -> Subqueryable:
2118        """
2119        Append to or set the common table expressions.
2120
2121        Example:
2122            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2123            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2124
2125        Args:
2126            alias: the SQL code string to parse as the table name.
2127                If an `Expression` instance is passed, this is used as-is.
2128            as_: the SQL code string to parse as the table expression.
2129                If an `Expression` instance is passed, it will be used as-is.
2130            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2131            append: if `True`, add to any existing expressions.
2132                Otherwise, this resets the expressions.
2133            dialect: the dialect used to parse the input expression.
2134            copy: if `False`, modify this expression instance in-place.
2135            opts: other options to use to parse the input expressions.
2136
2137        Returns:
2138            The modified expression.
2139        """
2140        return _apply_cte_builder(
2141            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2142        )

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

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

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

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

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

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

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

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

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

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

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:
2591    def select(
2592        self,
2593        *expressions: ExpOrStr,
2594        append: bool = True,
2595        dialect: DialectType = None,
2596        copy: bool = True,
2597        **opts,
2598    ) -> Select:
2599        """
2600        Append to or set the SELECT expressions.
2601
2602        Example:
2603            >>> Select().select("x", "y").sql()
2604            'SELECT x, y'
2605
2606        Args:
2607            *expressions: the SQL code strings to parse.
2608                If an `Expression` instance is passed, it will be used as-is.
2609            append: if `True`, add to any existing expressions.
2610                Otherwise, this resets the expressions.
2611            dialect: the dialect used to parse the input expressions.
2612            copy: if `False`, modify this expression instance in-place.
2613            opts: other options to use to parse the input expressions.
2614
2615        Returns:
2616            Select: the modified expression.
2617        """
2618        return _apply_list_builder(
2619            *expressions,
2620            instance=self,
2621            arg="expressions",
2622            append=append,
2623            dialect=dialect,
2624            copy=copy,
2625            **opts,
2626        )

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

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

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

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

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

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:
2901    def lock(self, update: bool = True, copy: bool = True) -> Select:
2902        """
2903        Set the locking read mode for this expression.
2904
2905        Examples:
2906            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2907            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2908
2909            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2910            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2911
2912        Args:
2913            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2914            copy: if `False`, modify this expression instance in-place.
2915
2916        Returns:
2917            The modified expression.
2918        """
2919
2920        inst = _maybe_copy(self, copy)
2921        inst.set("locks", [Lock(update=update)])
2922
2923        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):
2938class Subquery(DerivedTable, Unionable):
2939    arg_types = {
2940        "this": True,
2941        "alias": False,
2942        "with": False,
2943        **QUERY_MODIFIERS,
2944    }
2945
2946    def unnest(self):
2947        """
2948        Returns the first non subquery.
2949        """
2950        expression = self
2951        while isinstance(expression, Subquery):
2952            expression = expression.this
2953        return expression
2954
2955    @property
2956    def is_star(self) -> bool:
2957        return self.this.is_star
2958
2959    @property
2960    def output_name(self):
2961        return self.alias
def unnest(self):
2946    def unnest(self):
2947        """
2948        Returns the first non subquery.
2949        """
2950        expression = self
2951        while isinstance(expression, Subquery):
2952            expression = expression.this
2953        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):
2964class TableSample(Expression):
2965    arg_types = {
2966        "this": False,
2967        "method": False,
2968        "bucket_numerator": False,
2969        "bucket_denominator": False,
2970        "bucket_field": False,
2971        "percent": False,
2972        "rows": False,
2973        "size": False,
2974        "seed": False,
2975        "kind": False,
2976    }
class Tag(Expression):
2979class Tag(Expression):
2980    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2981
2982    arg_types = {
2983        "this": False,
2984        "prefix": False,
2985        "postfix": False,
2986    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2989class Pivot(Expression):
2990    arg_types = {
2991        "alias": False,
2992        "expressions": True,
2993        "field": True,
2994        "unpivot": True,
2995        "columns": False,
2996    }
class Window(Expression):
2999class Window(Expression):
3000    arg_types = {
3001        "this": True,
3002        "partition_by": False,
3003        "order": False,
3004        "spec": False,
3005        "alias": False,
3006        "over": False,
3007        "first": False,
3008    }
class WindowSpec(Expression):
3011class WindowSpec(Expression):
3012    arg_types = {
3013        "kind": False,
3014        "start": False,
3015        "start_side": False,
3016        "end": False,
3017        "end_side": False,
3018    }
class Where(Expression):
3021class Where(Expression):
3022    pass
class Star(Expression):
3025class Star(Expression):
3026    arg_types = {"except": False, "replace": False}
3027
3028    @property
3029    def name(self) -> str:
3030        return "*"
3031
3032    @property
3033    def output_name(self):
3034        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):
3037class Parameter(Expression):
3038    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
3041class SessionParameter(Expression):
3042    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
3045class Placeholder(Expression):
3046    arg_types = {"this": False, "kind": False}
class Null(Condition):
3049class Null(Condition):
3050    arg_types: t.Dict[str, t.Any] = {}
3051
3052    @property
3053    def name(self) -> str:
3054        return "NULL"
class Boolean(Condition):
3057class Boolean(Condition):
3058    pass
class DataTypeSize(Expression):
3061class DataTypeSize(Expression):
3062    arg_types = {"this": True, "expression": False}
class DataType(Expression):
3065class DataType(Expression):
3066    arg_types = {
3067        "this": True,
3068        "expressions": False,
3069        "nested": False,
3070        "values": False,
3071        "prefix": False,
3072    }
3073
3074    class Type(AutoName):
3075        ARRAY = auto()
3076        BIGDECIMAL = auto()
3077        BIGINT = auto()
3078        BIGSERIAL = auto()
3079        BINARY = auto()
3080        BIT = auto()
3081        BOOLEAN = auto()
3082        CHAR = auto()
3083        DATE = auto()
3084        DATETIME = auto()
3085        DATETIME64 = auto()
3086        DECIMAL = auto()
3087        DOUBLE = auto()
3088        FLOAT = auto()
3089        GEOGRAPHY = auto()
3090        GEOMETRY = auto()
3091        HLLSKETCH = auto()
3092        HSTORE = auto()
3093        IMAGE = auto()
3094        INET = auto()
3095        INT = auto()
3096        INT128 = auto()
3097        INT256 = auto()
3098        INTERVAL = auto()
3099        JSON = auto()
3100        JSONB = auto()
3101        LONGBLOB = auto()
3102        LONGTEXT = auto()
3103        MAP = auto()
3104        MEDIUMBLOB = auto()
3105        MEDIUMTEXT = auto()
3106        MONEY = auto()
3107        NCHAR = auto()
3108        NULL = auto()
3109        NULLABLE = auto()
3110        NVARCHAR = auto()
3111        OBJECT = auto()
3112        ROWVERSION = auto()
3113        SERIAL = auto()
3114        SMALLINT = auto()
3115        SMALLMONEY = auto()
3116        SMALLSERIAL = auto()
3117        STRUCT = auto()
3118        SUPER = auto()
3119        TEXT = auto()
3120        TIME = auto()
3121        TIMESTAMP = auto()
3122        TIMESTAMPTZ = auto()
3123        TIMESTAMPLTZ = auto()
3124        TINYINT = auto()
3125        UBIGINT = auto()
3126        UINT = auto()
3127        USMALLINT = auto()
3128        UTINYINT = auto()
3129        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3130        UINT128 = auto()
3131        UINT256 = auto()
3132        UNIQUEIDENTIFIER = auto()
3133        UUID = auto()
3134        VARBINARY = auto()
3135        VARCHAR = auto()
3136        VARIANT = auto()
3137        XML = auto()
3138
3139    TEXT_TYPES = {
3140        Type.CHAR,
3141        Type.NCHAR,
3142        Type.VARCHAR,
3143        Type.NVARCHAR,
3144        Type.TEXT,
3145    }
3146
3147    INTEGER_TYPES = {
3148        Type.INT,
3149        Type.TINYINT,
3150        Type.SMALLINT,
3151        Type.BIGINT,
3152        Type.INT128,
3153        Type.INT256,
3154    }
3155
3156    FLOAT_TYPES = {
3157        Type.FLOAT,
3158        Type.DOUBLE,
3159    }
3160
3161    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3162
3163    TEMPORAL_TYPES = {
3164        Type.TIMESTAMP,
3165        Type.TIMESTAMPTZ,
3166        Type.TIMESTAMPLTZ,
3167        Type.DATE,
3168        Type.DATETIME,
3169        Type.DATETIME64,
3170    }
3171
3172    @classmethod
3173    def build(
3174        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3175    ) -> DataType:
3176        from sqlglot import parse_one
3177
3178        if isinstance(dtype, str):
3179            if dtype.upper() in cls.Type.__members__:
3180                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3181            else:
3182                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3183            if data_type_exp is None:
3184                raise ValueError(f"Unparsable data type value: {dtype}")
3185        elif isinstance(dtype, DataType.Type):
3186            data_type_exp = DataType(this=dtype)
3187        elif isinstance(dtype, DataType):
3188            return dtype
3189        else:
3190            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3191        return DataType(**{**data_type_exp.args, **kwargs})
3192
3193    def is_type(self, dtype: DataType.Type) -> bool:
3194        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:
3172    @classmethod
3173    def build(
3174        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3175    ) -> DataType:
3176        from sqlglot import parse_one
3177
3178        if isinstance(dtype, str):
3179            if dtype.upper() in cls.Type.__members__:
3180                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3181            else:
3182                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3183            if data_type_exp is None:
3184                raise ValueError(f"Unparsable data type value: {dtype}")
3185        elif isinstance(dtype, DataType.Type):
3186            data_type_exp = DataType(this=dtype)
3187        elif isinstance(dtype, DataType):
3188            return dtype
3189        else:
3190            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3191        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3193    def is_type(self, dtype: DataType.Type) -> bool:
3194        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
3074    class Type(AutoName):
3075        ARRAY = auto()
3076        BIGDECIMAL = auto()
3077        BIGINT = auto()
3078        BIGSERIAL = auto()
3079        BINARY = auto()
3080        BIT = auto()
3081        BOOLEAN = auto()
3082        CHAR = auto()
3083        DATE = auto()
3084        DATETIME = auto()
3085        DATETIME64 = auto()
3086        DECIMAL = auto()
3087        DOUBLE = auto()
3088        FLOAT = auto()
3089        GEOGRAPHY = auto()
3090        GEOMETRY = auto()
3091        HLLSKETCH = auto()
3092        HSTORE = auto()
3093        IMAGE = auto()
3094        INET = auto()
3095        INT = auto()
3096        INT128 = auto()
3097        INT256 = auto()
3098        INTERVAL = auto()
3099        JSON = auto()
3100        JSONB = auto()
3101        LONGBLOB = auto()
3102        LONGTEXT = auto()
3103        MAP = auto()
3104        MEDIUMBLOB = auto()
3105        MEDIUMTEXT = auto()
3106        MONEY = auto()
3107        NCHAR = auto()
3108        NULL = auto()
3109        NULLABLE = auto()
3110        NVARCHAR = auto()
3111        OBJECT = auto()
3112        ROWVERSION = auto()
3113        SERIAL = auto()
3114        SMALLINT = auto()
3115        SMALLMONEY = auto()
3116        SMALLSERIAL = auto()
3117        STRUCT = auto()
3118        SUPER = auto()
3119        TEXT = auto()
3120        TIME = auto()
3121        TIMESTAMP = auto()
3122        TIMESTAMPTZ = auto()
3123        TIMESTAMPLTZ = auto()
3124        TINYINT = auto()
3125        UBIGINT = auto()
3126        UINT = auto()
3127        USMALLINT = auto()
3128        UTINYINT = auto()
3129        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3130        UINT128 = auto()
3131        UINT256 = auto()
3132        UNIQUEIDENTIFIER = auto()
3133        UUID = auto()
3134        VARBINARY = auto()
3135        VARCHAR = auto()
3136        VARIANT = auto()
3137        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):
3198class PseudoType(Expression):
3199    pass
class SubqueryPredicate(Predicate):
3203class SubqueryPredicate(Predicate):
3204    pass
class All(SubqueryPredicate):
3207class All(SubqueryPredicate):
3208    pass
class Any(SubqueryPredicate):
3211class Any(SubqueryPredicate):
3212    pass
class Exists(SubqueryPredicate):
3215class Exists(SubqueryPredicate):
3216    pass
class Command(Expression):
3221class Command(Expression):
3222    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
3225class Transaction(Expression):
3226    arg_types = {"this": False, "modes": False}
class Commit(Expression):
3229class Commit(Expression):
3230    arg_types = {"chain": False}
class Rollback(Expression):
3233class Rollback(Expression):
3234    arg_types = {"savepoint": False}
class AlterTable(Expression):
3237class AlterTable(Expression):
3238    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
3241class AddConstraint(Expression):
3242    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
3245class DropPartition(Expression):
3246    arg_types = {"expressions": True, "exists": False}
class Binary(Condition):
3250class Binary(Condition):
3251    arg_types = {"this": True, "expression": True}
3252
3253    @property
3254    def left(self):
3255        return self.this
3256
3257    @property
3258    def right(self):
3259        return self.expression
class Add(Binary):
3262class Add(Binary):
3263    pass
class Connector(Binary):
3266class Connector(Binary):
3267    pass
class And(Connector):
3270class And(Connector):
3271    pass
class Or(Connector):
3274class Or(Connector):
3275    pass
class BitwiseAnd(Binary):
3278class BitwiseAnd(Binary):
3279    pass
class BitwiseLeftShift(Binary):
3282class BitwiseLeftShift(Binary):
3283    pass
class BitwiseOr(Binary):
3286class BitwiseOr(Binary):
3287    pass
class BitwiseRightShift(Binary):
3290class BitwiseRightShift(Binary):
3291    pass
class BitwiseXor(Binary):
3294class BitwiseXor(Binary):
3295    pass
class Div(Binary):
3298class Div(Binary):
3299    pass
class Overlaps(Binary):
3302class Overlaps(Binary):
3303    pass
class Dot(Binary):
3306class Dot(Binary):
3307    @property
3308    def name(self) -> str:
3309        return self.expression.name
3310
3311    @classmethod
3312    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3313        """Build a Dot object with a sequence of expressions."""
3314        if len(expressions) < 2:
3315            raise ValueError(f"Dot requires >= 2 expressions.")
3316
3317        a, b, *expressions = expressions
3318        dot = Dot(this=a, expression=b)
3319
3320        for expression in expressions:
3321            dot = Dot(this=dot, expression=expression)
3322
3323        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3311    @classmethod
3312    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3313        """Build a Dot object with a sequence of expressions."""
3314        if len(expressions) < 2:
3315            raise ValueError(f"Dot requires >= 2 expressions.")
3316
3317        a, b, *expressions = expressions
3318        dot = Dot(this=a, expression=b)
3319
3320        for expression in expressions:
3321            dot = Dot(this=dot, expression=expression)
3322
3323        return dot

Build a Dot object with a sequence of expressions.

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

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

class Like(Binary, Predicate):
3382class Like(Binary, Predicate):
3383    pass
class LikeAny(Binary, Predicate):
3386class LikeAny(Binary, Predicate):
3387    pass
class LT(Binary, Predicate):
3390class LT(Binary, Predicate):
3391    pass
class LTE(Binary, Predicate):
3394class LTE(Binary, Predicate):
3395    pass
class Mod(Binary):
3398class Mod(Binary):
3399    pass
class Mul(Binary):
3402class Mul(Binary):
3403    pass
class NEQ(Binary, Predicate):
3406class NEQ(Binary, Predicate):
3407    pass
class SimilarTo(Binary, Predicate):
3410class SimilarTo(Binary, Predicate):
3411    pass
class Slice(Binary):
3414class Slice(Binary):
3415    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3418class Sub(Binary):
3419    pass
class ArrayOverlaps(Binary):
3422class ArrayOverlaps(Binary):
3423    pass
class Unary(Condition):
3428class Unary(Condition):
3429    pass
class BitwiseNot(Unary):
3432class BitwiseNot(Unary):
3433    pass
class Not(Unary):
3436class Not(Unary):
3437    pass
class Paren(Unary):
3440class Paren(Unary):
3441    arg_types = {"this": True, "with": False}
class Neg(Unary):
3444class Neg(Unary):
3445    pass
class Alias(Expression):
3448class Alias(Expression):
3449    arg_types = {"this": True, "alias": False}
3450
3451    @property
3452    def output_name(self):
3453        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):
3456class Aliases(Expression):
3457    arg_types = {"this": True, "expressions": True}
3458
3459    @property
3460    def aliases(self):
3461        return self.expressions
class AtTimeZone(Expression):
3464class AtTimeZone(Expression):
3465    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3468class Between(Predicate):
3469    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3472class Bracket(Condition):
3473    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3476class Distinct(Expression):
3477    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3480class In(Predicate):
3481    arg_types = {
3482        "this": True,
3483        "expressions": False,
3484        "query": False,
3485        "unnest": False,
3486        "field": False,
3487        "is_global": False,
3488    }
class TimeUnit(Expression):
3491class TimeUnit(Expression):
3492    """Automatically converts unit arg into a var."""
3493
3494    arg_types = {"unit": False}
3495
3496    def __init__(self, **args):
3497        unit = args.get("unit")
3498        if isinstance(unit, (Column, Literal)):
3499            args["unit"] = Var(this=unit.name)
3500        elif isinstance(unit, Week):
3501            unit.set("this", Var(this=unit.this.name))
3502        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3496    def __init__(self, **args):
3497        unit = args.get("unit")
3498        if isinstance(unit, (Column, Literal)):
3499            args["unit"] = Var(this=unit.name)
3500        elif isinstance(unit, Week):
3501            unit.set("this", Var(this=unit.this.name))
3502        super().__init__(**args)
class Interval(TimeUnit):
3505class Interval(TimeUnit):
3506    arg_types = {"this": False, "unit": False}
3507
3508    @property
3509    def unit(self) -> t.Optional[Var]:
3510        return self.args.get("unit")
class IgnoreNulls(Expression):
3513class IgnoreNulls(Expression):
3514    pass
class RespectNulls(Expression):
3517class RespectNulls(Expression):
3518    pass
class Func(Condition):
3522class Func(Condition):
3523    """
3524    The base class for all function expressions.
3525
3526    Attributes:
3527        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3528            treated as a variable length argument and the argument's value will be stored as a list.
3529        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3530            for this function expression. These values are used to map this node to a name during parsing
3531            as well as to provide the function's name during SQL string generation. By default the SQL
3532            name is set to the expression's class name transformed to snake case.
3533    """
3534
3535    is_var_len_args = False
3536
3537    @classmethod
3538    def from_arg_list(cls, args):
3539        if cls.is_var_len_args:
3540            all_arg_keys = list(cls.arg_types)
3541            # If this function supports variable length argument treat the last argument as such.
3542            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3543            num_non_var = len(non_var_len_arg_keys)
3544
3545            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3546            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3547        else:
3548            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3549
3550        return cls(**args_dict)
3551
3552    @classmethod
3553    def sql_names(cls):
3554        if cls is Func:
3555            raise NotImplementedError(
3556                "SQL name is only supported by concrete function implementations"
3557            )
3558        if "_sql_names" not in cls.__dict__:
3559            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3560        return cls._sql_names
3561
3562    @classmethod
3563    def sql_name(cls):
3564        return cls.sql_names()[0]
3565
3566    @classmethod
3567    def default_parser_mappings(cls):
3568        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):
3537    @classmethod
3538    def from_arg_list(cls, args):
3539        if cls.is_var_len_args:
3540            all_arg_keys = list(cls.arg_types)
3541            # If this function supports variable length argument treat the last argument as such.
3542            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3543            num_non_var = len(non_var_len_arg_keys)
3544
3545            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3546            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3547        else:
3548            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3549
3550        return cls(**args_dict)
@classmethod
def sql_names(cls):
3552    @classmethod
3553    def sql_names(cls):
3554        if cls is Func:
3555            raise NotImplementedError(
3556                "SQL name is only supported by concrete function implementations"
3557            )
3558        if "_sql_names" not in cls.__dict__:
3559            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3560        return cls._sql_names
@classmethod
def sql_name(cls):
3562    @classmethod
3563    def sql_name(cls):
3564        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3566    @classmethod
3567    def default_parser_mappings(cls):
3568        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3571class AggFunc(Func):
3572    pass
class ParameterizedAgg(AggFunc):
3575class ParameterizedAgg(AggFunc):
3576    arg_types = {"this": True, "expressions": True, "params": True}
class Abs(Func):
3579class Abs(Func):
3580    pass
class Anonymous(Func):
3583class Anonymous(Func):
3584    arg_types = {"this": True, "expressions": False}
3585    is_var_len_args = True
class Hll(AggFunc):
3590class Hll(AggFunc):
3591    arg_types = {"this": True, "expressions": False}
3592    is_var_len_args = True
class ApproxDistinct(AggFunc):
3595class ApproxDistinct(AggFunc):
3596    arg_types = {"this": True, "accuracy": False}
3597    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
class Array(Func):
3600class Array(Func):
3601    arg_types = {"expressions": False}
3602    is_var_len_args = True
class ToChar(Func):
3606class ToChar(Func):
3607    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3610class GenerateSeries(Func):
3611    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3614class ArrayAgg(AggFunc):
3615    pass
class ArrayAll(Func):
3618class ArrayAll(Func):
3619    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3622class ArrayAny(Func):
3623    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3626class ArrayConcat(Func):
3627    arg_types = {"this": True, "expressions": False}
3628    is_var_len_args = True
class ArrayContains(Binary, Func):
3631class ArrayContains(Binary, Func):
3632    pass
class ArrayContained(Binary):
3635class ArrayContained(Binary):
3636    pass
class ArrayFilter(Func):
3639class ArrayFilter(Func):
3640    arg_types = {"this": True, "expression": True}
3641    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3644class ArrayJoin(Func):
3645    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3648class ArraySize(Func):
3649    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3652class ArraySort(Func):
3653    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3656class ArraySum(Func):
3657    pass
class ArrayUnionAgg(AggFunc):
3660class ArrayUnionAgg(AggFunc):
3661    pass
class Avg(AggFunc):
3664class Avg(AggFunc):
3665    pass
class AnyValue(AggFunc):
3668class AnyValue(AggFunc):
3669    pass
class Case(Func):
3672class Case(Func):
3673    arg_types = {"this": False, "ifs": True, "default": False}
3674
3675    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3676        instance = _maybe_copy(self, copy)
3677        instance.append(
3678            "ifs",
3679            If(
3680                this=maybe_parse(condition, copy=copy, **opts),
3681                true=maybe_parse(then, copy=copy, **opts),
3682            ),
3683        )
3684        return instance
3685
3686    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3687        instance = _maybe_copy(self, copy)
3688        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3689        return instance
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3675    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3676        instance = _maybe_copy(self, copy)
3677        instance.append(
3678            "ifs",
3679            If(
3680                this=maybe_parse(condition, copy=copy, **opts),
3681                true=maybe_parse(then, copy=copy, **opts),
3682            ),
3683        )
3684        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3686    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3687        instance = _maybe_copy(self, copy)
3688        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3689        return instance
class Cast(Func):
3692class Cast(Func):
3693    arg_types = {"this": True, "to": True}
3694
3695    @property
3696    def name(self) -> str:
3697        return self.this.name
3698
3699    @property
3700    def to(self):
3701        return self.args["to"]
3702
3703    @property
3704    def output_name(self):
3705        return self.name
3706
3707    def is_type(self, dtype: DataType.Type) -> bool:
3708        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:
3707    def is_type(self, dtype: DataType.Type) -> bool:
3708        return self.to.is_type(dtype)
class CastToStrType(Func):
3711class CastToStrType(Func):
3712    arg_types = {"this": True, "expression": True}
class Collate(Binary):
3715class Collate(Binary):
3716    pass
class TryCast(Cast):
3719class TryCast(Cast):
3720    pass
class Ceil(Func):
3723class Ceil(Func):
3724    arg_types = {"this": True, "decimals": False}
3725    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3728class Coalesce(Func):
3729    arg_types = {"this": True, "expressions": False}
3730    is_var_len_args = True
class Concat(Func):
3733class Concat(Func):
3734    arg_types = {"expressions": True}
3735    is_var_len_args = True
class ConcatWs(Concat):
3738class ConcatWs(Concat):
3739    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3742class Count(AggFunc):
3743    arg_types = {"this": False}
class CountIf(AggFunc):
3746class CountIf(AggFunc):
3747    pass
class CurrentDate(Func):
3750class CurrentDate(Func):
3751    arg_types = {"this": False}
class CurrentDatetime(Func):
3754class CurrentDatetime(Func):
3755    arg_types = {"this": False}
class CurrentTime(Func):
3758class CurrentTime(Func):
3759    arg_types = {"this": False}
class CurrentTimestamp(Func):
3762class CurrentTimestamp(Func):
3763    arg_types = {"this": False}
class CurrentUser(Func):
3766class CurrentUser(Func):
3767    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3770class DateAdd(Func, TimeUnit):
3771    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3774class DateSub(Func, TimeUnit):
3775    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3778class DateDiff(Func, TimeUnit):
3779    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3780    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3783class DateTrunc(Func):
3784    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3787class DatetimeAdd(Func, TimeUnit):
3788    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3791class DatetimeSub(Func, TimeUnit):
3792    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3795class DatetimeDiff(Func, TimeUnit):
3796    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3799class DatetimeTrunc(Func, TimeUnit):
3800    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3803class DayOfWeek(Func):
3804    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3807class DayOfMonth(Func):
3808    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3811class DayOfYear(Func):
3812    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3815class WeekOfYear(Func):
3816    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3819class LastDateOfMonth(Func):
3820    pass
class Extract(Func):
3823class Extract(Func):
3824    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3827class TimestampAdd(Func, TimeUnit):
3828    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3831class TimestampSub(Func, TimeUnit):
3832    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3835class TimestampDiff(Func, TimeUnit):
3836    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3839class TimestampTrunc(Func, TimeUnit):
3840    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3843class TimeAdd(Func, TimeUnit):
3844    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3847class TimeSub(Func, TimeUnit):
3848    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3851class TimeDiff(Func, TimeUnit):
3852    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3855class TimeTrunc(Func, TimeUnit):
3856    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3859class DateFromParts(Func):
3860    _sql_names = ["DATEFROMPARTS"]
3861    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3864class DateStrToDate(Func):
3865    pass
class DateToDateStr(Func):
3868class DateToDateStr(Func):
3869    pass
class DateToDi(Func):
3872class DateToDi(Func):
3873    pass
class Day(Func):
3876class Day(Func):
3877    pass
class Decode(Func):
3880class Decode(Func):
3881    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3884class DiToDate(Func):
3885    pass
class Encode(Func):
3888class Encode(Func):
3889    arg_types = {"this": True, "charset": True}
class Exp(Func):
3892class Exp(Func):
3893    pass
class Explode(Func):
3896class Explode(Func):
3897    pass
class Floor(Func):
3900class Floor(Func):
3901    arg_types = {"this": True, "decimals": False}
class FromBase64(Func):
3904class FromBase64(Func):
3905    pass
class ToBase64(Func):
3908class ToBase64(Func):
3909    pass
class Greatest(Func):
3912class Greatest(Func):
3913    arg_types = {"this": True, "expressions": False}
3914    is_var_len_args = True
class GroupConcat(Func):
3917class GroupConcat(Func):
3918    arg_types = {"this": True, "separator": False}
class Hex(Func):
3921class Hex(Func):
3922    pass
class If(Func):
3925class If(Func):
3926    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3929class IfNull(Func):
3930    arg_types = {"this": True, "expression": False}
3931    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3934class Initcap(Func):
3935    pass
class JSONKeyValue(Expression):
3938class JSONKeyValue(Expression):
3939    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
3942class JSONObject(Func):
3943    arg_types = {
3944        "expressions": False,
3945        "null_handling": False,
3946        "unique_keys": False,
3947        "return_type": False,
3948        "format_json": False,
3949        "encoding": False,
3950    }
class OpenJSONColumnDef(Expression):
3953class OpenJSONColumnDef(Expression):
3954    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
class OpenJSON(Func):
3957class OpenJSON(Func):
3958    arg_types = {"this": True, "path": False, "expressions": False}
class JSONBContains(Binary):
3961class JSONBContains(Binary):
3962    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3965class JSONExtract(Binary, Func):
3966    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3969class JSONExtractScalar(JSONExtract):
3970    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3973class JSONBExtract(JSONExtract):
3974    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3977class JSONBExtractScalar(JSONExtract):
3978    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
3981class JSONFormat(Func):
3982    arg_types = {"this": False, "options": False}
3983    _sql_names = ["JSON_FORMAT"]
class Least(Func):
3986class Least(Func):
3987    arg_types = {"expressions": False}
3988    is_var_len_args = True
class Length(Func):
3991class Length(Func):
3992    pass
class Levenshtein(Func):
3995class Levenshtein(Func):
3996    arg_types = {
3997        "this": True,
3998        "expression": False,
3999        "ins_cost": False,
4000        "del_cost": False,
4001        "sub_cost": False,
4002    }
class Ln(Func):
4005class Ln(Func):
4006    pass
class Log(Func):
4009class Log(Func):
4010    arg_types = {"this": True, "expression": False}
class Log2(Func):
4013class Log2(Func):
4014    pass
class Log10(Func):
4017class Log10(Func):
4018    pass
class LogicalOr(AggFunc):
4021class LogicalOr(AggFunc):
4022    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
4025class LogicalAnd(AggFunc):
4026    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
4029class Lower(Func):
4030    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
4033class Map(Func):
4034    arg_types = {"keys": False, "values": False}
class StarMap(Func):
4037class StarMap(Func):
4038    pass
class VarMap(Func):
4041class VarMap(Func):
4042    arg_types = {"keys": True, "values": True}
4043    is_var_len_args = True
class MatchAgainst(Func):
4047class MatchAgainst(Func):
4048    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
4051class Max(AggFunc):
4052    arg_types = {"this": True, "expressions": False}
4053    is_var_len_args = True
class MD5(Func):
4056class MD5(Func):
4057    _sql_names = ["MD5"]
class Min(AggFunc):
4060class Min(AggFunc):
4061    arg_types = {"this": True, "expressions": False}
4062    is_var_len_args = True
class Month(Func):
4065class Month(Func):
4066    pass
class Nvl2(Func):
4069class Nvl2(Func):
4070    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
4073class Posexplode(Func):
4074    pass
class Pow(Binary, Func):
4077class Pow(Binary, Func):
4078    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
4081class PercentileCont(AggFunc):
4082    arg_types = {"this": True, "expression": False}
class PercentileDisc(AggFunc):
4085class PercentileDisc(AggFunc):
4086    arg_types = {"this": True, "expression": False}
class Quantile(AggFunc):
4089class Quantile(AggFunc):
4090    arg_types = {"this": True, "quantile": True}
class ApproxQuantile(Quantile):
4093class ApproxQuantile(Quantile):
4094    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
4097class RangeN(Func):
4098    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
4101class ReadCSV(Func):
4102    _sql_names = ["READ_CSV"]
4103    is_var_len_args = True
4104    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
4107class Reduce(Func):
4108    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
4111class RegexpExtract(Func):
4112    arg_types = {
4113        "this": True,
4114        "expression": True,
4115        "position": False,
4116        "occurrence": False,
4117        "group": False,
4118    }
class RegexpLike(Func):
4121class RegexpLike(Func):
4122    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
4125class RegexpILike(Func):
4126    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
4131class RegexpSplit(Func):
4132    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
4135class Repeat(Func):
4136    arg_types = {"this": True, "times": True}
class Round(Func):
4139class Round(Func):
4140    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
4143class RowNumber(Func):
4144    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
4147class SafeDivide(Func):
4148    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
4151class SetAgg(AggFunc):
4152    pass
class SHA(Func):
4155class SHA(Func):
4156    _sql_names = ["SHA", "SHA1"]
class SHA2(Func):
4159class SHA2(Func):
4160    _sql_names = ["SHA2"]
4161    arg_types = {"this": True, "length": False}
class SortArray(Func):
4164class SortArray(Func):
4165    arg_types = {"this": True, "asc": False}
class Split(Func):
4168class Split(Func):
4169    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
4174class Substring(Func):
4175    arg_types = {"this": True, "start": False, "length": False}
class StandardHash(Func):
4178class StandardHash(Func):
4179    arg_types = {"this": True, "expression": False}
class StrPosition(Func):
4182class StrPosition(Func):
4183    arg_types = {
4184        "this": True,
4185        "substr": True,
4186        "position": False,
4187        "instance": False,
4188    }
class StrToDate(Func):
4191class StrToDate(Func):
4192    arg_types = {"this": True, "format": True}
class StrToTime(Func):
4195class StrToTime(Func):
4196    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
4201class StrToUnix(Func):
4202    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
4205class NumberToStr(Func):
4206    arg_types = {"this": True, "format": True}
class Struct(Func):
4209class Struct(Func):
4210    arg_types = {"expressions": True}
4211    is_var_len_args = True
class StructExtract(Func):
4214class StructExtract(Func):
4215    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
4218class Sum(AggFunc):
4219    pass
class Sqrt(Func):
4222class Sqrt(Func):
4223    pass
class Stddev(AggFunc):
4226class Stddev(AggFunc):
4227    pass
class StddevPop(AggFunc):
4230class StddevPop(AggFunc):
4231    pass
class StddevSamp(AggFunc):
4234class StddevSamp(AggFunc):
4235    pass
class TimeToStr(Func):
4238class TimeToStr(Func):
4239    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
4242class TimeToTimeStr(Func):
4243    pass
class TimeToUnix(Func):
4246class TimeToUnix(Func):
4247    pass
class TimeStrToDate(Func):
4250class TimeStrToDate(Func):
4251    pass
class TimeStrToTime(Func):
4254class TimeStrToTime(Func):
4255    pass
class TimeStrToUnix(Func):
4258class TimeStrToUnix(Func):
4259    pass
class Trim(Func):
4262class Trim(Func):
4263    arg_types = {
4264        "this": True,
4265        "expression": False,
4266        "position": False,
4267        "collation": False,
4268    }
class TsOrDsAdd(Func, TimeUnit):
4271class TsOrDsAdd(Func, TimeUnit):
4272    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
4275class TsOrDsToDateStr(Func):
4276    pass
class TsOrDsToDate(Func):
4279class TsOrDsToDate(Func):
4280    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
4283class TsOrDiToDi(Func):
4284    pass
class Unhex(Func):
4287class Unhex(Func):
4288    pass
class UnixToStr(Func):
4291class UnixToStr(Func):
4292    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
4297class UnixToTime(Func):
4298    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4299
4300    SECONDS = Literal.string("seconds")
4301    MILLIS = Literal.string("millis")
4302    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
4305class UnixToTimeStr(Func):
4306    pass
class Upper(Func):
4309class Upper(Func):
4310    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
4313class Variance(AggFunc):
4314    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
4317class VariancePop(AggFunc):
4318    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
4321class Week(Func):
4322    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
4325class XMLTable(Func):
4326    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4329class Year(Func):
4330    pass
class Use(Expression):
4333class Use(Expression):
4334    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4337class Merge(Expression):
4338    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4341class When(Func):
4342    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
class NextValueFor(Func):
4347class NextValueFor(Func):
4348    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:
4385def maybe_parse(
4386    sql_or_expression: ExpOrStr,
4387    *,
4388    into: t.Optional[IntoType] = None,
4389    dialect: DialectType = None,
4390    prefix: t.Optional[str] = None,
4391    copy: bool = False,
4392    **opts,
4393) -> Expression:
4394    """Gracefully handle a possible string or expression.
4395
4396    Example:
4397        >>> maybe_parse("1")
4398        (LITERAL this: 1, is_string: False)
4399        >>> maybe_parse(to_identifier("x"))
4400        (IDENTIFIER this: x, quoted: False)
4401
4402    Args:
4403        sql_or_expression: the SQL code string or an expression
4404        into: the SQLGlot Expression to parse into
4405        dialect: the dialect used to parse the input expressions (in the case that an
4406            input expression is a SQL string).
4407        prefix: a string to prefix the sql with before it gets parsed
4408            (automatically includes a space)
4409        copy: whether or not to copy the expression.
4410        **opts: other options to use to parse the input expressions (again, in the case
4411            that an input expression is a SQL string).
4412
4413    Returns:
4414        Expression: the parsed or given expression.
4415    """
4416    if isinstance(sql_or_expression, Expression):
4417        if copy:
4418            return sql_or_expression.copy()
4419        return sql_or_expression
4420
4421    import sqlglot
4422
4423    sql = str(sql_or_expression)
4424    if prefix:
4425        sql = f"{prefix} {sql}"
4426    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):
4598def union(left, right, distinct=True, dialect=None, **opts):
4599    """
4600    Initializes a syntax tree from one UNION expression.
4601
4602    Example:
4603        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4604        'SELECT * FROM foo UNION SELECT * FROM bla'
4605
4606    Args:
4607        left (str | Expression): the SQL code string corresponding to the left-hand side.
4608            If an `Expression` instance is passed, it will be used as-is.
4609        right (str | Expression): the SQL code string corresponding to the right-hand side.
4610            If an `Expression` instance is passed, it will be used as-is.
4611        distinct (bool): set the DISTINCT flag if and only if this is true.
4612        dialect (str): the dialect used to parse the input expression.
4613        opts (kwargs): other options to use to parse the input expressions.
4614    Returns:
4615        Union: the syntax tree for the UNION expression.
4616    """
4617    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4618    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4619
4620    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):
4623def intersect(left, right, distinct=True, dialect=None, **opts):
4624    """
4625    Initializes a syntax tree from one INTERSECT expression.
4626
4627    Example:
4628        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4629        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4630
4631    Args:
4632        left (str | Expression): the SQL code string corresponding to the left-hand side.
4633            If an `Expression` instance is passed, it will be used as-is.
4634        right (str | Expression): the SQL code string corresponding to the right-hand side.
4635            If an `Expression` instance is passed, it will be used as-is.
4636        distinct (bool): set the DISTINCT flag if and only if this is true.
4637        dialect (str): the dialect used to parse the input expression.
4638        opts (kwargs): other options to use to parse the input expressions.
4639    Returns:
4640        Intersect: the syntax tree for the INTERSECT expression.
4641    """
4642    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4643    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4644
4645    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):
4648def except_(left, right, distinct=True, dialect=None, **opts):
4649    """
4650    Initializes a syntax tree from one EXCEPT expression.
4651
4652    Example:
4653        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4654        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4655
4656    Args:
4657        left (str | Expression): the SQL code string corresponding to the left-hand side.
4658            If an `Expression` instance is passed, it will be used as-is.
4659        right (str | Expression): the SQL code string corresponding to the right-hand side.
4660            If an `Expression` instance is passed, it will be used as-is.
4661        distinct (bool): set the DISTINCT flag if and only if this is true.
4662        dialect (str): the dialect used to parse the input expression.
4663        opts (kwargs): other options to use to parse the input expressions.
4664    Returns:
4665        Except: the syntax tree for the EXCEPT statement.
4666    """
4667    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4668    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4669
4670    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:
4673def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4674    """
4675    Initializes a syntax tree from one or multiple SELECT expressions.
4676
4677    Example:
4678        >>> select("col1", "col2").from_("tbl").sql()
4679        'SELECT col1, col2 FROM tbl'
4680
4681    Args:
4682        *expressions: the SQL code string to parse as the expressions of a
4683            SELECT statement. If an Expression instance is passed, this is used as-is.
4684        dialect: the dialect used to parse the input expressions (in the case that an
4685            input expression is a SQL string).
4686        **opts: other options to use to parse the input expressions (again, in the case
4687            that an input expression is a SQL string).
4688
4689    Returns:
4690        Select: the syntax tree for the SELECT statement.
4691    """
4692    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:
4695def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4696    """
4697    Initializes a syntax tree from a FROM expression.
4698
4699    Example:
4700        >>> from_("tbl").select("col1", "col2").sql()
4701        'SELECT col1, col2 FROM tbl'
4702
4703    Args:
4704        *expression: the SQL code string to parse as the FROM expressions of a
4705            SELECT statement. If an Expression instance is passed, this is used as-is.
4706        dialect: the dialect used to parse the input expression (in the case that the
4707            input expression is a SQL string).
4708        **opts: other options to use to parse the input expressions (again, in the case
4709            that the input expression is a SQL string).
4710
4711    Returns:
4712        Select: the syntax tree for the SELECT statement.
4713    """
4714    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:
4717def update(
4718    table: str | Table,
4719    properties: dict,
4720    where: t.Optional[ExpOrStr] = None,
4721    from_: t.Optional[ExpOrStr] = None,
4722    dialect: DialectType = None,
4723    **opts,
4724) -> Update:
4725    """
4726    Creates an update statement.
4727
4728    Example:
4729        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4730        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4731
4732    Args:
4733        *properties: dictionary of properties to set which are
4734            auto converted to sql objects eg None -> NULL
4735        where: sql conditional parsed into a WHERE statement
4736        from_: sql statement parsed into a FROM statement
4737        dialect: the dialect used to parse the input expressions.
4738        **opts: other options to use to parse the input expressions.
4739
4740    Returns:
4741        Update: the syntax tree for the UPDATE statement.
4742    """
4743    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4744    update_expr.set(
4745        "expressions",
4746        [
4747            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4748            for k, v in properties.items()
4749        ],
4750    )
4751    if from_:
4752        update_expr.set(
4753            "from",
4754            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4755        )
4756    if isinstance(where, Condition):
4757        where = Where(this=where)
4758    if where:
4759        update_expr.set(
4760            "where",
4761            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4762        )
4763    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:
4766def delete(
4767    table: ExpOrStr,
4768    where: t.Optional[ExpOrStr] = None,
4769    returning: t.Optional[ExpOrStr] = None,
4770    dialect: DialectType = None,
4771    **opts,
4772) -> Delete:
4773    """
4774    Builds a delete statement.
4775
4776    Example:
4777        >>> delete("my_table", where="id > 1").sql()
4778        'DELETE FROM my_table WHERE id > 1'
4779
4780    Args:
4781        where: sql conditional parsed into a WHERE statement
4782        returning: sql conditional parsed into a RETURNING statement
4783        dialect: the dialect used to parse the input expressions.
4784        **opts: other options to use to parse the input expressions.
4785
4786    Returns:
4787        Delete: the syntax tree for the DELETE statement.
4788    """
4789    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4790    if where:
4791        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4792    if returning:
4793        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4794    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:
4797def insert(
4798    expression: ExpOrStr,
4799    into: ExpOrStr,
4800    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
4801    overwrite: t.Optional[bool] = None,
4802    dialect: DialectType = None,
4803    copy: bool = True,
4804    **opts,
4805) -> Insert:
4806    """
4807    Builds an INSERT statement.
4808
4809    Example:
4810        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
4811        'INSERT INTO tbl VALUES (1, 2, 3)'
4812
4813    Args:
4814        expression: the sql string or expression of the INSERT statement
4815        into: the tbl to insert data to.
4816        columns: optionally the table's column names.
4817        overwrite: whether to INSERT OVERWRITE or not.
4818        dialect: the dialect used to parse the input expressions.
4819        copy: whether or not to copy the expression.
4820        **opts: other options to use to parse the input expressions.
4821
4822    Returns:
4823        Insert: the syntax tree for the INSERT statement.
4824    """
4825    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
4826    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
4827
4828    if columns:
4829        this = _apply_list_builder(
4830            *columns,
4831            instance=Schema(this=this),
4832            arg="expressions",
4833            into=Identifier,
4834            copy=False,
4835            dialect=dialect,
4836            **opts,
4837        )
4838
4839    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:
4842def condition(expression, dialect=None, copy=True, **opts) -> Condition:
4843    """
4844    Initialize a logical condition expression.
4845
4846    Example:
4847        >>> condition("x=1").sql()
4848        'x = 1'
4849
4850        This is helpful for composing larger logical syntax trees:
4851        >>> where = condition("x=1")
4852        >>> where = where.and_("y=1")
4853        >>> Select().from_("tbl").select("*").where(where).sql()
4854        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4855
4856    Args:
4857        *expression (str | Expression): the SQL code string to parse.
4858            If an Expression instance is passed, this is used as-is.
4859        dialect (str): the dialect used to parse the input expression (in the case that the
4860            input expression is a SQL string).
4861        copy (bool): Whether or not to copy `expression` (only applies to expressions).
4862        **opts: other options to use to parse the input expressions (again, in the case
4863            that the input expression is a SQL string).
4864
4865    Returns:
4866        Condition: the expression
4867    """
4868    return maybe_parse(  # type: ignore
4869        expression,
4870        into=Condition,
4871        dialect=dialect,
4872        copy=copy,
4873        **opts,
4874    )

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:
4877def and_(*expressions, dialect=None, copy=True, **opts) -> And:
4878    """
4879    Combine multiple conditions with an AND logical operator.
4880
4881    Example:
4882        >>> and_("x=1", and_("y=1", "z=1")).sql()
4883        'x = 1 AND (y = 1 AND z = 1)'
4884
4885    Args:
4886        *expressions (str | Expression): the SQL code strings to parse.
4887            If an Expression instance is passed, this is used as-is.
4888        dialect (str): the dialect used to parse the input expression.
4889        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4890        **opts: other options to use to parse the input expressions.
4891
4892    Returns:
4893        And: the new condition
4894    """
4895    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:
4898def or_(*expressions, dialect=None, copy=True, **opts) -> Or:
4899    """
4900    Combine multiple conditions with an OR logical operator.
4901
4902    Example:
4903        >>> or_("x=1", or_("y=1", "z=1")).sql()
4904        'x = 1 OR (y = 1 OR z = 1)'
4905
4906    Args:
4907        *expressions (str | Expression): the SQL code strings to parse.
4908            If an Expression instance is passed, this is used as-is.
4909        dialect (str): the dialect used to parse the input expression.
4910        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4911        **opts: other options to use to parse the input expressions.
4912
4913    Returns:
4914        Or: the new condition
4915    """
4916    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:
4919def not_(expression, dialect=None, copy=True, **opts) -> Not:
4920    """
4921    Wrap a condition with a NOT operator.
4922
4923    Example:
4924        >>> not_("this_suit='black'").sql()
4925        "NOT this_suit = 'black'"
4926
4927    Args:
4928        expression (str | Expression): the SQL code strings to parse.
4929            If an Expression instance is passed, this is used as-is.
4930        dialect (str): the dialect used to parse the input expression.
4931        **opts: other options to use to parse the input expressions.
4932
4933    Returns:
4934        Not: the new condition
4935    """
4936    this = condition(
4937        expression,
4938        dialect=dialect,
4939        copy=copy,
4940        **opts,
4941    )
4942    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:
4945def paren(expression, copy=True) -> Paren:
4946    return Paren(this=_maybe_copy(expression, copy))
def to_identifier(name, quoted=None, copy=True):
4964def to_identifier(name, quoted=None, copy=True):
4965    """Builds an identifier.
4966
4967    Args:
4968        name: The name to turn into an identifier.
4969        quoted: Whether or not force quote the identifier.
4970        copy: Whether or not to copy a passed in Identefier node.
4971
4972    Returns:
4973        The identifier ast node.
4974    """
4975
4976    if name is None:
4977        return None
4978
4979    if isinstance(name, Identifier):
4980        identifier = _maybe_copy(name, copy)
4981    elif isinstance(name, str):
4982        identifier = Identifier(
4983            this=name,
4984            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4985        )
4986    else:
4987        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4988    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:
4994def to_interval(interval: str | Literal) -> Interval:
4995    """Builds an interval expression from a string like '1 day' or '5 months'."""
4996    if isinstance(interval, Literal):
4997        if not interval.is_string:
4998            raise ValueError("Invalid interval string.")
4999
5000        interval = interval.this
5001
5002    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5003
5004    if not interval_parts:
5005        raise ValueError("Invalid interval string.")
5006
5007    return Interval(
5008        this=Literal.string(interval_parts.group(1)),
5009        unit=Var(this=interval_parts.group(2)),
5010    )

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]:
5023def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
5024    """
5025    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5026    If a table is passed in then that table is returned.
5027
5028    Args:
5029        sql_path: a `[catalog].[schema].[table]` string.
5030
5031    Returns:
5032        A table expression.
5033    """
5034    if sql_path is None or isinstance(sql_path, Table):
5035        return sql_path
5036    if not isinstance(sql_path, str):
5037        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5038
5039    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
5040    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:
5043def to_column(sql_path: str | Column, **kwargs) -> Column:
5044    """
5045    Create a column from a `[table].[column]` sql path. Schema is optional.
5046
5047    If a column is passed in then that column is returned.
5048
5049    Args:
5050        sql_path: `[table].[column]` string
5051    Returns:
5052        Table: A column expression
5053    """
5054    if sql_path is None or isinstance(sql_path, Column):
5055        return sql_path
5056    if not isinstance(sql_path, str):
5057        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5058    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):
5061def alias_(
5062    expression: ExpOrStr,
5063    alias: str | Identifier,
5064    table: bool | t.Sequence[str | Identifier] = False,
5065    quoted: t.Optional[bool] = None,
5066    dialect: DialectType = None,
5067    copy: bool = True,
5068    **opts,
5069):
5070    """Create an Alias expression.
5071
5072    Example:
5073        >>> alias_('foo', 'bar').sql()
5074        'foo AS bar'
5075
5076        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5077        '(SELECT 1, 2) AS bar(a, b)'
5078
5079    Args:
5080        expression: the SQL code strings to parse.
5081            If an Expression instance is passed, this is used as-is.
5082        alias: the alias name to use. If the name has
5083            special characters it is quoted.
5084        table: Whether or not to create a table alias, can also be a list of columns.
5085        quoted: whether or not to quote the alias
5086        dialect: the dialect used to parse the input expression.
5087        copy: Whether or not to copy the expression.
5088        **opts: other options to use to parse the input expressions.
5089
5090    Returns:
5091        Alias: the aliased expression
5092    """
5093    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5094    alias = to_identifier(alias, quoted=quoted)
5095
5096    if table:
5097        table_alias = TableAlias(this=alias)
5098        exp.set("alias", table_alias)
5099
5100        if not isinstance(table, bool):
5101            for column in table:
5102                table_alias.append("columns", to_identifier(column, quoted=quoted))
5103
5104        return exp
5105
5106    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5107    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5108    # for the complete Window expression.
5109    #
5110    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5111
5112    if "alias" in exp.arg_types and not isinstance(exp, Window):
5113        exp.set("alias", alias)
5114        return exp
5115    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):
5118def subquery(expression, alias=None, dialect=None, **opts):
5119    """
5120    Build a subquery expression.
5121
5122    Example:
5123        >>> subquery('select x from tbl', 'bar').select('x').sql()
5124        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5125
5126    Args:
5127        expression (str | Expression): the SQL code strings to parse.
5128            If an Expression instance is passed, this is used as-is.
5129        alias (str | Expression): the alias name to use.
5130        dialect (str): the dialect used to parse the input expression.
5131        **opts: other options to use to parse the input expressions.
5132
5133    Returns:
5134        Select: a new select with the subquery expression included
5135    """
5136
5137    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5138    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:
5141def column(
5142    col: str | Identifier,
5143    table: t.Optional[str | Identifier] = None,
5144    db: t.Optional[str | Identifier] = None,
5145    catalog: t.Optional[str | Identifier] = None,
5146    quoted: t.Optional[bool] = None,
5147) -> Column:
5148    """
5149    Build a Column.
5150
5151    Args:
5152        col: column name
5153        table: table name
5154        db: db name
5155        catalog: catalog name
5156        quoted: whether or not to force quote each part
5157    Returns:
5158        Column: column instance
5159    """
5160    return Column(
5161        this=to_identifier(col, quoted=quoted),
5162        table=to_identifier(table, quoted=quoted),
5163        db=to_identifier(db, quoted=quoted),
5164        catalog=to_identifier(catalog, quoted=quoted),
5165    )

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:
5168def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5169    """Cast an expression to a data type.
5170
5171    Example:
5172        >>> cast('x + 1', 'int').sql()
5173        'CAST(x + 1 AS INT)'
5174
5175    Args:
5176        expression: The expression to cast.
5177        to: The datatype to cast to.
5178
5179    Returns:
5180        A cast node.
5181    """
5182    expression = maybe_parse(expression, **opts)
5183    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:
5186def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
5187    """Build a Table.
5188
5189    Args:
5190        table (str | Expression): column name
5191        db (str | Expression): db name
5192        catalog (str | Expression): catalog name
5193
5194    Returns:
5195        Table: table instance
5196    """
5197    return Table(
5198        this=to_identifier(table, quoted=quoted),
5199        db=to_identifier(db, quoted=quoted),
5200        catalog=to_identifier(catalog, quoted=quoted),
5201        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5202    )

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

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:
5238def var(name: t.Optional[ExpOrStr]) -> Var:
5239    """Build a SQL variable.
5240
5241    Example:
5242        >>> repr(var('x'))
5243        '(VAR this: x)'
5244
5245        >>> repr(var(column('x', table='y')))
5246        '(VAR this: x)'
5247
5248    Args:
5249        name: The name of the var or an expression who's name will become the var.
5250
5251    Returns:
5252        The new variable node.
5253    """
5254    if not name:
5255        raise ValueError("Cannot convert empty name into var.")
5256
5257    if isinstance(name, Expression):
5258        name = name.name
5259    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:
5262def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5263    """Build ALTER TABLE... RENAME... expression
5264
5265    Args:
5266        old_name: The old name of the table
5267        new_name: The new name of the table
5268
5269    Returns:
5270        Alter table expression
5271    """
5272    old_table = to_table(old_name)
5273    new_table = to_table(new_name)
5274    return AlterTable(
5275        this=old_table,
5276        actions=[
5277            RenameTable(this=new_table),
5278        ],
5279    )

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:
5282def convert(value: t.Any, copy: bool = False) -> Expression:
5283    """Convert a python value into an expression object.
5284
5285    Raises an error if a conversion is not possible.
5286
5287    Args:
5288        value: A python object.
5289        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5290
5291    Returns:
5292        Expression: the equivalent expression object.
5293    """
5294    if isinstance(value, Expression):
5295        return _maybe_copy(value, copy)
5296    if isinstance(value, str):
5297        return Literal.string(value)
5298    if isinstance(value, bool):
5299        return Boolean(this=value)
5300    if value is None or (isinstance(value, float) and math.isnan(value)):
5301        return NULL
5302    if isinstance(value, numbers.Number):
5303        return Literal.number(value)
5304    if isinstance(value, datetime.datetime):
5305        datetime_literal = Literal.string(
5306            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5307        )
5308        return TimeStrToTime(this=datetime_literal)
5309    if isinstance(value, datetime.date):
5310        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5311        return DateStrToDate(this=date_literal)
5312    if isinstance(value, tuple):
5313        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5314    if isinstance(value, list):
5315        return Array(expressions=[convert(v, copy=copy) for v in value])
5316    if isinstance(value, dict):
5317        return Map(
5318            keys=[convert(k, copy=copy) for k in value],
5319            values=[convert(v, copy=copy) for v in value.values()],
5320        )
5321    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):
5324def replace_children(expression, fun, *args, **kwargs):
5325    """
5326    Replace children of an expression with the result of a lambda fun(child) -> exp.
5327    """
5328    for k, v in expression.args.items():
5329        is_list_arg = type(v) is list
5330
5331        child_nodes = v if is_list_arg else [v]
5332        new_child_nodes = []
5333
5334        for cn in child_nodes:
5335            if isinstance(cn, Expression):
5336                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5337                    new_child_nodes.append(child_node)
5338                    child_node.parent = expression
5339                    child_node.arg_key = k
5340            else:
5341                new_child_nodes.append(cn)
5342
5343        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):
5346def column_table_names(expression):
5347    """
5348    Return all table names referenced through columns in an expression.
5349
5350    Example:
5351        >>> import sqlglot
5352        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
5353        ['c', 'a']
5354
5355    Args:
5356        expression (sqlglot.Expression): expression to find table names
5357
5358    Returns:
5359        list: A list of unique names
5360    """
5361    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:
5364def table_name(table) -> str:
5365    """Get the full name of a table as a string.
5366
5367    Args:
5368        table (exp.Table | str): table expression node or string.
5369
5370    Examples:
5371        >>> from sqlglot import exp, parse_one
5372        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5373        'a.b.c'
5374
5375    Returns:
5376        The table name.
5377    """
5378
5379    table = maybe_parse(table, into=Table)
5380
5381    if not table:
5382        raise ValueError(f"Cannot parse {table}")
5383
5384    return ".".join(
5385        part
5386        for part in (
5387            table.text("catalog"),
5388            table.text("db"),
5389            table.name,
5390        )
5391        if part
5392    )

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):
5395def replace_tables(expression, mapping):
5396    """Replace all tables in expression according to the mapping.
5397
5398    Args:
5399        expression (sqlglot.Expression): expression node to be transformed and replaced.
5400        mapping (Dict[str, str]): mapping of table names.
5401
5402    Examples:
5403        >>> from sqlglot import exp, parse_one
5404        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5405        'SELECT * FROM c'
5406
5407    Returns:
5408        The mapped expression.
5409    """
5410
5411    def _replace_tables(node):
5412        if isinstance(node, Table):
5413            new_name = mapping.get(table_name(node))
5414            if new_name:
5415                return to_table(
5416                    new_name,
5417                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5418                )
5419        return node
5420
5421    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):
5424def replace_placeholders(expression, *args, **kwargs):
5425    """Replace placeholders in an expression.
5426
5427    Args:
5428        expression (sqlglot.Expression): expression node to be transformed and replaced.
5429        args: positional names that will substitute unnamed placeholders in the given order.
5430        kwargs: keyword arguments that will substitute named placeholders.
5431
5432    Examples:
5433        >>> from sqlglot import exp, parse_one
5434        >>> replace_placeholders(
5435        ...     parse_one("select * from :tbl where ? = ?"),
5436        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5437        ... ).sql()
5438        "SELECT * FROM foo WHERE str_col = 'b'"
5439
5440    Returns:
5441        The mapped expression.
5442    """
5443
5444    def _replace_placeholders(node, args, **kwargs):
5445        if isinstance(node, Placeholder):
5446            if node.name:
5447                new_name = kwargs.get(node.name)
5448                if new_name:
5449                    return convert(new_name)
5450            else:
5451                try:
5452                    return convert(next(args))
5453                except StopIteration:
5454                    pass
5455        return node
5456
5457    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:
5460def expand(
5461    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5462) -> Expression:
5463    """Transforms an expression by expanding all referenced sources into subqueries.
5464
5465    Examples:
5466        >>> from sqlglot import parse_one
5467        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5468        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5469
5470        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5471        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5472
5473    Args:
5474        expression: The expression to expand.
5475        sources: A dictionary of name to Subqueryables.
5476        copy: Whether or not to copy the expression during transformation. Defaults to True.
5477
5478    Returns:
5479        The transformed expression.
5480    """
5481
5482    def _expand(node: Expression):
5483        if isinstance(node, Table):
5484            name = table_name(node)
5485            source = sources.get(name)
5486            if source:
5487                subquery = source.subquery(node.alias or name)
5488                subquery.comments = [f"source: {name}"]
5489                return subquery.transform(_expand, copy=False)
5490        return node
5491
5492    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:
5495def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5496    """
5497    Returns a Func expression.
5498
5499    Examples:
5500        >>> func("abs", 5).sql()
5501        'ABS(5)'
5502
5503        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5504        'CAST(5 AS DOUBLE)'
5505
5506    Args:
5507        name: the name of the function to build.
5508        args: the args used to instantiate the function of interest.
5509        dialect: the source dialect.
5510        kwargs: the kwargs used to instantiate the function of interest.
5511
5512    Note:
5513        The arguments `args` and `kwargs` are mutually exclusive.
5514
5515    Returns:
5516        An instance of the function of interest, or an anonymous function, if `name` doesn't
5517        correspond to an existing `sqlglot.expressions.Func` class.
5518    """
5519    if args and kwargs:
5520        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5521
5522    from sqlglot.dialects.dialect import Dialect
5523
5524    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5525    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5526
5527    parser = Dialect.get_or_raise(dialect)().parser()
5528    from_args_list = parser.FUNCTIONS.get(name.upper())
5529
5530    if from_args_list:
5531        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5532    else:
5533        kwargs = kwargs or {"expressions": converted}
5534        function = Anonymous(this=name, **kwargs)
5535
5536    for error_message in function.error_messages(converted):
5537        raise ValueError(error_message)
5538
5539    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():
5542def true():
5543    """
5544    Returns a true Boolean expression.
5545    """
5546    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5549def false():
5550    """
5551    Returns a false Boolean expression.
5552    """
5553    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5556def null():
5557    """
5558    Returns a Null expression.
5559    """
5560    return Null()

Returns a Null expression.