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

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)
 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)
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:
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 ""

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):
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

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
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)
def append(self, arg_key, value):
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)

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):
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)

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

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

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
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)

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

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]:
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)

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

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
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)

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):
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)

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):
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))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
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

Returns the first non parenthesis child or self.

def unalias(self):
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

Returns the inner expression if this is an Alias.

def unnest_operands(self):
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())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
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

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:
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)

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):
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

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):
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

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):
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

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_):
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

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

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):
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)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
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)

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

class Condition(Expression):
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())
def and_(self, *expressions, dialect=None, copy=True, **opts):
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)

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):
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)

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):
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)

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:
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)
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy=True, **opts) -> sqlglot.expressions.In:
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        )
def between( self, low: Any, high: Any, copy=True, **opts) -> sqlglot.expressions.Between:
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        )
def is_( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Is:
756    def is_(self, other: ExpOrStr) -> Is:
757        return self._binop(Is, other)
def like( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Like:
759    def like(self, other: ExpOrStr) -> Like:
760        return self._binop(Like, other)
def ilike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.ILike:
762    def ilike(self, other: ExpOrStr) -> ILike:
763        return self._binop(ILike, other)
def eq(self, other: Any) -> sqlglot.expressions.EQ:
765    def eq(self, other: t.Any) -> EQ:
766        return self._binop(EQ, other)
def neq(self, other: Any) -> sqlglot.expressions.NEQ:
768    def neq(self, other: t.Any) -> NEQ:
769        return self._binop(NEQ, other)
def rlike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.RegexpLike:
771    def rlike(self, other: ExpOrStr) -> RegexpLike:
772        return self._binop(RegexpLike, other)
class Predicate(Condition):
847class Predicate(Condition):
848    """Relationships like x = y, x > 1, x >= y."""

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

class DerivedTable(Expression):
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]
class Unionable(Expression):
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)
def union(self, expression, distinct=True, dialect=None, **opts):
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)

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):
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)

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):
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)

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):
931class UDTF(DerivedTable, Unionable):
932    @property
933    def selects(self):
934        alias = self.args.get("alias")
935        return alias.columns if alias else []
class Cache(Expression):
938class Cache(Expression):
939    arg_types = {
940        "with": False,
941        "this": True,
942        "lazy": False,
943        "options": False,
944        "expression": False,
945    }
class Uncache(Expression):
948class Uncache(Expression):
949    arg_types = {"this": True, "exists": False}
class Create(Expression):
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    }
class Clone(Expression):
970class Clone(Expression):
971    arg_types = {
972        "this": True,
973        "when": False,
974        "kind": False,
975        "expression": False,
976    }
class Describe(Expression):
979class Describe(Expression):
980    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
983class Pragma(Expression):
984    pass
class Set(Expression):
987class Set(Expression):
988    arg_types = {"expressions": False}
class SetItem(Expression):
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    }
class Show(Expression):
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    }
class UserDefinedFunction(Expression):
1021class UserDefinedFunction(Expression):
1022    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
1025class CharacterSet(Expression):
1026    arg_types = {"this": True, "default": False}
class With(Expression):
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"))
class WithinGroup(Expression):
1037class WithinGroup(Expression):
1038    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
1041class CTE(DerivedTable):
1042    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
1045class TableAlias(Expression):
1046    arg_types = {"this": False, "columns": False}
1047
1048    @property
1049    def columns(self):
1050        return self.args.get("columns") or []
class BitString(Condition):
1053class BitString(Condition):
1054    pass
class HexString(Condition):
1057class HexString(Condition):
1058    pass
class ByteString(Condition):
1061class ByteString(Condition):
1062    pass
class Column(Condition):
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)
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:
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)

Converts the column into a dot expression.

class ColumnPosition(Expression):
1106class ColumnPosition(Expression):
1107    arg_types = {"this": False, "position": True}
class ColumnDef(Expression):
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 []
class AlterColumn(Expression):
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    }
class RenameTable(Expression):
1135class RenameTable(Expression):
1136    pass
class SetTag(Expression):
1139class SetTag(Expression):
1140    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
1143class Comment(Expression):
1144    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class MergeTreeTTLAction(Expression):
1148class MergeTreeTTLAction(Expression):
1149    arg_types = {
1150        "this": True,
1151        "delete": False,
1152        "recompress": False,
1153        "to_disk": False,
1154        "to_volume": False,
1155    }
class MergeTreeTTL(Expression):
1159class MergeTreeTTL(Expression):
1160    arg_types = {
1161        "expressions": True,
1162        "where": False,
1163        "group": False,
1164        "aggregates": False,
1165    }
class ColumnConstraint(Expression):
1168class ColumnConstraint(Expression):
1169    arg_types = {"this": False, "kind": True}
1170
1171    @property
1172    def kind(self) -> ColumnConstraintKind:
1173        return self.args["kind"]
class ColumnConstraintKind(Expression):
1176class ColumnConstraintKind(Expression):
1177    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1180class AutoIncrementColumnConstraint(ColumnConstraintKind):
1181    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1184class CaseSpecificColumnConstraint(ColumnConstraintKind):
1185    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1188class CharacterSetColumnConstraint(ColumnConstraintKind):
1189    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1192class CheckColumnConstraint(ColumnConstraintKind):
1193    pass
class CollateColumnConstraint(ColumnConstraintKind):
1196class CollateColumnConstraint(ColumnConstraintKind):
1197    pass
class CommentColumnConstraint(ColumnConstraintKind):
1200class CommentColumnConstraint(ColumnConstraintKind):
1201    pass
class CompressColumnConstraint(ColumnConstraintKind):
1204class CompressColumnConstraint(ColumnConstraintKind):
1205    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1208class DateFormatColumnConstraint(ColumnConstraintKind):
1209    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1212class DefaultColumnConstraint(ColumnConstraintKind):
1213    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1216class EncodeColumnConstraint(ColumnConstraintKind):
1217    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1220class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1221    # this: True -> ALWAYS, this: False -> BY DEFAULT
1222    arg_types = {
1223        "this": False,
1224        "expression": 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 AlgorithmProperty(Property):
1775class AlgorithmProperty(Property):
1776    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1779class AutoIncrementProperty(Property):
1780    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1783class BlockCompressionProperty(Property):
1784    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1787class CharacterSetProperty(Property):
1788    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1791class ChecksumProperty(Property):
1792    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1795class CollateProperty(Property):
1796    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1799class DataBlocksizeProperty(Property):
1800    arg_types = {
1801        "size": False,
1802        "units": False,
1803        "minimum": False,
1804        "maximum": False,
1805        "default": False,
1806    }
class DefinerProperty(Property):
1809class DefinerProperty(Property):
1810    arg_types = {"this": True}
class DistKeyProperty(Property):
1813class DistKeyProperty(Property):
1814    arg_types = {"this": True}
class DistStyleProperty(Property):
1817class DistStyleProperty(Property):
1818    arg_types = {"this": True}
class EngineProperty(Property):
1821class EngineProperty(Property):
1822    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1825class ExecuteAsProperty(Property):
1826    arg_types = {"this": True}
class ExternalProperty(Property):
1829class ExternalProperty(Property):
1830    arg_types = {"this": False}
class FallbackProperty(Property):
1833class FallbackProperty(Property):
1834    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1837class FileFormatProperty(Property):
1838    arg_types = {"this": True}
class FreespaceProperty(Property):
1841class FreespaceProperty(Property):
1842    arg_types = {"this": True, "percent": False}
class InputOutputFormat(Expression):
1845class InputOutputFormat(Expression):
1846    arg_types = {"input_format": False, "output_format": False}
class IsolatedLoadingProperty(Property):
1849class IsolatedLoadingProperty(Property):
1850    arg_types = {
1851        "no": True,
1852        "concurrent": True,
1853        "for_all": True,
1854        "for_insert": True,
1855        "for_none": True,
1856    }
class JournalProperty(Property):
1859class JournalProperty(Property):
1860    arg_types = {
1861        "no": False,
1862        "dual": False,
1863        "before": False,
1864        "local": False,
1865        "after": False,
1866    }
class LanguageProperty(Property):
1869class LanguageProperty(Property):
1870    arg_types = {"this": True}
class LikeProperty(Property):
1873class LikeProperty(Property):
1874    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1877class LocationProperty(Property):
1878    arg_types = {"this": True}
class LockingProperty(Property):
1881class LockingProperty(Property):
1882    arg_types = {
1883        "this": False,
1884        "kind": True,
1885        "for_or_in": True,
1886        "lock_type": True,
1887        "override": False,
1888    }
class LogProperty(Property):
1891class LogProperty(Property):
1892    arg_types = {"no": True}
class MaterializedProperty(Property):
1895class MaterializedProperty(Property):
1896    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1899class MergeBlockRatioProperty(Property):
1900    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1903class NoPrimaryIndexProperty(Property):
1904    arg_types = {}
class OnCommitProperty(Property):
1907class OnCommitProperty(Property):
1908    arg_type = {"delete": False}
class PartitionedByProperty(Property):
1911class PartitionedByProperty(Property):
1912    arg_types = {"this": True}
class ReturnsProperty(Property):
1915class ReturnsProperty(Property):
1916    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatProperty(Property):
1919class RowFormatProperty(Property):
1920    arg_types = {"this": True}
class RowFormatDelimitedProperty(Property):
1923class RowFormatDelimitedProperty(Property):
1924    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1925    arg_types = {
1926        "fields": False,
1927        "escaped": False,
1928        "collection_items": False,
1929        "map_keys": False,
1930        "lines": False,
1931        "null": False,
1932        "serde": False,
1933    }
class RowFormatSerdeProperty(Property):
1936class RowFormatSerdeProperty(Property):
1937    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1940class SchemaCommentProperty(Property):
1941    arg_types = {"this": True}
class SerdeProperties(Property):
1944class SerdeProperties(Property):
1945    arg_types = {"expressions": True}
class SetProperty(Property):
1948class SetProperty(Property):
1949    arg_types = {"multi": True}
class SettingsProperty(Property):
1952class SettingsProperty(Property):
1953    arg_types = {"expressions": True}
class SortKeyProperty(Property):
1956class SortKeyProperty(Property):
1957    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1960class SqlSecurityProperty(Property):
1961    arg_types = {"definer": True}
class StabilityProperty(Property):
1964class StabilityProperty(Property):
1965    arg_types = {"this": True}
class TemporaryProperty(Property):
1968class TemporaryProperty(Property):
1969    arg_types = {}
class TransientProperty(Property):
1972class TransientProperty(Property):
1973    arg_types = {"this": False}
class VolatileProperty(Property):
1976class VolatileProperty(Property):
1977    arg_types = {"this": False}
class WithDataProperty(Property):
1980class WithDataProperty(Property):
1981    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1984class WithJournalTableProperty(Property):
1985    arg_types = {"this": True}
class Properties(Expression):
1988class Properties(Expression):
1989    arg_types = {"expressions": True}
1990
1991    NAME_TO_PROPERTY = {
1992        "ALGORITHM": AlgorithmProperty,
1993        "AUTO_INCREMENT": AutoIncrementProperty,
1994        "CHARACTER SET": CharacterSetProperty,
1995        "COLLATE": CollateProperty,
1996        "COMMENT": SchemaCommentProperty,
1997        "DEFINER": DefinerProperty,
1998        "DISTKEY": DistKeyProperty,
1999        "DISTSTYLE": DistStyleProperty,
2000        "ENGINE": EngineProperty,
2001        "EXECUTE AS": ExecuteAsProperty,
2002        "FORMAT": FileFormatProperty,
2003        "LANGUAGE": LanguageProperty,
2004        "LOCATION": LocationProperty,
2005        "PARTITIONED_BY": PartitionedByProperty,
2006        "RETURNS": ReturnsProperty,
2007        "ROW_FORMAT": RowFormatProperty,
2008        "SORTKEY": SortKeyProperty,
2009    }
2010
2011    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2012
2013    # CREATE property locations
2014    # Form: schema specified
2015    #   create [POST_CREATE]
2016    #     table a [POST_NAME]
2017    #     (b int) [POST_SCHEMA]
2018    #     with ([POST_WITH])
2019    #     index (b) [POST_INDEX]
2020    #
2021    # Form: alias selection
2022    #   create [POST_CREATE]
2023    #     table a [POST_NAME]
2024    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2025    #     index (c) [POST_INDEX]
2026    class Location(AutoName):
2027        POST_CREATE = auto()
2028        POST_NAME = auto()
2029        POST_SCHEMA = auto()
2030        POST_WITH = auto()
2031        POST_ALIAS = auto()
2032        POST_EXPRESSION = auto()
2033        POST_INDEX = auto()
2034        UNSUPPORTED = auto()
2035
2036    @classmethod
2037    def from_dict(cls, properties_dict) -> Properties:
2038        expressions = []
2039        for key, value in properties_dict.items():
2040            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2041            if property_cls:
2042                expressions.append(property_cls(this=convert(value)))
2043            else:
2044                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2045
2046        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
2036    @classmethod
2037    def from_dict(cls, properties_dict) -> Properties:
2038        expressions = []
2039        for key, value in properties_dict.items():
2040            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2041            if property_cls:
2042                expressions.append(property_cls(this=convert(value)))
2043            else:
2044                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2045
2046        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
2026    class Location(AutoName):
2027        POST_CREATE = auto()
2028        POST_NAME = auto()
2029        POST_SCHEMA = auto()
2030        POST_WITH = auto()
2031        POST_ALIAS = auto()
2032        POST_EXPRESSION = auto()
2033        POST_INDEX = auto()
2034        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):
2049class Qualify(Expression):
2050    pass
class Return(Expression):
2054class Return(Expression):
2055    pass
class Reference(Expression):
2058class Reference(Expression):
2059    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
2062class Tuple(Expression):
2063    arg_types = {"expressions": False}
2064
2065    def isin(
2066        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
2067    ) -> In:
2068        return In(
2069            this=_maybe_copy(self, copy),
2070            expressions=[convert(e, copy=copy) for e in expressions],
2071            query=maybe_parse(query, copy=copy, **opts) if query else None,
2072        )
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy=True, **opts) -> sqlglot.expressions.In:
2065    def isin(
2066        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy=True, **opts
2067    ) -> In:
2068        return In(
2069            this=_maybe_copy(self, copy),
2070            expressions=[convert(e, copy=copy) for e in expressions],
2071            query=maybe_parse(query, copy=copy, **opts) if query else None,
2072        )
class Subqueryable(Unionable):
2075class Subqueryable(Unionable):
2076    def subquery(self, alias=None, copy=True) -> Subquery:
2077        """
2078        Convert this expression to an aliased expression that can be used as a Subquery.
2079
2080        Example:
2081            >>> subquery = Select().select("x").from_("tbl").subquery()
2082            >>> Select().select("x").from_(subquery).sql()
2083            'SELECT x FROM (SELECT x FROM tbl)'
2084
2085        Args:
2086            alias (str | Identifier): an optional alias for the subquery
2087            copy (bool): if `False`, modify this expression instance in-place.
2088
2089        Returns:
2090            Alias: the subquery
2091        """
2092        instance = _maybe_copy(self, copy)
2093        if not isinstance(alias, Expression):
2094            alias = TableAlias(this=to_identifier(alias)) if alias else None
2095
2096        return Subquery(this=instance, alias=alias)
2097
2098    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2099        raise NotImplementedError
2100
2101    @property
2102    def ctes(self):
2103        with_ = self.args.get("with")
2104        if not with_:
2105            return []
2106        return with_.expressions
2107
2108    @property
2109    def selects(self):
2110        raise NotImplementedError("Subqueryable objects must implement `selects`")
2111
2112    @property
2113    def named_selects(self):
2114        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2115
2116    def with_(
2117        self,
2118        alias: ExpOrStr,
2119        as_: ExpOrStr,
2120        recursive: t.Optional[bool] = None,
2121        append: bool = True,
2122        dialect: DialectType = None,
2123        copy: bool = True,
2124        **opts,
2125    ) -> Subqueryable:
2126        """
2127        Append to or set the common table expressions.
2128
2129        Example:
2130            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2131            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2132
2133        Args:
2134            alias: the SQL code string to parse as the table name.
2135                If an `Expression` instance is passed, this is used as-is.
2136            as_: the SQL code string to parse as the table expression.
2137                If an `Expression` instance is passed, it will be used as-is.
2138            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2139            append: if `True`, add to any existing expressions.
2140                Otherwise, this resets the expressions.
2141            dialect: the dialect used to parse the input expression.
2142            copy: if `False`, modify this expression instance in-place.
2143            opts: other options to use to parse the input expressions.
2144
2145        Returns:
2146            The modified expression.
2147        """
2148        return _apply_cte_builder(
2149            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2150        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
2076    def subquery(self, alias=None, copy=True) -> Subquery:
2077        """
2078        Convert this expression to an aliased expression that can be used as a Subquery.
2079
2080        Example:
2081            >>> subquery = Select().select("x").from_("tbl").subquery()
2082            >>> Select().select("x").from_(subquery).sql()
2083            'SELECT x FROM (SELECT x FROM tbl)'
2084
2085        Args:
2086            alias (str | Identifier): an optional alias for the subquery
2087            copy (bool): if `False`, modify this expression instance in-place.
2088
2089        Returns:
2090            Alias: the subquery
2091        """
2092        instance = _maybe_copy(self, copy)
2093        if not isinstance(alias, Expression):
2094            alias = TableAlias(this=to_identifier(alias)) if alias else None
2095
2096        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:
2098    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2099        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:
2116    def with_(
2117        self,
2118        alias: ExpOrStr,
2119        as_: ExpOrStr,
2120        recursive: t.Optional[bool] = None,
2121        append: bool = True,
2122        dialect: DialectType = None,
2123        copy: bool = True,
2124        **opts,
2125    ) -> Subqueryable:
2126        """
2127        Append to or set the common table expressions.
2128
2129        Example:
2130            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2131            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2132
2133        Args:
2134            alias: the SQL code string to parse as the table name.
2135                If an `Expression` instance is passed, this is used as-is.
2136            as_: the SQL code string to parse as the table expression.
2137                If an `Expression` instance is passed, it will be used as-is.
2138            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2139            append: if `True`, add to any existing expressions.
2140                Otherwise, this resets the expressions.
2141            dialect: the dialect used to parse the input expression.
2142            copy: if `False`, modify this expression instance in-place.
2143            opts: other options to use to parse the input expressions.
2144
2145        Returns:
2146            The modified expression.
2147        """
2148        return _apply_cte_builder(
2149            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2150        )

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2997class Pivot(Expression):
2998    arg_types = {
2999        "alias": False,
3000        "expressions": True,
3001        "field": True,
3002        "unpivot": True,
3003        "columns": False,
3004    }
class Window(Expression):
3007class Window(Expression):
3008    arg_types = {
3009        "this": True,
3010        "partition_by": False,
3011        "order": False,
3012        "spec": False,
3013        "alias": False,
3014        "over": False,
3015        "first": False,
3016    }
class WindowSpec(Expression):
3019class WindowSpec(Expression):
3020    arg_types = {
3021        "kind": False,
3022        "start": False,
3023        "start_side": False,
3024        "end": False,
3025        "end_side": False,
3026    }
class Where(Expression):
3029class Where(Expression):
3030    pass
class Star(Expression):
3033class Star(Expression):
3034    arg_types = {"except": False, "replace": False}
3035
3036    @property
3037    def name(self) -> str:
3038        return "*"
3039
3040    @property
3041    def output_name(self):
3042        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):
3045class Parameter(Expression):
3046    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
3049class SessionParameter(Expression):
3050    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
3053class Placeholder(Expression):
3054    arg_types = {"this": False, "kind": False}
class Null(Condition):
3057class Null(Condition):
3058    arg_types: t.Dict[str, t.Any] = {}
3059
3060    @property
3061    def name(self) -> str:
3062        return "NULL"
class Boolean(Condition):
3065class Boolean(Condition):
3066    pass
class DataTypeSize(Expression):
3069class DataTypeSize(Expression):
3070    arg_types = {"this": True, "expression": False}
class DataType(Expression):
3073class DataType(Expression):
3074    arg_types = {
3075        "this": True,
3076        "expressions": False,
3077        "nested": False,
3078        "values": False,
3079        "prefix": False,
3080    }
3081
3082    class Type(AutoName):
3083        ARRAY = auto()
3084        BIGDECIMAL = auto()
3085        BIGINT = auto()
3086        BIGSERIAL = auto()
3087        BINARY = auto()
3088        BIT = auto()
3089        BOOLEAN = auto()
3090        CHAR = auto()
3091        DATE = auto()
3092        DATETIME = auto()
3093        DATETIME64 = auto()
3094        DECIMAL = auto()
3095        DOUBLE = auto()
3096        FLOAT = auto()
3097        GEOGRAPHY = auto()
3098        GEOMETRY = auto()
3099        HLLSKETCH = auto()
3100        HSTORE = auto()
3101        IMAGE = auto()
3102        INET = auto()
3103        INT = auto()
3104        INT128 = auto()
3105        INT256 = auto()
3106        INTERVAL = auto()
3107        JSON = auto()
3108        JSONB = auto()
3109        LONGBLOB = auto()
3110        LONGTEXT = auto()
3111        MAP = auto()
3112        MEDIUMBLOB = auto()
3113        MEDIUMTEXT = auto()
3114        MONEY = auto()
3115        NCHAR = auto()
3116        NULL = auto()
3117        NULLABLE = auto()
3118        NVARCHAR = auto()
3119        OBJECT = auto()
3120        ROWVERSION = auto()
3121        SERIAL = auto()
3122        SMALLINT = auto()
3123        SMALLMONEY = auto()
3124        SMALLSERIAL = auto()
3125        STRUCT = auto()
3126        SUPER = auto()
3127        TEXT = auto()
3128        TIME = auto()
3129        TIMESTAMP = auto()
3130        TIMESTAMPTZ = auto()
3131        TIMESTAMPLTZ = auto()
3132        TINYINT = auto()
3133        UBIGINT = auto()
3134        UINT = auto()
3135        USMALLINT = auto()
3136        UTINYINT = auto()
3137        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3138        UINT128 = auto()
3139        UINT256 = auto()
3140        UNIQUEIDENTIFIER = auto()
3141        UUID = auto()
3142        VARBINARY = auto()
3143        VARCHAR = auto()
3144        VARIANT = auto()
3145        XML = auto()
3146
3147    TEXT_TYPES = {
3148        Type.CHAR,
3149        Type.NCHAR,
3150        Type.VARCHAR,
3151        Type.NVARCHAR,
3152        Type.TEXT,
3153    }
3154
3155    INTEGER_TYPES = {
3156        Type.INT,
3157        Type.TINYINT,
3158        Type.SMALLINT,
3159        Type.BIGINT,
3160        Type.INT128,
3161        Type.INT256,
3162    }
3163
3164    FLOAT_TYPES = {
3165        Type.FLOAT,
3166        Type.DOUBLE,
3167    }
3168
3169    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3170
3171    TEMPORAL_TYPES = {
3172        Type.TIMESTAMP,
3173        Type.TIMESTAMPTZ,
3174        Type.TIMESTAMPLTZ,
3175        Type.DATE,
3176        Type.DATETIME,
3177        Type.DATETIME64,
3178    }
3179
3180    @classmethod
3181    def build(
3182        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3183    ) -> DataType:
3184        from sqlglot import parse_one
3185
3186        if isinstance(dtype, str):
3187            if dtype.upper() in cls.Type.__members__:
3188                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3189            else:
3190                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3191
3192            if data_type_exp is None:
3193                raise ValueError(f"Unparsable data type value: {dtype}")
3194        elif isinstance(dtype, DataType.Type):
3195            data_type_exp = DataType(this=dtype)
3196        elif isinstance(dtype, DataType):
3197            return dtype
3198        else:
3199            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3200
3201        return DataType(**{**data_type_exp.args, **kwargs})
3202
3203    def is_type(self, dtype: DataType.Type) -> bool:
3204        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:
3180    @classmethod
3181    def build(
3182        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3183    ) -> DataType:
3184        from sqlglot import parse_one
3185
3186        if isinstance(dtype, str):
3187            if dtype.upper() in cls.Type.__members__:
3188                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
3189            else:
3190                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3191
3192            if data_type_exp is None:
3193                raise ValueError(f"Unparsable data type value: {dtype}")
3194        elif isinstance(dtype, DataType.Type):
3195            data_type_exp = DataType(this=dtype)
3196        elif isinstance(dtype, DataType):
3197            return dtype
3198        else:
3199            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3200
3201        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3203    def is_type(self, dtype: DataType.Type) -> bool:
3204        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
3082    class Type(AutoName):
3083        ARRAY = auto()
3084        BIGDECIMAL = auto()
3085        BIGINT = auto()
3086        BIGSERIAL = auto()
3087        BINARY = auto()
3088        BIT = auto()
3089        BOOLEAN = auto()
3090        CHAR = auto()
3091        DATE = auto()
3092        DATETIME = auto()
3093        DATETIME64 = auto()
3094        DECIMAL = auto()
3095        DOUBLE = auto()
3096        FLOAT = auto()
3097        GEOGRAPHY = auto()
3098        GEOMETRY = auto()
3099        HLLSKETCH = auto()
3100        HSTORE = auto()
3101        IMAGE = auto()
3102        INET = auto()
3103        INT = auto()
3104        INT128 = auto()
3105        INT256 = auto()
3106        INTERVAL = auto()
3107        JSON = auto()
3108        JSONB = auto()
3109        LONGBLOB = auto()
3110        LONGTEXT = auto()
3111        MAP = auto()
3112        MEDIUMBLOB = auto()
3113        MEDIUMTEXT = auto()
3114        MONEY = auto()
3115        NCHAR = auto()
3116        NULL = auto()
3117        NULLABLE = auto()
3118        NVARCHAR = auto()
3119        OBJECT = auto()
3120        ROWVERSION = auto()
3121        SERIAL = auto()
3122        SMALLINT = auto()
3123        SMALLMONEY = auto()
3124        SMALLSERIAL = auto()
3125        STRUCT = auto()
3126        SUPER = auto()
3127        TEXT = auto()
3128        TIME = auto()
3129        TIMESTAMP = auto()
3130        TIMESTAMPTZ = auto()
3131        TIMESTAMPLTZ = auto()
3132        TINYINT = auto()
3133        UBIGINT = auto()
3134        UINT = auto()
3135        USMALLINT = auto()
3136        UTINYINT = auto()
3137        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3138        UINT128 = auto()
3139        UINT256 = auto()
3140        UNIQUEIDENTIFIER = auto()
3141        UUID = auto()
3142        VARBINARY = auto()
3143        VARCHAR = auto()
3144        VARIANT = auto()
3145        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):
3208class PseudoType(Expression):
3209    pass
class SubqueryPredicate(Predicate):
3213class SubqueryPredicate(Predicate):
3214    pass
class All(SubqueryPredicate):
3217class All(SubqueryPredicate):
3218    pass
class Any(SubqueryPredicate):
3221class Any(SubqueryPredicate):
3222    pass
class Exists(SubqueryPredicate):
3225class Exists(SubqueryPredicate):
3226    pass
class Command(Expression):
3231class Command(Expression):
3232    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
3235class Transaction(Expression):
3236    arg_types = {"this": False, "modes": False}
class Commit(Expression):
3239class Commit(Expression):
3240    arg_types = {"chain": False}
class Rollback(Expression):
3243class Rollback(Expression):
3244    arg_types = {"savepoint": False}
class AlterTable(Expression):
3247class AlterTable(Expression):
3248    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
3251class AddConstraint(Expression):
3252    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
3255class DropPartition(Expression):
3256    arg_types = {"expressions": True, "exists": False}
class Binary(Condition):
3260class Binary(Condition):
3261    arg_types = {"this": True, "expression": True}
3262
3263    @property
3264    def left(self):
3265        return self.this
3266
3267    @property
3268    def right(self):
3269        return self.expression
class Add(Binary):
3272class Add(Binary):
3273    pass
class Connector(Binary):
3276class Connector(Binary):
3277    pass
class And(Connector):
3280class And(Connector):
3281    pass
class Or(Connector):
3284class Or(Connector):
3285    pass
class BitwiseAnd(Binary):
3288class BitwiseAnd(Binary):
3289    pass
class BitwiseLeftShift(Binary):
3292class BitwiseLeftShift(Binary):
3293    pass
class BitwiseOr(Binary):
3296class BitwiseOr(Binary):
3297    pass
class BitwiseRightShift(Binary):
3300class BitwiseRightShift(Binary):
3301    pass
class BitwiseXor(Binary):
3304class BitwiseXor(Binary):
3305    pass
class Div(Binary):
3308class Div(Binary):
3309    pass
class Overlaps(Binary):
3312class Overlaps(Binary):
3313    pass
class Dot(Binary):
3316class Dot(Binary):
3317    @property
3318    def name(self) -> str:
3319        return self.expression.name
3320
3321    @classmethod
3322    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3323        """Build a Dot object with a sequence of expressions."""
3324        if len(expressions) < 2:
3325            raise ValueError(f"Dot requires >= 2 expressions.")
3326
3327        a, b, *expressions = expressions
3328        dot = Dot(this=a, expression=b)
3329
3330        for expression in expressions:
3331            dot = Dot(this=dot, expression=expression)
3332
3333        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3321    @classmethod
3322    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3323        """Build a Dot object with a sequence of expressions."""
3324        if len(expressions) < 2:
3325            raise ValueError(f"Dot requires >= 2 expressions.")
3326
3327        a, b, *expressions = expressions
3328        dot = Dot(this=a, expression=b)
3329
3330        for expression in expressions:
3331            dot = Dot(this=dot, expression=expression)
3332
3333        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3336class DPipe(Binary):
3337    pass
class EQ(Binary, Predicate):
3340class EQ(Binary, Predicate):
3341    pass
class NullSafeEQ(Binary, Predicate):
3344class NullSafeEQ(Binary, Predicate):
3345    pass
class NullSafeNEQ(Binary, Predicate):
3348class NullSafeNEQ(Binary, Predicate):
3349    pass
class Distance(Binary):
3352class Distance(Binary):
3353    pass
class Escape(Binary):
3356class Escape(Binary):
3357    pass
class Glob(Binary, Predicate):
3360class Glob(Binary, Predicate):
3361    pass
class GT(Binary, Predicate):
3364class GT(Binary, Predicate):
3365    pass
class GTE(Binary, Predicate):
3368class GTE(Binary, Predicate):
3369    pass
class ILike(Binary, Predicate):
3372class ILike(Binary, Predicate):
3373    pass
class ILikeAny(Binary, Predicate):
3376class ILikeAny(Binary, Predicate):
3377    pass
class IntDiv(Binary):
3380class IntDiv(Binary):
3381    pass
class Is(Binary, Predicate):
3384class Is(Binary, Predicate):
3385    pass
class Kwarg(Binary):
3388class Kwarg(Binary):
3389    """Kwarg in special functions like func(kwarg => y)."""

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

class Like(Binary, Predicate):
3392class Like(Binary, Predicate):
3393    pass
class LikeAny(Binary, Predicate):
3396class LikeAny(Binary, Predicate):
3397    pass
class LT(Binary, Predicate):
3400class LT(Binary, Predicate):
3401    pass
class LTE(Binary, Predicate):
3404class LTE(Binary, Predicate):
3405    pass
class Mod(Binary):
3408class Mod(Binary):
3409    pass
class Mul(Binary):
3412class Mul(Binary):
3413    pass
class NEQ(Binary, Predicate):
3416class NEQ(Binary, Predicate):
3417    pass
class SimilarTo(Binary, Predicate):
3420class SimilarTo(Binary, Predicate):
3421    pass
class Slice(Binary):
3424class Slice(Binary):
3425    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3428class Sub(Binary):
3429    pass
class ArrayOverlaps(Binary):
3432class ArrayOverlaps(Binary):
3433    pass
class Unary(Condition):
3438class Unary(Condition):
3439    pass
class BitwiseNot(Unary):
3442class BitwiseNot(Unary):
3443    pass
class Not(Unary):
3446class Not(Unary):
3447    pass
class Paren(Unary):
3450class Paren(Unary):
3451    arg_types = {"this": True, "with": False}
class Neg(Unary):
3454class Neg(Unary):
3455    pass
class Alias(Expression):
3458class Alias(Expression):
3459    arg_types = {"this": True, "alias": False}
3460
3461    @property
3462    def output_name(self):
3463        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):
3466class Aliases(Expression):
3467    arg_types = {"this": True, "expressions": True}
3468
3469    @property
3470    def aliases(self):
3471        return self.expressions
class AtTimeZone(Expression):
3474class AtTimeZone(Expression):
3475    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3478class Between(Predicate):
3479    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3482class Bracket(Condition):
3483    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3486class Distinct(Expression):
3487    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3490class In(Predicate):
3491    arg_types = {
3492        "this": True,
3493        "expressions": False,
3494        "query": False,
3495        "unnest": False,
3496        "field": False,
3497        "is_global": False,
3498    }
class TimeUnit(Expression):
3501class TimeUnit(Expression):
3502    """Automatically converts unit arg into a var."""
3503
3504    arg_types = {"unit": False}
3505
3506    def __init__(self, **args):
3507        unit = args.get("unit")
3508        if isinstance(unit, (Column, Literal)):
3509            args["unit"] = Var(this=unit.name)
3510        elif isinstance(unit, Week):
3511            unit.set("this", Var(this=unit.this.name))
3512        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3506    def __init__(self, **args):
3507        unit = args.get("unit")
3508        if isinstance(unit, (Column, Literal)):
3509            args["unit"] = Var(this=unit.name)
3510        elif isinstance(unit, Week):
3511            unit.set("this", Var(this=unit.this.name))
3512        super().__init__(**args)
class Interval(TimeUnit):
3515class Interval(TimeUnit):
3516    arg_types = {"this": False, "unit": False}
3517
3518    @property
3519    def unit(self) -> t.Optional[Var]:
3520        return self.args.get("unit")
class IgnoreNulls(Expression):
3523class IgnoreNulls(Expression):
3524    pass
class RespectNulls(Expression):
3527class RespectNulls(Expression):
3528    pass
class Func(Condition):
3532class Func(Condition):
3533    """
3534    The base class for all function expressions.
3535
3536    Attributes:
3537        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3538            treated as a variable length argument and the argument's value will be stored as a list.
3539        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3540            for this function expression. These values are used to map this node to a name during parsing
3541            as well as to provide the function's name during SQL string generation. By default the SQL
3542            name is set to the expression's class name transformed to snake case.
3543    """
3544
3545    is_var_len_args = False
3546
3547    @classmethod
3548    def from_arg_list(cls, args):
3549        if cls.is_var_len_args:
3550            all_arg_keys = list(cls.arg_types)
3551            # If this function supports variable length argument treat the last argument as such.
3552            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3553            num_non_var = len(non_var_len_arg_keys)
3554
3555            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3556            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3557        else:
3558            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3559
3560        return cls(**args_dict)
3561
3562    @classmethod
3563    def sql_names(cls):
3564        if cls is Func:
3565            raise NotImplementedError(
3566                "SQL name is only supported by concrete function implementations"
3567            )
3568        if "_sql_names" not in cls.__dict__:
3569            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3570        return cls._sql_names
3571
3572    @classmethod
3573    def sql_name(cls):
3574        return cls.sql_names()[0]
3575
3576    @classmethod
3577    def default_parser_mappings(cls):
3578        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):
3547    @classmethod
3548    def from_arg_list(cls, args):
3549        if cls.is_var_len_args:
3550            all_arg_keys = list(cls.arg_types)
3551            # If this function supports variable length argument treat the last argument as such.
3552            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3553            num_non_var = len(non_var_len_arg_keys)
3554
3555            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3556            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3557        else:
3558            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3559
3560        return cls(**args_dict)
@classmethod
def sql_names(cls):
3562    @classmethod
3563    def sql_names(cls):
3564        if cls is Func:
3565            raise NotImplementedError(
3566                "SQL name is only supported by concrete function implementations"
3567            )
3568        if "_sql_names" not in cls.__dict__:
3569            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3570        return cls._sql_names
@classmethod
def sql_name(cls):
3572    @classmethod
3573    def sql_name(cls):
3574        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3576    @classmethod
3577    def default_parser_mappings(cls):
3578        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3581class AggFunc(Func):
3582    pass
class ParameterizedAgg(AggFunc):
3585class ParameterizedAgg(AggFunc):
3586    arg_types = {"this": True, "expressions": True, "params": True}
class Abs(Func):
3589class Abs(Func):
3590    pass
class Anonymous(Func):
3593class Anonymous(Func):
3594    arg_types = {"this": True, "expressions": False}
3595    is_var_len_args = True
class Hll(AggFunc):
3600class Hll(AggFunc):
3601    arg_types = {"this": True, "expressions": False}
3602    is_var_len_args = True
class ApproxDistinct(AggFunc):
3605class ApproxDistinct(AggFunc):
3606    arg_types = {"this": True, "accuracy": False}
3607    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
class Array(Func):
3610class Array(Func):
3611    arg_types = {"expressions": False}
3612    is_var_len_args = True
class ToChar(Func):
3616class ToChar(Func):
3617    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3620class GenerateSeries(Func):
3621    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3624class ArrayAgg(AggFunc):
3625    pass
class ArrayAll(Func):
3628class ArrayAll(Func):
3629    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3632class ArrayAny(Func):
3633    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3636class ArrayConcat(Func):
3637    arg_types = {"this": True, "expressions": False}
3638    is_var_len_args = True
class ArrayContains(Binary, Func):
3641class ArrayContains(Binary, Func):
3642    pass
class ArrayContained(Binary):
3645class ArrayContained(Binary):
3646    pass
class ArrayFilter(Func):
3649class ArrayFilter(Func):
3650    arg_types = {"this": True, "expression": True}
3651    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3654class ArrayJoin(Func):
3655    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3658class ArraySize(Func):
3659    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3662class ArraySort(Func):
3663    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3666class ArraySum(Func):
3667    pass
class ArrayUnionAgg(AggFunc):
3670class ArrayUnionAgg(AggFunc):
3671    pass
class Avg(AggFunc):
3674class Avg(AggFunc):
3675    pass
class AnyValue(AggFunc):
3678class AnyValue(AggFunc):
3679    pass
class Case(Func):
3682class Case(Func):
3683    arg_types = {"this": False, "ifs": True, "default": False}
3684
3685    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3686        instance = _maybe_copy(self, copy)
3687        instance.append(
3688            "ifs",
3689            If(
3690                this=maybe_parse(condition, copy=copy, **opts),
3691                true=maybe_parse(then, copy=copy, **opts),
3692            ),
3693        )
3694        return instance
3695
3696    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3697        instance = _maybe_copy(self, copy)
3698        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3699        return instance
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3685    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3686        instance = _maybe_copy(self, copy)
3687        instance.append(
3688            "ifs",
3689            If(
3690                this=maybe_parse(condition, copy=copy, **opts),
3691                true=maybe_parse(then, copy=copy, **opts),
3692            ),
3693        )
3694        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3696    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3697        instance = _maybe_copy(self, copy)
3698        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3699        return instance
class Cast(Func):
3702class Cast(Func):
3703    arg_types = {"this": True, "to": True}
3704
3705    @property
3706    def name(self) -> str:
3707        return self.this.name
3708
3709    @property
3710    def to(self):
3711        return self.args["to"]
3712
3713    @property
3714    def output_name(self):
3715        return self.name
3716
3717    def is_type(self, dtype: DataType.Type) -> bool:
3718        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:
3717    def is_type(self, dtype: DataType.Type) -> bool:
3718        return self.to.is_type(dtype)
class CastToStrType(Func):
3721class CastToStrType(Func):
3722    arg_types = {"this": True, "expression": True}
class Collate(Binary):
3725class Collate(Binary):
3726    pass
class TryCast(Cast):
3729class TryCast(Cast):
3730    pass
class Ceil(Func):
3733class Ceil(Func):
3734    arg_types = {"this": True, "decimals": False}
3735    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3738class Coalesce(Func):
3739    arg_types = {"this": True, "expressions": False}
3740    is_var_len_args = True
class Concat(Func):
3743class Concat(Func):
3744    arg_types = {"expressions": True}
3745    is_var_len_args = True
class ConcatWs(Concat):
3748class ConcatWs(Concat):
3749    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3752class Count(AggFunc):
3753    arg_types = {"this": False}
class CountIf(AggFunc):
3756class CountIf(AggFunc):
3757    pass
class CurrentDate(Func):
3760class CurrentDate(Func):
3761    arg_types = {"this": False}
class CurrentDatetime(Func):
3764class CurrentDatetime(Func):
3765    arg_types = {"this": False}
class CurrentTime(Func):
3768class CurrentTime(Func):
3769    arg_types = {"this": False}
class CurrentTimestamp(Func):
3772class CurrentTimestamp(Func):
3773    arg_types = {"this": False}
class CurrentUser(Func):
3776class CurrentUser(Func):
3777    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3780class DateAdd(Func, TimeUnit):
3781    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3784class DateSub(Func, TimeUnit):
3785    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3788class DateDiff(Func, TimeUnit):
3789    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3790    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3793class DateTrunc(Func):
3794    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3797class DatetimeAdd(Func, TimeUnit):
3798    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3801class DatetimeSub(Func, TimeUnit):
3802    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3805class DatetimeDiff(Func, TimeUnit):
3806    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3809class DatetimeTrunc(Func, TimeUnit):
3810    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3813class DayOfWeek(Func):
3814    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3817class DayOfMonth(Func):
3818    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3821class DayOfYear(Func):
3822    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3825class WeekOfYear(Func):
3826    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3829class LastDateOfMonth(Func):
3830    pass
class Extract(Func):
3833class Extract(Func):
3834    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3837class TimestampAdd(Func, TimeUnit):
3838    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3841class TimestampSub(Func, TimeUnit):
3842    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3845class TimestampDiff(Func, TimeUnit):
3846    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3849class TimestampTrunc(Func, TimeUnit):
3850    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3853class TimeAdd(Func, TimeUnit):
3854    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3857class TimeSub(Func, TimeUnit):
3858    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3861class TimeDiff(Func, TimeUnit):
3862    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3865class TimeTrunc(Func, TimeUnit):
3866    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3869class DateFromParts(Func):
3870    _sql_names = ["DATEFROMPARTS"]
3871    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3874class DateStrToDate(Func):
3875    pass
class DateToDateStr(Func):
3878class DateToDateStr(Func):
3879    pass
class DateToDi(Func):
3882class DateToDi(Func):
3883    pass
class Day(Func):
3886class Day(Func):
3887    pass
class Decode(Func):
3890class Decode(Func):
3891    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3894class DiToDate(Func):
3895    pass
class Encode(Func):
3898class Encode(Func):
3899    arg_types = {"this": True, "charset": True}
class Exp(Func):
3902class Exp(Func):
3903    pass
class Explode(Func):
3906class Explode(Func):
3907    pass
class Floor(Func):
3910class Floor(Func):
3911    arg_types = {"this": True, "decimals": False}
class FromBase64(Func):
3914class FromBase64(Func):
3915    pass
class ToBase64(Func):
3918class ToBase64(Func):
3919    pass
class Greatest(Func):
3922class Greatest(Func):
3923    arg_types = {"this": True, "expressions": False}
3924    is_var_len_args = True
class GroupConcat(Func):
3927class GroupConcat(Func):
3928    arg_types = {"this": True, "separator": False}
class Hex(Func):
3931class Hex(Func):
3932    pass
class If(Func):
3935class If(Func):
3936    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3939class IfNull(Func):
3940    arg_types = {"this": True, "expression": False}
3941    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3944class Initcap(Func):
3945    arg_types = {"this": True, "expression": False}
class JSONKeyValue(Expression):
3948class JSONKeyValue(Expression):
3949    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
3952class JSONObject(Func):
3953    arg_types = {
3954        "expressions": False,
3955        "null_handling": False,
3956        "unique_keys": False,
3957        "return_type": False,
3958        "format_json": False,
3959        "encoding": False,
3960    }
class OpenJSONColumnDef(Expression):
3963class OpenJSONColumnDef(Expression):
3964    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
class OpenJSON(Func):
3967class OpenJSON(Func):
3968    arg_types = {"this": True, "path": False, "expressions": False}
class JSONBContains(Binary):
3971class JSONBContains(Binary):
3972    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3975class JSONExtract(Binary, Func):
3976    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3979class JSONExtractScalar(JSONExtract):
3980    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3983class JSONBExtract(JSONExtract):
3984    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3987class JSONBExtractScalar(JSONExtract):
3988    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
3991class JSONFormat(Func):
3992    arg_types = {"this": False, "options": False}
3993    _sql_names = ["JSON_FORMAT"]
class Least(Func):
3996class Least(Func):
3997    arg_types = {"expressions": False}
3998    is_var_len_args = True
class Length(Func):
4001class Length(Func):
4002    pass
class Levenshtein(Func):
4005class Levenshtein(Func):
4006    arg_types = {
4007        "this": True,
4008        "expression": False,
4009        "ins_cost": False,
4010        "del_cost": False,
4011        "sub_cost": False,
4012    }
class Ln(Func):
4015class Ln(Func):
4016    pass
class Log(Func):
4019class Log(Func):
4020    arg_types = {"this": True, "expression": False}
class Log2(Func):
4023class Log2(Func):
4024    pass
class Log10(Func):
4027class Log10(Func):
4028    pass
class LogicalOr(AggFunc):
4031class LogicalOr(AggFunc):
4032    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
4035class LogicalAnd(AggFunc):
4036    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
4039class Lower(Func):
4040    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
4043class Map(Func):
4044    arg_types = {"keys": False, "values": False}
class StarMap(Func):
4047class StarMap(Func):
4048    pass
class VarMap(Func):
4051class VarMap(Func):
4052    arg_types = {"keys": True, "values": True}
4053    is_var_len_args = True
class MatchAgainst(Func):
4057class MatchAgainst(Func):
4058    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
4061class Max(AggFunc):
4062    arg_types = {"this": True, "expressions": False}
4063    is_var_len_args = True
class MD5(Func):
4066class MD5(Func):
4067    _sql_names = ["MD5"]
class Min(AggFunc):
4070class Min(AggFunc):
4071    arg_types = {"this": True, "expressions": False}
4072    is_var_len_args = True
class Month(Func):
4075class Month(Func):
4076    pass
class Nvl2(Func):
4079class Nvl2(Func):
4080    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
4083class Posexplode(Func):
4084    pass
class Pow(Binary, Func):
4087class Pow(Binary, Func):
4088    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
4091class PercentileCont(AggFunc):
4092    arg_types = {"this": True, "expression": False}
class PercentileDisc(AggFunc):
4095class PercentileDisc(AggFunc):
4096    arg_types = {"this": True, "expression": False}
class Quantile(AggFunc):
4099class Quantile(AggFunc):
4100    arg_types = {"this": True, "quantile": True}
class ApproxQuantile(Quantile):
4103class ApproxQuantile(Quantile):
4104    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
4107class RangeN(Func):
4108    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
4111class ReadCSV(Func):
4112    _sql_names = ["READ_CSV"]
4113    is_var_len_args = True
4114    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
4117class Reduce(Func):
4118    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
4121class RegexpExtract(Func):
4122    arg_types = {
4123        "this": True,
4124        "expression": True,
4125        "position": False,
4126        "occurrence": False,
4127        "group": False,
4128    }
class RegexpLike(Func):
4131class RegexpLike(Func):
4132    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
4135class RegexpILike(Func):
4136    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
4141class RegexpSplit(Func):
4142    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
4145class Repeat(Func):
4146    arg_types = {"this": True, "times": True}
class Round(Func):
4149class Round(Func):
4150    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
4153class RowNumber(Func):
4154    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
4157class SafeDivide(Func):
4158    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
4161class SetAgg(AggFunc):
4162    pass
class SHA(Func):
4165class SHA(Func):
4166    _sql_names = ["SHA", "SHA1"]
class SHA2(Func):
4169class SHA2(Func):
4170    _sql_names = ["SHA2"]
4171    arg_types = {"this": True, "length": False}
class SortArray(Func):
4174class SortArray(Func):
4175    arg_types = {"this": True, "asc": False}
class Split(Func):
4178class Split(Func):
4179    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
4184class Substring(Func):
4185    arg_types = {"this": True, "start": False, "length": False}
class StandardHash(Func):
4188class StandardHash(Func):
4189    arg_types = {"this": True, "expression": False}
class StrPosition(Func):
4192class StrPosition(Func):
4193    arg_types = {
4194        "this": True,
4195        "substr": True,
4196        "position": False,
4197        "instance": False,
4198    }
class StrToDate(Func):
4201class StrToDate(Func):
4202    arg_types = {"this": True, "format": True}
class StrToTime(Func):
4205class StrToTime(Func):
4206    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
4211class StrToUnix(Func):
4212    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
4215class NumberToStr(Func):
4216    arg_types = {"this": True, "format": True}
class Struct(Func):
4219class Struct(Func):
4220    arg_types = {"expressions": True}
4221    is_var_len_args = True
class StructExtract(Func):
4224class StructExtract(Func):
4225    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
4228class Sum(AggFunc):
4229    pass
class Sqrt(Func):
4232class Sqrt(Func):
4233    pass
class Stddev(AggFunc):
4236class Stddev(AggFunc):
4237    pass
class StddevPop(AggFunc):
4240class StddevPop(AggFunc):
4241    pass
class StddevSamp(AggFunc):
4244class StddevSamp(AggFunc):
4245    pass
class TimeToStr(Func):
4248class TimeToStr(Func):
4249    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
4252class TimeToTimeStr(Func):
4253    pass
class TimeToUnix(Func):
4256class TimeToUnix(Func):
4257    pass
class TimeStrToDate(Func):
4260class TimeStrToDate(Func):
4261    pass
class TimeStrToTime(Func):
4264class TimeStrToTime(Func):
4265    pass
class TimeStrToUnix(Func):
4268class TimeStrToUnix(Func):
4269    pass
class Trim(Func):
4272class Trim(Func):
4273    arg_types = {
4274        "this": True,
4275        "expression": False,
4276        "position": False,
4277        "collation": False,
4278    }
class TsOrDsAdd(Func, TimeUnit):
4281class TsOrDsAdd(Func, TimeUnit):
4282    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
4285class TsOrDsToDateStr(Func):
4286    pass
class TsOrDsToDate(Func):
4289class TsOrDsToDate(Func):
4290    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
4293class TsOrDiToDi(Func):
4294    pass
class Unhex(Func):
4297class Unhex(Func):
4298    pass
class UnixToStr(Func):
4301class UnixToStr(Func):
4302    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
4307class UnixToTime(Func):
4308    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4309
4310    SECONDS = Literal.string("seconds")
4311    MILLIS = Literal.string("millis")
4312    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
4315class UnixToTimeStr(Func):
4316    pass
class Upper(Func):
4319class Upper(Func):
4320    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
4323class Variance(AggFunc):
4324    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
4327class VariancePop(AggFunc):
4328    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
4331class Week(Func):
4332    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
4335class XMLTable(Func):
4336    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4339class Year(Func):
4340    pass
class Use(Expression):
4343class Use(Expression):
4344    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4347class Merge(Expression):
4348    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4351class When(Func):
4352    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
class NextValueFor(Func):
4357class NextValueFor(Func):
4358    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:
4395def maybe_parse(
4396    sql_or_expression: ExpOrStr,
4397    *,
4398    into: t.Optional[IntoType] = None,
4399    dialect: DialectType = None,
4400    prefix: t.Optional[str] = None,
4401    copy: bool = False,
4402    **opts,
4403) -> Expression:
4404    """Gracefully handle a possible string or expression.
4405
4406    Example:
4407        >>> maybe_parse("1")
4408        (LITERAL this: 1, is_string: False)
4409        >>> maybe_parse(to_identifier("x"))
4410        (IDENTIFIER this: x, quoted: False)
4411
4412    Args:
4413        sql_or_expression: the SQL code string or an expression
4414        into: the SQLGlot Expression to parse into
4415        dialect: the dialect used to parse the input expressions (in the case that an
4416            input expression is a SQL string).
4417        prefix: a string to prefix the sql with before it gets parsed
4418            (automatically includes a space)
4419        copy: whether or not to copy the expression.
4420        **opts: other options to use to parse the input expressions (again, in the case
4421            that an input expression is a SQL string).
4422
4423    Returns:
4424        Expression: the parsed or given expression.
4425    """
4426    if isinstance(sql_or_expression, Expression):
4427        if copy:
4428            return sql_or_expression.copy()
4429        return sql_or_expression
4430
4431    import sqlglot
4432
4433    sql = str(sql_or_expression)
4434    if prefix:
4435        sql = f"{prefix} {sql}"
4436    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):
4608def union(left, right, distinct=True, dialect=None, **opts):
4609    """
4610    Initializes a syntax tree from one UNION expression.
4611
4612    Example:
4613        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4614        'SELECT * FROM foo UNION SELECT * FROM bla'
4615
4616    Args:
4617        left (str | Expression): the SQL code string corresponding to the left-hand side.
4618            If an `Expression` instance is passed, it will be used as-is.
4619        right (str | Expression): the SQL code string corresponding to the right-hand side.
4620            If an `Expression` instance is passed, it will be used as-is.
4621        distinct (bool): set the DISTINCT flag if and only if this is true.
4622        dialect (str): the dialect used to parse the input expression.
4623        opts (kwargs): other options to use to parse the input expressions.
4624    Returns:
4625        Union: the syntax tree for the UNION expression.
4626    """
4627    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4628    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4629
4630    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):
4633def intersect(left, right, distinct=True, dialect=None, **opts):
4634    """
4635    Initializes a syntax tree from one INTERSECT expression.
4636
4637    Example:
4638        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4639        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4640
4641    Args:
4642        left (str | Expression): the SQL code string corresponding to the left-hand side.
4643            If an `Expression` instance is passed, it will be used as-is.
4644        right (str | Expression): the SQL code string corresponding to the right-hand side.
4645            If an `Expression` instance is passed, it will be used as-is.
4646        distinct (bool): set the DISTINCT flag if and only if this is true.
4647        dialect (str): the dialect used to parse the input expression.
4648        opts (kwargs): other options to use to parse the input expressions.
4649    Returns:
4650        Intersect: the syntax tree for the INTERSECT expression.
4651    """
4652    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4653    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4654
4655    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):
4658def except_(left, right, distinct=True, dialect=None, **opts):
4659    """
4660    Initializes a syntax tree from one EXCEPT expression.
4661
4662    Example:
4663        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4664        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4665
4666    Args:
4667        left (str | Expression): the SQL code string corresponding to the left-hand side.
4668            If an `Expression` instance is passed, it will be used as-is.
4669        right (str | Expression): the SQL code string corresponding to the right-hand side.
4670            If an `Expression` instance is passed, it will be used as-is.
4671        distinct (bool): set the DISTINCT flag if and only if this is true.
4672        dialect (str): the dialect used to parse the input expression.
4673        opts (kwargs): other options to use to parse the input expressions.
4674    Returns:
4675        Except: the syntax tree for the EXCEPT statement.
4676    """
4677    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4678    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4679
4680    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:
4683def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4684    """
4685    Initializes a syntax tree from one or multiple SELECT expressions.
4686
4687    Example:
4688        >>> select("col1", "col2").from_("tbl").sql()
4689        'SELECT col1, col2 FROM tbl'
4690
4691    Args:
4692        *expressions: the SQL code string to parse as the expressions of a
4693            SELECT statement. If an Expression instance is passed, this is used as-is.
4694        dialect: the dialect used to parse the input expressions (in the case that an
4695            input expression is a SQL string).
4696        **opts: other options to use to parse the input expressions (again, in the case
4697            that an input expression is a SQL string).
4698
4699    Returns:
4700        Select: the syntax tree for the SELECT statement.
4701    """
4702    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:
4705def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4706    """
4707    Initializes a syntax tree from a FROM expression.
4708
4709    Example:
4710        >>> from_("tbl").select("col1", "col2").sql()
4711        'SELECT col1, col2 FROM tbl'
4712
4713    Args:
4714        *expression: the SQL code string to parse as the FROM expressions of a
4715            SELECT statement. If an Expression instance is passed, this is used as-is.
4716        dialect: the dialect used to parse the input expression (in the case that the
4717            input expression is a SQL string).
4718        **opts: other options to use to parse the input expressions (again, in the case
4719            that the input expression is a SQL string).
4720
4721    Returns:
4722        Select: the syntax tree for the SELECT statement.
4723    """
4724    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:
4727def update(
4728    table: str | Table,
4729    properties: dict,
4730    where: t.Optional[ExpOrStr] = None,
4731    from_: t.Optional[ExpOrStr] = None,
4732    dialect: DialectType = None,
4733    **opts,
4734) -> Update:
4735    """
4736    Creates an update statement.
4737
4738    Example:
4739        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4740        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4741
4742    Args:
4743        *properties: dictionary of properties to set which are
4744            auto converted to sql objects eg None -> NULL
4745        where: sql conditional parsed into a WHERE statement
4746        from_: sql statement parsed into a FROM statement
4747        dialect: the dialect used to parse the input expressions.
4748        **opts: other options to use to parse the input expressions.
4749
4750    Returns:
4751        Update: the syntax tree for the UPDATE statement.
4752    """
4753    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4754    update_expr.set(
4755        "expressions",
4756        [
4757            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4758            for k, v in properties.items()
4759        ],
4760    )
4761    if from_:
4762        update_expr.set(
4763            "from",
4764            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4765        )
4766    if isinstance(where, Condition):
4767        where = Where(this=where)
4768    if where:
4769        update_expr.set(
4770            "where",
4771            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4772        )
4773    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:
4776def delete(
4777    table: ExpOrStr,
4778    where: t.Optional[ExpOrStr] = None,
4779    returning: t.Optional[ExpOrStr] = None,
4780    dialect: DialectType = None,
4781    **opts,
4782) -> Delete:
4783    """
4784    Builds a delete statement.
4785
4786    Example:
4787        >>> delete("my_table", where="id > 1").sql()
4788        'DELETE FROM my_table WHERE id > 1'
4789
4790    Args:
4791        where: sql conditional parsed into a WHERE statement
4792        returning: sql conditional parsed into a RETURNING statement
4793        dialect: the dialect used to parse the input expressions.
4794        **opts: other options to use to parse the input expressions.
4795
4796    Returns:
4797        Delete: the syntax tree for the DELETE statement.
4798    """
4799    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4800    if where:
4801        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4802    if returning:
4803        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4804    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:
4807def insert(
4808    expression: ExpOrStr,
4809    into: ExpOrStr,
4810    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
4811    overwrite: t.Optional[bool] = None,
4812    dialect: DialectType = None,
4813    copy: bool = True,
4814    **opts,
4815) -> Insert:
4816    """
4817    Builds an INSERT statement.
4818
4819    Example:
4820        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
4821        'INSERT INTO tbl VALUES (1, 2, 3)'
4822
4823    Args:
4824        expression: the sql string or expression of the INSERT statement
4825        into: the tbl to insert data to.
4826        columns: optionally the table's column names.
4827        overwrite: whether to INSERT OVERWRITE or not.
4828        dialect: the dialect used to parse the input expressions.
4829        copy: whether or not to copy the expression.
4830        **opts: other options to use to parse the input expressions.
4831
4832    Returns:
4833        Insert: the syntax tree for the INSERT statement.
4834    """
4835    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
4836    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
4837
4838    if columns:
4839        this = _apply_list_builder(
4840            *columns,
4841            instance=Schema(this=this),
4842            arg="expressions",
4843            into=Identifier,
4844            copy=False,
4845            dialect=dialect,
4846            **opts,
4847        )
4848
4849    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:
4852def condition(expression, dialect=None, copy=True, **opts) -> Condition:
4853    """
4854    Initialize a logical condition expression.
4855
4856    Example:
4857        >>> condition("x=1").sql()
4858        'x = 1'
4859
4860        This is helpful for composing larger logical syntax trees:
4861        >>> where = condition("x=1")
4862        >>> where = where.and_("y=1")
4863        >>> Select().from_("tbl").select("*").where(where).sql()
4864        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4865
4866    Args:
4867        *expression (str | Expression): the SQL code string to parse.
4868            If an Expression instance is passed, this is used as-is.
4869        dialect (str): the dialect used to parse the input expression (in the case that the
4870            input expression is a SQL string).
4871        copy (bool): Whether or not to copy `expression` (only applies to expressions).
4872        **opts: other options to use to parse the input expressions (again, in the case
4873            that the input expression is a SQL string).
4874
4875    Returns:
4876        Condition: the expression
4877    """
4878    return maybe_parse(  # type: ignore
4879        expression,
4880        into=Condition,
4881        dialect=dialect,
4882        copy=copy,
4883        **opts,
4884    )

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:
4887def and_(*expressions, dialect=None, copy=True, **opts) -> And:
4888    """
4889    Combine multiple conditions with an AND logical operator.
4890
4891    Example:
4892        >>> and_("x=1", and_("y=1", "z=1")).sql()
4893        'x = 1 AND (y = 1 AND z = 1)'
4894
4895    Args:
4896        *expressions (str | Expression): the SQL code strings to parse.
4897            If an Expression instance is passed, this is used as-is.
4898        dialect (str): the dialect used to parse the input expression.
4899        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4900        **opts: other options to use to parse the input expressions.
4901
4902    Returns:
4903        And: the new condition
4904    """
4905    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:
4908def or_(*expressions, dialect=None, copy=True, **opts) -> Or:
4909    """
4910    Combine multiple conditions with an OR logical operator.
4911
4912    Example:
4913        >>> or_("x=1", or_("y=1", "z=1")).sql()
4914        'x = 1 OR (y = 1 OR z = 1)'
4915
4916    Args:
4917        *expressions (str | Expression): the SQL code strings to parse.
4918            If an Expression instance is passed, this is used as-is.
4919        dialect (str): the dialect used to parse the input expression.
4920        copy (bool): whether or not to copy `expressions` (only applies to Expressions).
4921        **opts: other options to use to parse the input expressions.
4922
4923    Returns:
4924        Or: the new condition
4925    """
4926    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:
4929def not_(expression, dialect=None, copy=True, **opts) -> Not:
4930    """
4931    Wrap a condition with a NOT operator.
4932
4933    Example:
4934        >>> not_("this_suit='black'").sql()
4935        "NOT this_suit = 'black'"
4936
4937    Args:
4938        expression (str | Expression): the SQL code strings to parse.
4939            If an Expression instance is passed, this is used as-is.
4940        dialect (str): the dialect used to parse the input expression.
4941        **opts: other options to use to parse the input expressions.
4942
4943    Returns:
4944        Not: the new condition
4945    """
4946    this = condition(
4947        expression,
4948        dialect=dialect,
4949        copy=copy,
4950        **opts,
4951    )
4952    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:
4955def paren(expression, copy=True) -> Paren:
4956    return Paren(this=_maybe_copy(expression, copy))
def to_identifier(name, quoted=None, copy=True):
4974def to_identifier(name, quoted=None, copy=True):
4975    """Builds an identifier.
4976
4977    Args:
4978        name: The name to turn into an identifier.
4979        quoted: Whether or not force quote the identifier.
4980        copy: Whether or not to copy a passed in Identefier node.
4981
4982    Returns:
4983        The identifier ast node.
4984    """
4985
4986    if name is None:
4987        return None
4988
4989    if isinstance(name, Identifier):
4990        identifier = _maybe_copy(name, copy)
4991    elif isinstance(name, str):
4992        identifier = Identifier(
4993            this=name,
4994            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4995        )
4996    else:
4997        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4998    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:
5004def to_interval(interval: str | Literal) -> Interval:
5005    """Builds an interval expression from a string like '1 day' or '5 months'."""
5006    if isinstance(interval, Literal):
5007        if not interval.is_string:
5008            raise ValueError("Invalid interval string.")
5009
5010        interval = interval.this
5011
5012    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5013
5014    if not interval_parts:
5015        raise ValueError("Invalid interval string.")
5016
5017    return Interval(
5018        this=Literal.string(interval_parts.group(1)),
5019        unit=Var(this=interval_parts.group(2)),
5020    )

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

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Optional[sqlglot.expressions.Table]:
5033def to_table(
5034    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5035) -> t.Optional[Table]:
5036    """
5037    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5038    If a table is passed in then that table is returned.
5039
5040    Args:
5041        sql_path: a `[catalog].[schema].[table]` string.
5042        dialect: the source dialect according to which the table name will be parsed.
5043        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5044
5045    Returns:
5046        A table expression.
5047    """
5048    if sql_path is None or isinstance(sql_path, Table):
5049        return sql_path
5050    if not isinstance(sql_path, str):
5051        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5052
5053    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5054    if table:
5055        for k, v in kwargs.items():
5056            table.set(k, v)
5057
5058    return table

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
  • dialect: the source dialect according to which the table name will be parsed.
  • kwargs: the kwargs to instantiate the resulting Table expression with.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
5061def to_column(sql_path: str | Column, **kwargs) -> Column:
5062    """
5063    Create a column from a `[table].[column]` sql path. Schema is optional.
5064
5065    If a column is passed in then that column is returned.
5066
5067    Args:
5068        sql_path: `[table].[column]` string
5069    Returns:
5070        Table: A column expression
5071    """
5072    if sql_path is None or isinstance(sql_path, Column):
5073        return sql_path
5074    if not isinstance(sql_path, str):
5075        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5076    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):
5079def alias_(
5080    expression: ExpOrStr,
5081    alias: str | Identifier,
5082    table: bool | t.Sequence[str | Identifier] = False,
5083    quoted: t.Optional[bool] = None,
5084    dialect: DialectType = None,
5085    copy: bool = True,
5086    **opts,
5087):
5088    """Create an Alias expression.
5089
5090    Example:
5091        >>> alias_('foo', 'bar').sql()
5092        'foo AS bar'
5093
5094        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5095        '(SELECT 1, 2) AS bar(a, b)'
5096
5097    Args:
5098        expression: the SQL code strings to parse.
5099            If an Expression instance is passed, this is used as-is.
5100        alias: the alias name to use. If the name has
5101            special characters it is quoted.
5102        table: Whether or not to create a table alias, can also be a list of columns.
5103        quoted: whether or not to quote the alias
5104        dialect: the dialect used to parse the input expression.
5105        copy: Whether or not to copy the expression.
5106        **opts: other options to use to parse the input expressions.
5107
5108    Returns:
5109        Alias: the aliased expression
5110    """
5111    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5112    alias = to_identifier(alias, quoted=quoted)
5113
5114    if table:
5115        table_alias = TableAlias(this=alias)
5116        exp.set("alias", table_alias)
5117
5118        if not isinstance(table, bool):
5119            for column in table:
5120                table_alias.append("columns", to_identifier(column, quoted=quoted))
5121
5122        return exp
5123
5124    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5125    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5126    # for the complete Window expression.
5127    #
5128    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5129
5130    if "alias" in exp.arg_types and not isinstance(exp, Window):
5131        exp.set("alias", alias)
5132        return exp
5133    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):
5136def subquery(expression, alias=None, dialect=None, **opts):
5137    """
5138    Build a subquery expression.
5139
5140    Example:
5141        >>> subquery('select x from tbl', 'bar').select('x').sql()
5142        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5143
5144    Args:
5145        expression (str | Expression): the SQL code strings to parse.
5146            If an Expression instance is passed, this is used as-is.
5147        alias (str | Expression): the alias name to use.
5148        dialect (str): the dialect used to parse the input expression.
5149        **opts: other options to use to parse the input expressions.
5150
5151    Returns:
5152        Select: a new select with the subquery expression included
5153    """
5154
5155    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5156    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:
5159def column(
5160    col: str | Identifier,
5161    table: t.Optional[str | Identifier] = None,
5162    db: t.Optional[str | Identifier] = None,
5163    catalog: t.Optional[str | Identifier] = None,
5164    quoted: t.Optional[bool] = None,
5165) -> Column:
5166    """
5167    Build a Column.
5168
5169    Args:
5170        col: column name
5171        table: table name
5172        db: db name
5173        catalog: catalog name
5174        quoted: whether or not to force quote each part
5175    Returns:
5176        Column: column instance
5177    """
5178    return Column(
5179        this=to_identifier(col, quoted=quoted),
5180        table=to_identifier(table, quoted=quoted),
5181        db=to_identifier(db, quoted=quoted),
5182        catalog=to_identifier(catalog, quoted=quoted),
5183    )

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:
5186def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5187    """Cast an expression to a data type.
5188
5189    Example:
5190        >>> cast('x + 1', 'int').sql()
5191        'CAST(x + 1 AS INT)'
5192
5193    Args:
5194        expression: The expression to cast.
5195        to: The datatype to cast to.
5196
5197    Returns:
5198        A cast node.
5199    """
5200    expression = maybe_parse(expression, **opts)
5201    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:
5204def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
5205    """Build a Table.
5206
5207    Args:
5208        table (str | Expression): column name
5209        db (str | Expression): db name
5210        catalog (str | Expression): catalog name
5211
5212    Returns:
5213        Table: table instance
5214    """
5215    return Table(
5216        this=to_identifier(table, quoted=quoted),
5217        db=to_identifier(db, quoted=quoted),
5218        catalog=to_identifier(catalog, quoted=quoted),
5219        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5220    )

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:
5223def values(
5224    values: t.Iterable[t.Tuple[t.Any, ...]],
5225    alias: t.Optional[str] = None,
5226    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5227) -> Values:
5228    """Build VALUES statement.
5229
5230    Example:
5231        >>> values([(1, '2')]).sql()
5232        "VALUES (1, '2')"
5233
5234    Args:
5235        values: values statements that will be converted to SQL
5236        alias: optional alias
5237        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5238         If either are provided then an alias is also required.
5239
5240    Returns:
5241        Values: the Values expression object
5242    """
5243    if columns and not alias:
5244        raise ValueError("Alias is required when providing columns")
5245
5246    return Values(
5247        expressions=[convert(tup) for tup in values],
5248        alias=(
5249            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5250            if columns
5251            else (TableAlias(this=to_identifier(alias)) if alias else None)
5252        ),
5253    )

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:
5256def var(name: t.Optional[ExpOrStr]) -> Var:
5257    """Build a SQL variable.
5258
5259    Example:
5260        >>> repr(var('x'))
5261        '(VAR this: x)'
5262
5263        >>> repr(var(column('x', table='y')))
5264        '(VAR this: x)'
5265
5266    Args:
5267        name: The name of the var or an expression who's name will become the var.
5268
5269    Returns:
5270        The new variable node.
5271    """
5272    if not name:
5273        raise ValueError("Cannot convert empty name into var.")
5274
5275    if isinstance(name, Expression):
5276        name = name.name
5277    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:
5280def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5281    """Build ALTER TABLE... RENAME... expression
5282
5283    Args:
5284        old_name: The old name of the table
5285        new_name: The new name of the table
5286
5287    Returns:
5288        Alter table expression
5289    """
5290    old_table = to_table(old_name)
5291    new_table = to_table(new_name)
5292    return AlterTable(
5293        this=old_table,
5294        actions=[
5295            RenameTable(this=new_table),
5296        ],
5297    )

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

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

Returns a true Boolean expression.

def false():
5567def false():
5568    """
5569    Returns a false Boolean expression.
5570    """
5571    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5574def null():
5575    """
5576    Returns a Null expression.
5577    """
5578    return Null()

Returns a Null expression.