Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


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

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
Expression(**args: Any)
89    def __init__(self, **args: t.Any):
90        self.args: t.Dict[str, t.Any] = args
91        self.parent: t.Optional[Expression] = None
92        self.arg_key: t.Optional[str] = None
93        self.comments: t.Optional[t.List[str]] = None
94        self._type: t.Optional[DataType] = None
95        self._meta: t.Optional[t.Dict[str, t.Any]] = None
96        self._hash: t.Optional[int] = None
97
98        for arg_key, value in self.args.items():
99            self._set_parent(arg_key, value)
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
142    def text(self, key) -> str:
143        """
144        Returns a textual representation of the argument corresponding to "key". This can only be used
145        for args that are strings or leaf Expression instances, such as identifiers and literals.
146        """
147        field = self.args.get(key)
148        if isinstance(field, str):
149            return field
150        if isinstance(field, (Identifier, Literal, Var)):
151            return field.this
152        if isinstance(field, (Star, Null)):
153            return field.name
154        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def copy(self):
252    def copy(self):
253        """
254        Returns a deep copy of the expression.
255        """
256        new = deepcopy(self)
257        new.parent = self.parent
258        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
260    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
261        if self.comments is None:
262            self.comments = []
263        if comments:
264            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
266    def append(self, arg_key: str, value: t.Any) -> None:
267        """
268        Appends value to arg_key if it's a list or sets it as a new list.
269
270        Args:
271            arg_key (str): name of the list expression arg
272            value (Any): value to append to the list
273        """
274        if not isinstance(self.args.get(arg_key), list):
275            self.args[arg_key] = []
276        self.args[arg_key].append(value)
277        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key: str, value: Any) -> None:
279    def set(self, arg_key: str, value: t.Any) -> None:
280        """
281        Sets `arg_key` to `value`.
282
283        Args:
284            arg_key (str): name of the expression arg.
285            value: value to set the arg to.
286        """
287        self.args[arg_key] = value
288        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth: int

Returns the depth of this tree.

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

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

def find(self, *expression_types: Type[~E], bfs: bool = True) -> Optional[~E]:
320    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
321        """
322        Returns the first node in this tree which matches at least one of
323        the specified types.
324
325        Args:
326            expression_types: the expression type(s) to match.
327            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
328
329        Returns:
330            The node which matches the criteria or None if no such node was found.
331        """
332        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

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

def find_all(self, *expression_types: Type[~E], bfs: bool = True) -> Iterator[~E]:
334    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
335        """
336        Returns a generator object which visits all nodes in this tree and only
337        yields those that match at least one of the specified expression types.
338
339        Args:
340            expression_types: the expression type(s) to match.
341            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
350    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)

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

Returns:

The generator object.

def bfs(self, prune=None):
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))

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

Returns:

The generator object.

def unnest(self):
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression

Returns the first non parenthesis child or self.

def unalias(self):
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
553    def replace(self, expression):
554        """
555        Swap out this expression with a new expression.
556
557        For example::
558
559            >>> tree = Select().select("x").from_("tbl")
560            >>> tree.find(Column).replace(Column(this="y"))
561            (COLUMN this: y)
562            >>> tree.sql()
563            'SELECT y FROM tbl'
564
565        Args:
566            expression: new node
567
568        Returns:
569            The new expression or expressions.
570        """
571        if not self.parent:
572            return expression
573
574        parent = self.parent
575        self.parent = None
576
577        replace_children(parent, lambda child: expression if child is self else child)
578        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression: new node
Returns:

The new expression or expressions.

def pop(self: ~E) -> ~E:
580    def pop(self: E) -> E:
581        """
582        Remove this expression from its AST.
583
584        Returns:
585            The popped expression.
586        """
587        self.replace(None)
588        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_: Type[~E]) -> ~E:
590    def assert_is(self, type_: t.Type[E]) -> E:
591        """
592        Assert that this `Expression` is an instance of `type_`.
593
594        If it is NOT an instance of `type_`, this raises an assertion error.
595        Otherwise, this returns this expression.
596
597        Examples:
598            This is useful for type security in chained expressions:
599
600            >>> import sqlglot
601            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
602            'SELECT x, z FROM y'
603        """
604        assert isinstance(self, type_)
605        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
607    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
608        """
609        Checks if this expression is valid (e.g. all mandatory args are set).
610
611        Args:
612            args: a sequence of values that were used to instantiate a Func expression. This is used
613                to check that the provided arguments don't exceed the function argument limit.
614
615        Returns:
616            A list of error messages for all possible errors that were found.
617        """
618        errors: t.List[str] = []
619
620        for k in self.args:
621            if k not in self.arg_types:
622                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
623        for k, mandatory in self.arg_types.items():
624            v = self.args.get(k)
625            if mandatory and (v is None or (isinstance(v, list) and not v)):
626                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
627
628        if (
629            args
630            and isinstance(self, Func)
631            and len(args) > len(self.arg_types)
632            and not self.is_var_len_args
633        ):
634            errors.append(
635                f"The number of provided arguments ({len(args)}) is greater than "
636                f"the maximum number of supported arguments ({len(self.arg_types)})"
637            )
638
639        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
641    def dump(self):
642        """
643        Dump this Expression to a JSON-serializable dict.
644        """
645        from sqlglot.serde import dump
646
647        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
649    @classmethod
650    def load(cls, obj):
651        """
652        Load a dict (as returned by `Expression.dump`) into an Expression instance.
653        """
654        from sqlglot.serde import load
655
656        return load(obj)

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

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

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new And condition.

def or_( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
694    def or_(
695        self,
696        *expressions: t.Optional[ExpOrStr],
697        dialect: DialectType = None,
698        copy: bool = True,
699        **opts,
700    ) -> Condition:
701        """
702        OR this condition with one or multiple expressions.
703
704        Example:
705            >>> condition("x=1").or_("y=1").sql()
706            'x = 1 OR y = 1'
707
708        Args:
709            *expressions: the SQL code strings to parse.
710                If an `Expression` instance is passed, it will be used as-is.
711            dialect: the dialect used to parse the input expression.
712            copy: whether or not to copy the involved expressions (only applies to Expressions).
713            opts: other options to use to parse the input expressions.
714
715        Returns:
716            The new Or condition.
717        """
718        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new Or condition.

def not_(self, copy: bool = True):
720    def not_(self, copy: bool = True):
721        """
722        Wrap this condition with NOT.
723
724        Example:
725            >>> condition("x=1").not_().sql()
726            'NOT x = 1'
727
728        Args:
729            copy: whether or not to copy this object.
730
731        Returns:
732            The new Not instance.
733        """
734        return not_(self, copy=copy)

Wrap this condition with NOT.

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

The new Not instance.

def as_( self, alias: str | sqlglot.expressions.Identifier, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Alias:
736    def as_(
737        self,
738        alias: str | Identifier,
739        quoted: t.Optional[bool] = None,
740        dialect: DialectType = None,
741        copy: bool = True,
742        **opts,
743    ) -> Alias:
744        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
761    def isin(
762        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
763    ) -> In:
764        return In(
765            this=_maybe_copy(self, copy),
766            expressions=[convert(e, copy=copy) for e in expressions],
767            query=maybe_parse(query, copy=copy, **opts) if query else None,
768        )
def between( self, low: Any, high: Any, copy: bool = True, **opts) -> sqlglot.expressions.Between:
770    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
771        return Between(
772            this=_maybe_copy(self, copy),
773            low=convert(low, copy=copy, **opts),
774            high=convert(high, copy=copy, **opts),
775        )
def is_( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Is:
777    def is_(self, other: ExpOrStr) -> Is:
778        return self._binop(Is, other)
def like( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Like:
780    def like(self, other: ExpOrStr) -> Like:
781        return self._binop(Like, other)
def ilike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.ILike:
783    def ilike(self, other: ExpOrStr) -> ILike:
784        return self._binop(ILike, other)
def eq(self, other: Any) -> sqlglot.expressions.EQ:
786    def eq(self, other: t.Any) -> EQ:
787        return self._binop(EQ, other)
def neq(self, other: Any) -> sqlglot.expressions.NEQ:
789    def neq(self, other: t.Any) -> NEQ:
790        return self._binop(NEQ, other)
def rlike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.RegexpLike:
792    def rlike(self, other: ExpOrStr) -> RegexpLike:
793        return self._binop(RegexpLike, other)
class Predicate(Condition):
868class Predicate(Condition):
869    """Relationships like x = y, x > 1, x >= y."""

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

class DerivedTable(Expression):
872class DerivedTable(Expression):
873    @property
874    def alias_column_names(self) -> t.List[str]:
875        table_alias = self.args.get("alias")
876        if not table_alias:
877            return []
878        return [c.name for c in table_alias.args.get("columns") or []]
879
880    @property
881    def selects(self):
882        return self.this.selects if isinstance(self.this, Subqueryable) else []
883
884    @property
885    def named_selects(self):
886        return [select.output_name for select in self.selects]
class Unionable(Expression):
889class Unionable(Expression):
890    def union(
891        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
892    ) -> Unionable:
893        """
894        Builds a UNION expression.
895
896        Example:
897            >>> import sqlglot
898            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
899            'SELECT * FROM foo UNION SELECT * FROM bla'
900
901        Args:
902            expression: the SQL code string.
903                If an `Expression` instance is passed, it will be used as-is.
904            distinct: set the DISTINCT flag if and only if this is true.
905            dialect: the dialect used to parse the input expression.
906            opts: other options to use to parse the input expressions.
907
908        Returns:
909            The new Union expression.
910        """
911        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
912
913    def intersect(
914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
915    ) -> Unionable:
916        """
917        Builds an INTERSECT expression.
918
919        Example:
920            >>> import sqlglot
921            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
922            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
923
924        Args:
925            expression: the SQL code string.
926                If an `Expression` instance is passed, it will be used as-is.
927            distinct: set the DISTINCT flag if and only if this is true.
928            dialect: the dialect used to parse the input expression.
929            opts: other options to use to parse the input expressions.
930
931        Returns:
932            The new Intersect expression.
933        """
934        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
935
936    def except_(
937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
938    ) -> Unionable:
939        """
940        Builds an EXCEPT expression.
941
942        Example:
943            >>> import sqlglot
944            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
945            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
946
947        Args:
948            expression: the SQL code string.
949                If an `Expression` instance is passed, it will be used as-is.
950            distinct: set the DISTINCT flag if and only if this is true.
951            dialect: the dialect used to parse the input expression.
952            opts: other options to use to parse the input expressions.
953
954        Returns:
955            The new Except expression.
956        """
957        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
890    def union(
891        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
892    ) -> Unionable:
893        """
894        Builds a UNION expression.
895
896        Example:
897            >>> import sqlglot
898            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
899            'SELECT * FROM foo UNION SELECT * FROM bla'
900
901        Args:
902            expression: the SQL code string.
903                If an `Expression` instance is passed, it will be used as-is.
904            distinct: set the DISTINCT flag if and only if this is true.
905            dialect: the dialect used to parse the input expression.
906            opts: other options to use to parse the input expressions.
907
908        Returns:
909            The new Union expression.
910        """
911        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union expression.

def intersect( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
913    def intersect(
914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
915    ) -> Unionable:
916        """
917        Builds an INTERSECT expression.
918
919        Example:
920            >>> import sqlglot
921            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
922            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
923
924        Args:
925            expression: the SQL code string.
926                If an `Expression` instance is passed, it will be used as-is.
927            distinct: set the DISTINCT flag if and only if this is true.
928            dialect: the dialect used to parse the input expression.
929            opts: other options to use to parse the input expressions.
930
931        Returns:
932            The new Intersect expression.
933        """
934        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect expression.

def except_( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
936    def except_(
937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
938    ) -> Unionable:
939        """
940        Builds an EXCEPT expression.
941
942        Example:
943            >>> import sqlglot
944            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
945            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
946
947        Args:
948            expression: the SQL code string.
949                If an `Expression` instance is passed, it will be used as-is.
950            distinct: set the DISTINCT flag if and only if this is true.
951            dialect: the dialect used to parse the input expression.
952            opts: other options to use to parse the input expressions.
953
954        Returns:
955            The new Except expression.
956        """
957        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except expression.

class UDTF(DerivedTable, Unionable):
960class UDTF(DerivedTable, Unionable):
961    @property
962    def selects(self):
963        alias = self.args.get("alias")
964        return alias.columns if alias else []
class Cache(Expression):
967class Cache(Expression):
968    arg_types = {
969        "with": False,
970        "this": True,
971        "lazy": False,
972        "options": False,
973        "expression": False,
974    }
class Uncache(Expression):
977class Uncache(Expression):
978    arg_types = {"this": True, "exists": False}
class Create(Expression):
981class Create(Expression):
982    arg_types = {
983        "with": False,
984        "this": True,
985        "kind": True,
986        "expression": False,
987        "exists": False,
988        "properties": False,
989        "replace": False,
990        "unique": False,
991        "indexes": False,
992        "no_schema_binding": False,
993        "begin": False,
994        "clone": False,
995    }
class Clone(Expression):
 999class Clone(Expression):
1000    arg_types = {
1001        "this": True,
1002        "when": False,
1003        "kind": False,
1004        "expression": False,
1005    }
class Describe(Expression):
1008class Describe(Expression):
1009    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
1012class Pragma(Expression):
1013    pass
class Set(Expression):
1016class Set(Expression):
1017    arg_types = {"expressions": False}
class SetItem(Expression):
1020class SetItem(Expression):
1021    arg_types = {
1022        "this": False,
1023        "expressions": False,
1024        "kind": False,
1025        "collate": False,  # MySQL SET NAMES statement
1026        "global": False,
1027    }
class Show(Expression):
1030class Show(Expression):
1031    arg_types = {
1032        "this": True,
1033        "target": False,
1034        "offset": False,
1035        "limit": False,
1036        "like": False,
1037        "where": False,
1038        "db": False,
1039        "full": False,
1040        "mutex": False,
1041        "query": False,
1042        "channel": False,
1043        "global": False,
1044        "log": False,
1045        "position": False,
1046        "types": False,
1047    }
class UserDefinedFunction(Expression):
1050class UserDefinedFunction(Expression):
1051    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
1054class CharacterSet(Expression):
1055    arg_types = {"this": True, "default": False}
class With(Expression):
1058class With(Expression):
1059    arg_types = {"expressions": True, "recursive": False}
1060
1061    @property
1062    def recursive(self) -> bool:
1063        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
1066class WithinGroup(Expression):
1067    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
1070class CTE(DerivedTable):
1071    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
1074class TableAlias(Expression):
1075    arg_types = {"this": False, "columns": False}
1076
1077    @property
1078    def columns(self):
1079        return self.args.get("columns") or []
class BitString(Condition):
1082class BitString(Condition):
1083    pass
class HexString(Condition):
1086class HexString(Condition):
1087    pass
class ByteString(Condition):
1090class ByteString(Condition):
1091    pass
class RawString(Condition):
1094class RawString(Condition):
1095    pass
class Column(Condition):
1098class Column(Condition):
1099    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1100
1101    @property
1102    def table(self) -> str:
1103        return self.text("table")
1104
1105    @property
1106    def db(self) -> str:
1107        return self.text("db")
1108
1109    @property
1110    def catalog(self) -> str:
1111        return self.text("catalog")
1112
1113    @property
1114    def output_name(self) -> str:
1115        return self.name
1116
1117    @property
1118    def parts(self) -> t.List[Identifier]:
1119        """Return the parts of a column in order catalog, db, table, name."""
1120        return [
1121            t.cast(Identifier, self.args[part])
1122            for part in ("catalog", "db", "table", "this")
1123            if self.args.get(part)
1124        ]
1125
1126    def to_dot(self) -> Dot:
1127        """Converts the column into a dot expression."""
1128        parts = self.parts
1129        parent = self.parent
1130
1131        while parent:
1132            if isinstance(parent, Dot):
1133                parts.append(parent.expression)
1134            parent = parent.parent
1135
1136        return Dot.build(parts)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

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

def to_dot(self) -> sqlglot.expressions.Dot:
1126    def to_dot(self) -> Dot:
1127        """Converts the column into a dot expression."""
1128        parts = self.parts
1129        parent = self.parent
1130
1131        while parent:
1132            if isinstance(parent, Dot):
1133                parts.append(parent.expression)
1134            parent = parent.parent
1135
1136        return Dot.build(parts)

Converts the column into a dot expression.

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

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

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

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

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

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

class Drop(Expression):
1415class Drop(Expression):
1416    arg_types = {
1417        "this": False,
1418        "kind": False,
1419        "exists": False,
1420        "temporary": False,
1421        "materialized": False,
1422        "cascade": False,
1423        "constraints": False,
1424        "purge": False,
1425    }
class Filter(Expression):
1428class Filter(Expression):
1429    arg_types = {"this": True, "expression": True}
class Check(Expression):
1432class Check(Expression):
1433    pass
class Directory(Expression):
1436class Directory(Expression):
1437    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1438    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1441class ForeignKey(Expression):
1442    arg_types = {
1443        "expressions": True,
1444        "reference": False,
1445        "delete": False,
1446        "update": False,
1447    }
class PrimaryKey(Expression):
1450class PrimaryKey(Expression):
1451    arg_types = {"expressions": True, "options": False}
class Into(Expression):
1456class Into(Expression):
1457    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1460class From(Expression):
1461    @property
1462    def name(self) -> str:
1463        return self.this.name
1464
1465    @property
1466    def alias_or_name(self) -> str:
1467        return self.this.alias_or_name
class Having(Expression):
1470class Having(Expression):
1471    pass
class Hint(Expression):
1474class Hint(Expression):
1475    arg_types = {"expressions": True}
class JoinHint(Expression):
1478class JoinHint(Expression):
1479    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1482class Identifier(Expression):
1483    arg_types = {"this": True, "quoted": False}
1484
1485    @property
1486    def quoted(self) -> bool:
1487        return bool(self.args.get("quoted"))
1488
1489    @property
1490    def hashable_args(self) -> t.Any:
1491        if self.quoted and any(char.isupper() for char in self.this):
1492            return (self.this, self.quoted)
1493        return self.this.lower()
1494
1495    @property
1496    def output_name(self) -> str:
1497        return self.name
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Index(Expression):
1500class Index(Expression):
1501    arg_types = {
1502        "this": False,
1503        "table": False,
1504        "using": False,
1505        "where": False,
1506        "columns": False,
1507        "unique": False,
1508        "primary": False,
1509        "amp": False,  # teradata
1510        "partition_by": False,  # teradata
1511    }
class Insert(Expression):
1514class Insert(Expression):
1515    arg_types = {
1516        "with": False,
1517        "this": True,
1518        "expression": False,
1519        "conflict": False,
1520        "returning": False,
1521        "overwrite": False,
1522        "exists": False,
1523        "partition": False,
1524        "alternative": False,
1525    }
1526
1527    def with_(
1528        self,
1529        alias: ExpOrStr,
1530        as_: ExpOrStr,
1531        recursive: t.Optional[bool] = None,
1532        append: bool = True,
1533        dialect: DialectType = None,
1534        copy: bool = True,
1535        **opts,
1536    ) -> Insert:
1537        """
1538        Append to or set the common table expressions.
1539
1540        Example:
1541            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1542            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1543
1544        Args:
1545            alias: the SQL code string to parse as the table name.
1546                If an `Expression` instance is passed, this is used as-is.
1547            as_: the SQL code string to parse as the table expression.
1548                If an `Expression` instance is passed, it will be used as-is.
1549            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1550            append: if `True`, add to any existing expressions.
1551                Otherwise, this resets the expressions.
1552            dialect: the dialect used to parse the input expression.
1553            copy: if `False`, modify this expression instance in-place.
1554            opts: other options to use to parse the input expressions.
1555
1556        Returns:
1557            The modified expression.
1558        """
1559        return _apply_cte_builder(
1560            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1561        )
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:
1527    def with_(
1528        self,
1529        alias: ExpOrStr,
1530        as_: ExpOrStr,
1531        recursive: t.Optional[bool] = None,
1532        append: bool = True,
1533        dialect: DialectType = None,
1534        copy: bool = True,
1535        **opts,
1536    ) -> Insert:
1537        """
1538        Append to or set the common table expressions.
1539
1540        Example:
1541            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1542            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1543
1544        Args:
1545            alias: the SQL code string to parse as the table name.
1546                If an `Expression` instance is passed, this is used as-is.
1547            as_: the SQL code string to parse as the table expression.
1548                If an `Expression` instance is passed, it will be used as-is.
1549            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1550            append: if `True`, add to any existing expressions.
1551                Otherwise, this resets the expressions.
1552            dialect: the dialect used to parse the input expression.
1553            copy: if `False`, modify this expression instance in-place.
1554            opts: other options to use to parse the input expressions.
1555
1556        Returns:
1557            The modified expression.
1558        """
1559        return _apply_cte_builder(
1560            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1561        )

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):
1564class OnConflict(Expression):
1565    arg_types = {
1566        "duplicate": False,
1567        "expressions": False,
1568        "nothing": False,
1569        "key": False,
1570        "constraint": False,
1571    }
class Returning(Expression):
1574class Returning(Expression):
1575    arg_types = {"expressions": True}
class Introducer(Expression):
1579class Introducer(Expression):
1580    arg_types = {"this": True, "expression": True}
class National(Expression):
1584class National(Expression):
1585    pass
class LoadData(Expression):
1588class LoadData(Expression):
1589    arg_types = {
1590        "this": True,
1591        "local": False,
1592        "overwrite": False,
1593        "inpath": True,
1594        "partition": False,
1595        "input_format": False,
1596        "serde": False,
1597    }
class Partition(Expression):
1600class Partition(Expression):
1601    arg_types = {"expressions": True}
class Fetch(Expression):
1604class Fetch(Expression):
1605    arg_types = {
1606        "direction": False,
1607        "count": False,
1608        "percent": False,
1609        "with_ties": False,
1610    }
class Group(Expression):
1613class Group(Expression):
1614    arg_types = {
1615        "expressions": False,
1616        "grouping_sets": False,
1617        "cube": False,
1618        "rollup": False,
1619        "totals": False,
1620    }
class Lambda(Expression):
1623class Lambda(Expression):
1624    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1627class Limit(Expression):
1628    arg_types = {"this": False, "expression": True, "offset": False}
class Literal(Condition):
1631class Literal(Condition):
1632    arg_types = {"this": True, "is_string": True}
1633
1634    @property
1635    def hashable_args(self) -> t.Any:
1636        return (self.this, self.args.get("is_string"))
1637
1638    @classmethod
1639    def number(cls, number) -> Literal:
1640        return cls(this=str(number), is_string=False)
1641
1642    @classmethod
1643    def string(cls, string) -> Literal:
1644        return cls(this=str(string), is_string=True)
1645
1646    @property
1647    def output_name(self) -> str:
1648        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1638    @classmethod
1639    def number(cls, number) -> Literal:
1640        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1642    @classmethod
1643    def string(cls, string) -> Literal:
1644        return cls(this=str(string), is_string=True)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Join(Expression):
1651class Join(Expression):
1652    arg_types = {
1653        "this": True,
1654        "on": False,
1655        "side": False,
1656        "kind": False,
1657        "using": False,
1658        "method": False,
1659        "global": False,
1660        "hint": False,
1661    }
1662
1663    @property
1664    def method(self) -> str:
1665        return self.text("method").upper()
1666
1667    @property
1668    def kind(self) -> str:
1669        return self.text("kind").upper()
1670
1671    @property
1672    def side(self) -> str:
1673        return self.text("side").upper()
1674
1675    @property
1676    def hint(self) -> str:
1677        return self.text("hint").upper()
1678
1679    @property
1680    def alias_or_name(self) -> str:
1681        return self.this.alias_or_name
1682
1683    def on(
1684        self,
1685        *expressions: t.Optional[ExpOrStr],
1686        append: bool = True,
1687        dialect: DialectType = None,
1688        copy: bool = True,
1689        **opts,
1690    ) -> Join:
1691        """
1692        Append to or set the ON expressions.
1693
1694        Example:
1695            >>> import sqlglot
1696            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1697            'JOIN x ON y = 1'
1698
1699        Args:
1700            *expressions: the SQL code strings to parse.
1701                If an `Expression` instance is passed, it will be used as-is.
1702                Multiple expressions are combined with an AND operator.
1703            append: if `True`, AND the new expressions to any existing expression.
1704                Otherwise, this resets the expression.
1705            dialect: the dialect used to parse the input expressions.
1706            copy: if `False`, modify this expression instance in-place.
1707            opts: other options to use to parse the input expressions.
1708
1709        Returns:
1710            The modified Join expression.
1711        """
1712        join = _apply_conjunction_builder(
1713            *expressions,
1714            instance=self,
1715            arg="on",
1716            append=append,
1717            dialect=dialect,
1718            copy=copy,
1719            **opts,
1720        )
1721
1722        if join.kind == "CROSS":
1723            join.set("kind", None)
1724
1725        return join
1726
1727    def using(
1728        self,
1729        *expressions: t.Optional[ExpOrStr],
1730        append: bool = True,
1731        dialect: DialectType = None,
1732        copy: bool = True,
1733        **opts,
1734    ) -> Join:
1735        """
1736        Append to or set the USING expressions.
1737
1738        Example:
1739            >>> import sqlglot
1740            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1741            'JOIN x USING (foo, bla)'
1742
1743        Args:
1744            *expressions: the SQL code strings to parse.
1745                If an `Expression` instance is passed, it will be used as-is.
1746            append: if `True`, concatenate the new expressions to the existing "using" list.
1747                Otherwise, this resets the expression.
1748            dialect: the dialect used to parse the input expressions.
1749            copy: if `False`, modify this expression instance in-place.
1750            opts: other options to use to parse the input expressions.
1751
1752        Returns:
1753            The modified Join expression.
1754        """
1755        join = _apply_list_builder(
1756            *expressions,
1757            instance=self,
1758            arg="using",
1759            append=append,
1760            dialect=dialect,
1761            copy=copy,
1762            **opts,
1763        )
1764
1765        if join.kind == "CROSS":
1766            join.set("kind", None)
1767
1768        return join
def on( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1683    def on(
1684        self,
1685        *expressions: t.Optional[ExpOrStr],
1686        append: bool = True,
1687        dialect: DialectType = None,
1688        copy: bool = True,
1689        **opts,
1690    ) -> Join:
1691        """
1692        Append to or set the ON expressions.
1693
1694        Example:
1695            >>> import sqlglot
1696            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1697            'JOIN x ON y = 1'
1698
1699        Args:
1700            *expressions: the SQL code strings to parse.
1701                If an `Expression` instance is passed, it will be used as-is.
1702                Multiple expressions are combined with an AND operator.
1703            append: if `True`, AND the new expressions to any existing expression.
1704                Otherwise, this resets the expression.
1705            dialect: the dialect used to parse the input expressions.
1706            copy: if `False`, modify this expression instance in-place.
1707            opts: other options to use to parse the input expressions.
1708
1709        Returns:
1710            The modified Join expression.
1711        """
1712        join = _apply_conjunction_builder(
1713            *expressions,
1714            instance=self,
1715            arg="on",
1716            append=append,
1717            dialect=dialect,
1718            copy=copy,
1719            **opts,
1720        )
1721
1722        if join.kind == "CROSS":
1723            join.set("kind", None)
1724
1725        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

def using( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1727    def using(
1728        self,
1729        *expressions: t.Optional[ExpOrStr],
1730        append: bool = True,
1731        dialect: DialectType = None,
1732        copy: bool = True,
1733        **opts,
1734    ) -> Join:
1735        """
1736        Append to or set the USING expressions.
1737
1738        Example:
1739            >>> import sqlglot
1740            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1741            'JOIN x USING (foo, bla)'
1742
1743        Args:
1744            *expressions: the SQL code strings to parse.
1745                If an `Expression` instance is passed, it will be used as-is.
1746            append: if `True`, concatenate the new expressions to the existing "using" list.
1747                Otherwise, this resets the expression.
1748            dialect: the dialect used to parse the input expressions.
1749            copy: if `False`, modify this expression instance in-place.
1750            opts: other options to use to parse the input expressions.
1751
1752        Returns:
1753            The modified Join expression.
1754        """
1755        join = _apply_list_builder(
1756            *expressions,
1757            instance=self,
1758            arg="using",
1759            append=append,
1760            dialect=dialect,
1761            copy=copy,
1762            **opts,
1763        )
1764
1765        if join.kind == "CROSS":
1766            join.set("kind", None)
1767
1768        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

class Lateral(UDTF):
1771class Lateral(UDTF):
1772    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1775class MatchRecognize(Expression):
1776    arg_types = {
1777        "partition_by": False,
1778        "order": False,
1779        "measures": False,
1780        "rows": False,
1781        "after": False,
1782        "pattern": False,
1783        "define": False,
1784        "alias": False,
1785    }
class Final(Expression):
1790class Final(Expression):
1791    pass
class Offset(Expression):
1794class Offset(Expression):
1795    arg_types = {"this": False, "expression": True}
class Order(Expression):
1798class Order(Expression):
1799    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1804class Cluster(Order):
1805    pass
class Distribute(Order):
1808class Distribute(Order):
1809    pass
class Sort(Order):
1812class Sort(Order):
1813    pass
class Ordered(Expression):
1816class Ordered(Expression):
1817    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1820class Property(Expression):
1821    arg_types = {"this": True, "value": True}
class AlgorithmProperty(Property):
1824class AlgorithmProperty(Property):
1825    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1828class AutoIncrementProperty(Property):
1829    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1832class BlockCompressionProperty(Property):
1833    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1836class CharacterSetProperty(Property):
1837    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1840class ChecksumProperty(Property):
1841    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1844class CollateProperty(Property):
1845    arg_types = {"this": True}
class CopyGrantsProperty(Property):
1848class CopyGrantsProperty(Property):
1849    arg_types = {}
class DataBlocksizeProperty(Property):
1852class DataBlocksizeProperty(Property):
1853    arg_types = {
1854        "size": False,
1855        "units": False,
1856        "minimum": False,
1857        "maximum": False,
1858        "default": False,
1859    }
class DefinerProperty(Property):
1862class DefinerProperty(Property):
1863    arg_types = {"this": True}
class DistKeyProperty(Property):
1866class DistKeyProperty(Property):
1867    arg_types = {"this": True}
class DistStyleProperty(Property):
1870class DistStyleProperty(Property):
1871    arg_types = {"this": True}
class EngineProperty(Property):
1874class EngineProperty(Property):
1875    arg_types = {"this": True}
class ToTableProperty(Property):
1878class ToTableProperty(Property):
1879    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1882class ExecuteAsProperty(Property):
1883    arg_types = {"this": True}
class ExternalProperty(Property):
1886class ExternalProperty(Property):
1887    arg_types = {"this": False}
class FallbackProperty(Property):
1890class FallbackProperty(Property):
1891    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1894class FileFormatProperty(Property):
1895    arg_types = {"this": True}
class FreespaceProperty(Property):
1898class FreespaceProperty(Property):
1899    arg_types = {"this": True, "percent": False}
class InputOutputFormat(Expression):
1902class InputOutputFormat(Expression):
1903    arg_types = {"input_format": False, "output_format": False}
class IsolatedLoadingProperty(Property):
1906class IsolatedLoadingProperty(Property):
1907    arg_types = {
1908        "no": True,
1909        "concurrent": True,
1910        "for_all": True,
1911        "for_insert": True,
1912        "for_none": True,
1913    }
class JournalProperty(Property):
1916class JournalProperty(Property):
1917    arg_types = {
1918        "no": False,
1919        "dual": False,
1920        "before": False,
1921        "local": False,
1922        "after": False,
1923    }
class LanguageProperty(Property):
1926class LanguageProperty(Property):
1927    arg_types = {"this": True}
class DictProperty(Property):
1930class DictProperty(Property):
1931    arg_types = {"this": True, "kind": True, "settings": False}
class DictSubProperty(Property):
1934class DictSubProperty(Property):
1935    pass
class DictRange(Property):
1938class DictRange(Property):
1939    arg_types = {"this": True, "min": True, "max": True}
class OnCluster(Property):
1944class OnCluster(Property):
1945    arg_types = {"this": True}
class LikeProperty(Property):
1948class LikeProperty(Property):
1949    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1952class LocationProperty(Property):
1953    arg_types = {"this": True}
class LockingProperty(Property):
1956class LockingProperty(Property):
1957    arg_types = {
1958        "this": False,
1959        "kind": True,
1960        "for_or_in": True,
1961        "lock_type": True,
1962        "override": False,
1963    }
class LogProperty(Property):
1966class LogProperty(Property):
1967    arg_types = {"no": True}
class MaterializedProperty(Property):
1970class MaterializedProperty(Property):
1971    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1974class MergeBlockRatioProperty(Property):
1975    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1978class NoPrimaryIndexProperty(Property):
1979    arg_types = {}
class OnCommitProperty(Property):
1982class OnCommitProperty(Property):
1983    arg_type = {"delete": False}
class PartitionedByProperty(Property):
1986class PartitionedByProperty(Property):
1987    arg_types = {"this": True}
class ReturnsProperty(Property):
1990class ReturnsProperty(Property):
1991    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatProperty(Property):
1994class RowFormatProperty(Property):
1995    arg_types = {"this": True}
class RowFormatDelimitedProperty(Property):
1998class RowFormatDelimitedProperty(Property):
1999    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2000    arg_types = {
2001        "fields": False,
2002        "escaped": False,
2003        "collection_items": False,
2004        "map_keys": False,
2005        "lines": False,
2006        "null": False,
2007        "serde": False,
2008    }
class RowFormatSerdeProperty(Property):
2011class RowFormatSerdeProperty(Property):
2012    arg_types = {"this": True}
class SchemaCommentProperty(Property):
2015class SchemaCommentProperty(Property):
2016    arg_types = {"this": True}
class SerdeProperties(Property):
2019class SerdeProperties(Property):
2020    arg_types = {"expressions": True}
class SetProperty(Property):
2023class SetProperty(Property):
2024    arg_types = {"multi": True}
class SettingsProperty(Property):
2027class SettingsProperty(Property):
2028    arg_types = {"expressions": True}
class SortKeyProperty(Property):
2031class SortKeyProperty(Property):
2032    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
2035class SqlSecurityProperty(Property):
2036    arg_types = {"definer": True}
class StabilityProperty(Property):
2039class StabilityProperty(Property):
2040    arg_types = {"this": True}
class TemporaryProperty(Property):
2043class TemporaryProperty(Property):
2044    arg_types = {}
class TransientProperty(Property):
2047class TransientProperty(Property):
2048    arg_types = {"this": False}
class VolatileProperty(Property):
2051class VolatileProperty(Property):
2052    arg_types = {"this": False}
class WithDataProperty(Property):
2055class WithDataProperty(Property):
2056    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
2059class WithJournalTableProperty(Property):
2060    arg_types = {"this": True}
class Properties(Expression):
2063class Properties(Expression):
2064    arg_types = {"expressions": True}
2065
2066    NAME_TO_PROPERTY = {
2067        "ALGORITHM": AlgorithmProperty,
2068        "AUTO_INCREMENT": AutoIncrementProperty,
2069        "CHARACTER SET": CharacterSetProperty,
2070        "COLLATE": CollateProperty,
2071        "COMMENT": SchemaCommentProperty,
2072        "DEFINER": DefinerProperty,
2073        "DISTKEY": DistKeyProperty,
2074        "DISTSTYLE": DistStyleProperty,
2075        "ENGINE": EngineProperty,
2076        "EXECUTE AS": ExecuteAsProperty,
2077        "FORMAT": FileFormatProperty,
2078        "LANGUAGE": LanguageProperty,
2079        "LOCATION": LocationProperty,
2080        "PARTITIONED_BY": PartitionedByProperty,
2081        "RETURNS": ReturnsProperty,
2082        "ROW_FORMAT": RowFormatProperty,
2083        "SORTKEY": SortKeyProperty,
2084    }
2085
2086    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2087
2088    # CREATE property locations
2089    # Form: schema specified
2090    #   create [POST_CREATE]
2091    #     table a [POST_NAME]
2092    #     (b int) [POST_SCHEMA]
2093    #     with ([POST_WITH])
2094    #     index (b) [POST_INDEX]
2095    #
2096    # Form: alias selection
2097    #   create [POST_CREATE]
2098    #     table a [POST_NAME]
2099    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2100    #     index (c) [POST_INDEX]
2101    class Location(AutoName):
2102        POST_CREATE = auto()
2103        POST_NAME = auto()
2104        POST_SCHEMA = auto()
2105        POST_WITH = auto()
2106        POST_ALIAS = auto()
2107        POST_EXPRESSION = auto()
2108        POST_INDEX = auto()
2109        UNSUPPORTED = auto()
2110
2111    @classmethod
2112    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2113        expressions = []
2114        for key, value in properties_dict.items():
2115            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2116            if property_cls:
2117                expressions.append(property_cls(this=convert(value)))
2118            else:
2119                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2120
2121        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict: Dict) -> sqlglot.expressions.Properties:
2111    @classmethod
2112    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2113        expressions = []
2114        for key, value in properties_dict.items():
2115            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2116            if property_cls:
2117                expressions.append(property_cls(this=convert(value)))
2118            else:
2119                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2120
2121        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
2101    class Location(AutoName):
2102        POST_CREATE = auto()
2103        POST_NAME = auto()
2104        POST_SCHEMA = auto()
2105        POST_WITH = auto()
2106        POST_ALIAS = auto()
2107        POST_EXPRESSION = auto()
2108        POST_INDEX = auto()
2109        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):
2124class Qualify(Expression):
2125    pass
class Return(Expression):
2129class Return(Expression):
2130    pass
class Reference(Expression):
2133class Reference(Expression):
2134    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
2137class Tuple(Expression):
2138    arg_types = {"expressions": False}
2139
2140    def isin(
2141        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2142    ) -> In:
2143        return In(
2144            this=_maybe_copy(self, copy),
2145            expressions=[convert(e, copy=copy) for e in expressions],
2146            query=maybe_parse(query, copy=copy, **opts) if query else None,
2147        )
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2140    def isin(
2141        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2142    ) -> In:
2143        return In(
2144            this=_maybe_copy(self, copy),
2145            expressions=[convert(e, copy=copy) for e in expressions],
2146            query=maybe_parse(query, copy=copy, **opts) if query else None,
2147        )
class Subqueryable(Unionable):
2150class Subqueryable(Unionable):
2151    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2152        """
2153        Convert this expression to an aliased expression that can be used as a Subquery.
2154
2155        Example:
2156            >>> subquery = Select().select("x").from_("tbl").subquery()
2157            >>> Select().select("x").from_(subquery).sql()
2158            'SELECT x FROM (SELECT x FROM tbl)'
2159
2160        Args:
2161            alias (str | Identifier): an optional alias for the subquery
2162            copy (bool): if `False`, modify this expression instance in-place.
2163
2164        Returns:
2165            Alias: the subquery
2166        """
2167        instance = _maybe_copy(self, copy)
2168        if not isinstance(alias, Expression):
2169            alias = TableAlias(this=to_identifier(alias)) if alias else None
2170
2171        return Subquery(this=instance, alias=alias)
2172
2173    def limit(
2174        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2175    ) -> Select:
2176        raise NotImplementedError
2177
2178    @property
2179    def ctes(self):
2180        with_ = self.args.get("with")
2181        if not with_:
2182            return []
2183        return with_.expressions
2184
2185    @property
2186    def selects(self):
2187        raise NotImplementedError("Subqueryable objects must implement `selects`")
2188
2189    @property
2190    def named_selects(self):
2191        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2192
2193    def with_(
2194        self,
2195        alias: ExpOrStr,
2196        as_: ExpOrStr,
2197        recursive: t.Optional[bool] = None,
2198        append: bool = True,
2199        dialect: DialectType = None,
2200        copy: bool = True,
2201        **opts,
2202    ) -> Subqueryable:
2203        """
2204        Append to or set the common table expressions.
2205
2206        Example:
2207            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2208            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2209
2210        Args:
2211            alias: the SQL code string to parse as the table name.
2212                If an `Expression` instance is passed, this is used as-is.
2213            as_: the SQL code string to parse as the table expression.
2214                If an `Expression` instance is passed, it will be used as-is.
2215            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2216            append: if `True`, add to any existing expressions.
2217                Otherwise, this resets the expressions.
2218            dialect: the dialect used to parse the input expression.
2219            copy: if `False`, modify this expression instance in-place.
2220            opts: other options to use to parse the input expressions.
2221
2222        Returns:
2223            The modified expression.
2224        """
2225        return _apply_cte_builder(
2226            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2227        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2151    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2152        """
2153        Convert this expression to an aliased expression that can be used as a Subquery.
2154
2155        Example:
2156            >>> subquery = Select().select("x").from_("tbl").subquery()
2157            >>> Select().select("x").from_(subquery).sql()
2158            'SELECT x FROM (SELECT x FROM tbl)'
2159
2160        Args:
2161            alias (str | Identifier): an optional alias for the subquery
2162            copy (bool): if `False`, modify this expression instance in-place.
2163
2164        Returns:
2165            Alias: the subquery
2166        """
2167        instance = _maybe_copy(self, copy)
2168        if not isinstance(alias, Expression):
2169            alias = TableAlias(this=to_identifier(alias)) if alias else None
2170
2171        return Subquery(this=instance, alias=alias)

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2173    def limit(
2174        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2175    ) -> Select:
2176        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:
2193    def with_(
2194        self,
2195        alias: ExpOrStr,
2196        as_: ExpOrStr,
2197        recursive: t.Optional[bool] = None,
2198        append: bool = True,
2199        dialect: DialectType = None,
2200        copy: bool = True,
2201        **opts,
2202    ) -> Subqueryable:
2203        """
2204        Append to or set the common table expressions.
2205
2206        Example:
2207            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2208            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2209
2210        Args:
2211            alias: the SQL code string to parse as the table name.
2212                If an `Expression` instance is passed, this is used as-is.
2213            as_: the SQL code string to parse as the table expression.
2214                If an `Expression` instance is passed, it will be used as-is.
2215            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2216            append: if `True`, add to any existing expressions.
2217                Otherwise, this resets the expressions.
2218            dialect: the dialect used to parse the input expression.
2219            copy: if `False`, modify this expression instance in-place.
2220            opts: other options to use to parse the input expressions.
2221
2222        Returns:
2223            The modified expression.
2224        """
2225        return _apply_cte_builder(
2226            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2227        )

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):
2253class Table(Expression):
2254    arg_types = {
2255        "this": True,
2256        "alias": False,
2257        "db": False,
2258        "catalog": False,
2259        "laterals": False,
2260        "joins": False,
2261        "pivots": False,
2262        "hints": False,
2263        "system_time": False,
2264    }
2265
2266    @property
2267    def db(self) -> str:
2268        return self.text("db")
2269
2270    @property
2271    def catalog(self) -> str:
2272        return self.text("catalog")
2273
2274    @property
2275    def parts(self) -> t.List[Identifier]:
2276        """Return the parts of a table in order catalog, db, table."""
2277        return [
2278            t.cast(Identifier, self.args[part])
2279            for part in ("catalog", "db", "this")
2280            if self.args.get(part)
2281        ]

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

class SystemTime(Expression):
2285class SystemTime(Expression):
2286    arg_types = {
2287        "this": False,
2288        "expression": False,
2289        "kind": True,
2290    }
class Union(Subqueryable):
2293class Union(Subqueryable):
2294    arg_types = {
2295        "with": False,
2296        "this": True,
2297        "expression": True,
2298        "distinct": False,
2299        **QUERY_MODIFIERS,
2300    }
2301
2302    def limit(
2303        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2304    ) -> Select:
2305        """
2306        Set the LIMIT expression.
2307
2308        Example:
2309            >>> select("1").union(select("1")).limit(1).sql()
2310            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2311
2312        Args:
2313            expression: the SQL code string to parse.
2314                This can also be an integer.
2315                If a `Limit` instance is passed, this is used as-is.
2316                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2317            dialect: the dialect used to parse the input expression.
2318            copy: if `False`, modify this expression instance in-place.
2319            opts: other options to use to parse the input expressions.
2320
2321        Returns:
2322            The limited subqueryable.
2323        """
2324        return (
2325            select("*")
2326            .from_(self.subquery(alias="_l_0", copy=copy))
2327            .limit(expression, dialect=dialect, copy=False, **opts)
2328        )
2329
2330    def select(
2331        self,
2332        *expressions: t.Optional[ExpOrStr],
2333        append: bool = True,
2334        dialect: DialectType = None,
2335        copy: bool = True,
2336        **opts,
2337    ) -> Union:
2338        """Append to or set the SELECT of the union recursively.
2339
2340        Example:
2341            >>> from sqlglot import parse_one
2342            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2343            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2344
2345        Args:
2346            *expressions: the SQL code strings to parse.
2347                If an `Expression` instance is passed, it will be used as-is.
2348            append: if `True`, add to any existing expressions.
2349                Otherwise, this resets the expressions.
2350            dialect: the dialect used to parse the input expressions.
2351            copy: if `False`, modify this expression instance in-place.
2352            opts: other options to use to parse the input expressions.
2353
2354        Returns:
2355            Union: the modified expression.
2356        """
2357        this = self.copy() if copy else self
2358        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2359        this.expression.unnest().select(
2360            *expressions, append=append, dialect=dialect, copy=False, **opts
2361        )
2362        return this
2363
2364    @property
2365    def named_selects(self):
2366        return self.this.unnest().named_selects
2367
2368    @property
2369    def is_star(self) -> bool:
2370        return self.this.is_star or self.expression.is_star
2371
2372    @property
2373    def selects(self):
2374        return self.this.unnest().selects
2375
2376    @property
2377    def left(self):
2378        return self.this
2379
2380    @property
2381    def right(self):
2382        return self.expression
def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2302    def limit(
2303        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2304    ) -> Select:
2305        """
2306        Set the LIMIT expression.
2307
2308        Example:
2309            >>> select("1").union(select("1")).limit(1).sql()
2310            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2311
2312        Args:
2313            expression: the SQL code string to parse.
2314                This can also be an integer.
2315                If a `Limit` instance is passed, this is used as-is.
2316                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2317            dialect: the dialect used to parse the input expression.
2318            copy: if `False`, modify this expression instance in-place.
2319            opts: other options to use to parse the input expressions.
2320
2321        Returns:
2322            The limited subqueryable.
2323        """
2324        return (
2325            select("*")
2326            .from_(self.subquery(alias="_l_0", copy=copy))
2327            .limit(expression, dialect=dialect, copy=False, **opts)
2328        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The limited subqueryable.

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

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • expression : the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def group_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2479    def group_by(
2480        self,
2481        *expressions: t.Optional[ExpOrStr],
2482        append: bool = True,
2483        dialect: DialectType = None,
2484        copy: bool = True,
2485        **opts,
2486    ) -> Select:
2487        """
2488        Set the GROUP BY expression.
2489
2490        Example:
2491            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2492            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2493
2494        Args:
2495            *expressions: the SQL code strings to parse.
2496                If a `Group` instance is passed, this is used as-is.
2497                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2498                If nothing is passed in then a group by is not applied to the expression
2499            append: if `True`, add to any existing expressions.
2500                Otherwise, this flattens all the `Group` expression into a single expression.
2501            dialect: the dialect used to parse the input expression.
2502            copy: if `False`, modify this expression instance in-place.
2503            opts: other options to use to parse the input expressions.
2504
2505        Returns:
2506            The modified Select expression.
2507        """
2508        if not expressions:
2509            return self if not copy else self.copy()
2510
2511        return _apply_child_list_builder(
2512            *expressions,
2513            instance=self,
2514            arg="group",
2515            append=append,
2516            copy=copy,
2517            prefix="GROUP BY",
2518            into=Group,
2519            dialect=dialect,
2520            **opts,
2521        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def order_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2523    def order_by(
2524        self,
2525        *expressions: t.Optional[ExpOrStr],
2526        append: bool = True,
2527        dialect: DialectType = None,
2528        copy: bool = True,
2529        **opts,
2530    ) -> Select:
2531        """
2532        Set the ORDER BY expression.
2533
2534        Example:
2535            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2536            'SELECT x FROM tbl ORDER BY x DESC'
2537
2538        Args:
2539            *expressions: the SQL code strings to parse.
2540                If a `Group` instance is passed, this is used as-is.
2541                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2542            append: if `True`, add to any existing expressions.
2543                Otherwise, this flattens all the `Order` expression into a single expression.
2544            dialect: the dialect used to parse the input expression.
2545            copy: if `False`, modify this expression instance in-place.
2546            opts: other options to use to parse the input expressions.
2547
2548        Returns:
2549            The modified Select expression.
2550        """
2551        return _apply_child_list_builder(
2552            *expressions,
2553            instance=self,
2554            arg="order",
2555            append=append,
2556            copy=copy,
2557            prefix="ORDER BY",
2558            into=Order,
2559            dialect=dialect,
2560            **opts,
2561        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def sort_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2563    def sort_by(
2564        self,
2565        *expressions: t.Optional[ExpOrStr],
2566        append: bool = True,
2567        dialect: DialectType = None,
2568        copy: bool = True,
2569        **opts,
2570    ) -> Select:
2571        """
2572        Set the SORT BY expression.
2573
2574        Example:
2575            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2576            'SELECT x FROM tbl SORT BY x DESC'
2577
2578        Args:
2579            *expressions: the SQL code strings to parse.
2580                If a `Group` instance is passed, this is used as-is.
2581                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2582            append: if `True`, add to any existing expressions.
2583                Otherwise, this flattens all the `Order` expression into a single expression.
2584            dialect: the dialect used to parse the input expression.
2585            copy: if `False`, modify this expression instance in-place.
2586            opts: other options to use to parse the input expressions.
2587
2588        Returns:
2589            The modified Select expression.
2590        """
2591        return _apply_child_list_builder(
2592            *expressions,
2593            instance=self,
2594            arg="sort",
2595            append=append,
2596            copy=copy,
2597            prefix="SORT BY",
2598            into=Sort,
2599            dialect=dialect,
2600            **opts,
2601        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def cluster_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2603    def cluster_by(
2604        self,
2605        *expressions: t.Optional[ExpOrStr],
2606        append: bool = True,
2607        dialect: DialectType = None,
2608        copy: bool = True,
2609        **opts,
2610    ) -> Select:
2611        """
2612        Set the CLUSTER BY expression.
2613
2614        Example:
2615            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2616            'SELECT x FROM tbl CLUSTER BY x DESC'
2617
2618        Args:
2619            *expressions: the SQL code strings to parse.
2620                If a `Group` instance is passed, this is used as-is.
2621                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2622            append: if `True`, add to any existing expressions.
2623                Otherwise, this flattens all the `Order` expression into a single expression.
2624            dialect: the dialect used to parse the input expression.
2625            copy: if `False`, modify this expression instance in-place.
2626            opts: other options to use to parse the input expressions.
2627
2628        Returns:
2629            The modified Select expression.
2630        """
2631        return _apply_child_list_builder(
2632            *expressions,
2633            instance=self,
2634            arg="cluster",
2635            append=append,
2636            copy=copy,
2637            prefix="CLUSTER BY",
2638            into=Cluster,
2639            dialect=dialect,
2640            **opts,
2641        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2643    def limit(
2644        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2645    ) -> Select:
2646        """
2647        Set the LIMIT expression.
2648
2649        Example:
2650            >>> Select().from_("tbl").select("x").limit(10).sql()
2651            'SELECT x FROM tbl LIMIT 10'
2652
2653        Args:
2654            expression: the SQL code string to parse.
2655                This can also be an integer.
2656                If a `Limit` instance is passed, this is used as-is.
2657                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2658            dialect: the dialect used to parse the input expression.
2659            copy: if `False`, modify this expression instance in-place.
2660            opts: other options to use to parse the input expressions.
2661
2662        Returns:
2663            Select: the modified expression.
2664        """
2665        return _apply_builder(
2666            expression=expression,
2667            instance=self,
2668            arg="limit",
2669            into=Limit,
2670            prefix="LIMIT",
2671            dialect=dialect,
2672            copy=copy,
2673            **opts,
2674        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2676    def offset(
2677        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2678    ) -> Select:
2679        """
2680        Set the OFFSET expression.
2681
2682        Example:
2683            >>> Select().from_("tbl").select("x").offset(10).sql()
2684            'SELECT x FROM tbl OFFSET 10'
2685
2686        Args:
2687            expression: the SQL code string to parse.
2688                This can also be an integer.
2689                If a `Offset` instance is passed, this is used as-is.
2690                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2691            dialect: the dialect used to parse the input expression.
2692            copy: if `False`, modify this expression instance in-place.
2693            opts: other options to use to parse the input expressions.
2694
2695        Returns:
2696            The modified Select expression.
2697        """
2698        return _apply_builder(
2699            expression=expression,
2700            instance=self,
2701            arg="offset",
2702            into=Offset,
2703            prefix="OFFSET",
2704            dialect=dialect,
2705            copy=copy,
2706            **opts,
2707        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2709    def select(
2710        self,
2711        *expressions: t.Optional[ExpOrStr],
2712        append: bool = True,
2713        dialect: DialectType = None,
2714        copy: bool = True,
2715        **opts,
2716    ) -> Select:
2717        """
2718        Append to or set the SELECT expressions.
2719
2720        Example:
2721            >>> Select().select("x", "y").sql()
2722            'SELECT x, y'
2723
2724        Args:
2725            *expressions: the SQL code strings to parse.
2726                If an `Expression` instance is passed, it will be used as-is.
2727            append: if `True`, add to any existing expressions.
2728                Otherwise, this resets the expressions.
2729            dialect: the dialect used to parse the input expressions.
2730            copy: if `False`, modify this expression instance in-place.
2731            opts: other options to use to parse the input expressions.
2732
2733        Returns:
2734            The modified Select expression.
2735        """
2736        return _apply_list_builder(
2737            *expressions,
2738            instance=self,
2739            arg="expressions",
2740            append=append,
2741            dialect=dialect,
2742            copy=copy,
2743            **opts,
2744        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def lateral( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2746    def lateral(
2747        self,
2748        *expressions: t.Optional[ExpOrStr],
2749        append: bool = True,
2750        dialect: DialectType = None,
2751        copy: bool = True,
2752        **opts,
2753    ) -> Select:
2754        """
2755        Append to or set the LATERAL expressions.
2756
2757        Example:
2758            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2759            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2760
2761        Args:
2762            *expressions: the SQL code strings to parse.
2763                If an `Expression` instance is passed, it will be used as-is.
2764            append: if `True`, add to any existing expressions.
2765                Otherwise, this resets the expressions.
2766            dialect: the dialect used to parse the input expressions.
2767            copy: if `False`, modify this expression instance in-place.
2768            opts: other options to use to parse the input expressions.
2769
2770        Returns:
2771            The modified Select expression.
2772        """
2773        return _apply_list_builder(
2774            *expressions,
2775            instance=self,
2776            arg="laterals",
2777            append=append,
2778            into=Lateral,
2779            prefix="LATERAL VIEW",
2780            dialect=dialect,
2781            copy=copy,
2782            **opts,
2783        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def join( self, expression: Union[str, sqlglot.expressions.Expression], on: Union[str, sqlglot.expressions.Expression, NoneType] = None, using: Union[str, sqlglot.expressions.Expression, List[Union[str, sqlglot.expressions.Expression]], NoneType] = None, append: bool = True, join_type: Optional[str] = None, join_alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2785    def join(
2786        self,
2787        expression: ExpOrStr,
2788        on: t.Optional[ExpOrStr] = None,
2789        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2790        append: bool = True,
2791        join_type: t.Optional[str] = None,
2792        join_alias: t.Optional[Identifier | str] = None,
2793        dialect: DialectType = None,
2794        copy: bool = True,
2795        **opts,
2796    ) -> Select:
2797        """
2798        Append to or set the JOIN expressions.
2799
2800        Example:
2801            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2802            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2803
2804            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2805            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2806
2807            Use `join_type` to change the type of join:
2808
2809            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2810            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2811
2812        Args:
2813            expression: the SQL code string to parse.
2814                If an `Expression` instance is passed, it will be used as-is.
2815            on: optionally specify the join "on" criteria as a SQL string.
2816                If an `Expression` instance is passed, it will be used as-is.
2817            using: optionally specify the join "using" criteria as a SQL string.
2818                If an `Expression` instance is passed, it will be used as-is.
2819            append: if `True`, add to any existing expressions.
2820                Otherwise, this resets the expressions.
2821            join_type: if set, alter the parsed join type.
2822            join_alias: an optional alias for the joined source.
2823            dialect: the dialect used to parse the input expressions.
2824            copy: if `False`, modify this expression instance in-place.
2825            opts: other options to use to parse the input expressions.
2826
2827        Returns:
2828            Select: the modified expression.
2829        """
2830        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2831
2832        try:
2833            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2834        except ParseError:
2835            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2836
2837        join = expression if isinstance(expression, Join) else Join(this=expression)
2838
2839        if isinstance(join.this, Select):
2840            join.this.replace(join.this.subquery())
2841
2842        if join_type:
2843            method: t.Optional[Token]
2844            side: t.Optional[Token]
2845            kind: t.Optional[Token]
2846
2847            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2848
2849            if method:
2850                join.set("method", method.text)
2851            if side:
2852                join.set("side", side.text)
2853            if kind:
2854                join.set("kind", kind.text)
2855
2856        if on:
2857            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2858            join.set("on", on)
2859
2860        if using:
2861            join = _apply_list_builder(
2862                *ensure_list(using),
2863                instance=join,
2864                arg="using",
2865                append=append,
2866                copy=copy,
2867                **opts,
2868            )
2869
2870        if join_alias:
2871            join.set("this", alias_(join.this, join_alias, table=True))
2872
2873        return _apply_list_builder(
2874            join,
2875            instance=self,
2876            arg="joins",
2877            append=append,
2878            copy=copy,
2879            **opts,
2880        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on: optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using: optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type: if set, alter the parsed join type.
  • join_alias: an optional alias for the joined source.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2882    def where(
2883        self,
2884        *expressions: t.Optional[ExpOrStr],
2885        append: bool = True,
2886        dialect: DialectType = None,
2887        copy: bool = True,
2888        **opts,
2889    ) -> Select:
2890        """
2891        Append to or set the WHERE expressions.
2892
2893        Example:
2894            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2895            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2896
2897        Args:
2898            *expressions: the SQL code strings to parse.
2899                If an `Expression` instance is passed, it will be used as-is.
2900                Multiple expressions are combined with an AND operator.
2901            append: if `True`, AND the new expressions to any existing expression.
2902                Otherwise, this resets the expression.
2903            dialect: the dialect used to parse the input expressions.
2904            copy: if `False`, modify this expression instance in-place.
2905            opts: other options to use to parse the input expressions.
2906
2907        Returns:
2908            Select: the modified expression.
2909        """
2910        return _apply_conjunction_builder(
2911            *expressions,
2912            instance=self,
2913            arg="where",
2914            append=append,
2915            into=Where,
2916            dialect=dialect,
2917            copy=copy,
2918            **opts,
2919        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2921    def having(
2922        self,
2923        *expressions: t.Optional[ExpOrStr],
2924        append: bool = True,
2925        dialect: DialectType = None,
2926        copy: bool = True,
2927        **opts,
2928    ) -> Select:
2929        """
2930        Append to or set the HAVING expressions.
2931
2932        Example:
2933            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2934            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2935
2936        Args:
2937            *expressions: the SQL code strings to parse.
2938                If an `Expression` instance is passed, it will be used as-is.
2939                Multiple expressions are combined with an AND operator.
2940            append: if `True`, AND the new expressions to any existing expression.
2941                Otherwise, this resets the expression.
2942            dialect: the dialect used to parse the input expressions.
2943            copy: if `False`, modify this expression instance in-place.
2944            opts: other options to use to parse the input expressions.
2945
2946        Returns:
2947            The modified Select expression.
2948        """
2949        return _apply_conjunction_builder(
2950            *expressions,
2951            instance=self,
2952            arg="having",
2953            append=append,
2954            into=Having,
2955            dialect=dialect,
2956            copy=copy,
2957            **opts,
2958        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def window( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2960    def window(
2961        self,
2962        *expressions: t.Optional[ExpOrStr],
2963        append: bool = True,
2964        dialect: DialectType = None,
2965        copy: bool = True,
2966        **opts,
2967    ) -> Select:
2968        return _apply_list_builder(
2969            *expressions,
2970            instance=self,
2971            arg="windows",
2972            append=append,
2973            into=Window,
2974            dialect=dialect,
2975            copy=copy,
2976            **opts,
2977        )
def qualify( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2979    def qualify(
2980        self,
2981        *expressions: t.Optional[ExpOrStr],
2982        append: bool = True,
2983        dialect: DialectType = None,
2984        copy: bool = True,
2985        **opts,
2986    ) -> Select:
2987        return _apply_conjunction_builder(
2988            *expressions,
2989            instance=self,
2990            arg="qualify",
2991            append=append,
2992            into=Qualify,
2993            dialect=dialect,
2994            copy=copy,
2995            **opts,
2996        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2998    def distinct(
2999        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3000    ) -> Select:
3001        """
3002        Set the OFFSET expression.
3003
3004        Example:
3005            >>> Select().from_("tbl").select("x").distinct().sql()
3006            'SELECT DISTINCT x FROM tbl'
3007
3008        Args:
3009            ons: the expressions to distinct on
3010            distinct: whether the Select should be distinct
3011            copy: if `False`, modify this expression instance in-place.
3012
3013        Returns:
3014            Select: the modified expression.
3015        """
3016        instance = _maybe_copy(self, copy)
3017        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3018        instance.set("distinct", Distinct(on=on) if distinct else None)
3019        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • ons: the expressions to distinct on
  • distinct: whether the Select should be distinct
  • copy: if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table: Union[str, sqlglot.expressions.Expression], properties: Optional[Dict] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Create:
3021    def ctas(
3022        self,
3023        table: ExpOrStr,
3024        properties: t.Optional[t.Dict] = None,
3025        dialect: DialectType = None,
3026        copy: bool = True,
3027        **opts,
3028    ) -> Create:
3029        """
3030        Convert this expression to a CREATE TABLE AS statement.
3031
3032        Example:
3033            >>> Select().select("*").from_("tbl").ctas("x").sql()
3034            'CREATE TABLE x AS SELECT * FROM tbl'
3035
3036        Args:
3037            table: the SQL code string to parse as the table name.
3038                If another `Expression` instance is passed, it will be used as-is.
3039            properties: an optional mapping of table properties
3040            dialect: the dialect used to parse the input table.
3041            copy: if `False`, modify this expression instance in-place.
3042            opts: other options to use to parse the input table.
3043
3044        Returns:
3045            The new Create expression.
3046        """
3047        instance = _maybe_copy(self, copy)
3048        table_expression = maybe_parse(
3049            table,
3050            into=Table,
3051            dialect=dialect,
3052            **opts,
3053        )
3054        properties_expression = None
3055        if properties:
3056            properties_expression = Properties.from_dict(properties)
3057
3058        return Create(
3059            this=table_expression,
3060            kind="table",
3061            expression=instance,
3062            properties=properties_expression,
3063        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table: the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties: an optional mapping of table properties
  • dialect: the dialect used to parse the input table.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input table.
Returns:

The new Create expression.

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3065    def lock(self, update: bool = True, copy: bool = True) -> Select:
3066        """
3067        Set the locking read mode for this expression.
3068
3069        Examples:
3070            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3071            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3072
3073            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3074            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3075
3076        Args:
3077            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3078            copy: if `False`, modify this expression instance in-place.
3079
3080        Returns:
3081            The modified expression.
3082        """
3083        inst = _maybe_copy(self, copy)
3084        inst.set("locks", [Lock(update=update)])
3085
3086        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.

def hint( self, *hints: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True) -> sqlglot.expressions.Select:
3088    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3089        """
3090        Set hints for this expression.
3091
3092        Examples:
3093            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3094            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3095
3096        Args:
3097            hints: The SQL code strings to parse as the hints.
3098                If an `Expression` instance is passed, it will be used as-is.
3099            dialect: The dialect used to parse the hints.
3100            copy: If `False`, modify this expression instance in-place.
3101
3102        Returns:
3103            The modified expression.
3104        """
3105        inst = _maybe_copy(self, copy)
3106        inst.set(
3107            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3108        )
3109
3110        return inst

Set hints for this expression.

Examples:
>>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
'SELECT /*+ BROADCAST(y) */ x FROM tbl'
Arguments:
  • hints: The SQL code strings to parse as the hints. If an Expression instance is passed, it will be used as-is.
  • dialect: The dialect used to parse the hints.
  • 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):
3125class Subquery(DerivedTable, Unionable):
3126    arg_types = {
3127        "this": True,
3128        "alias": False,
3129        "with": False,
3130        **QUERY_MODIFIERS,
3131    }
3132
3133    def unnest(self):
3134        """
3135        Returns the first non subquery.
3136        """
3137        expression = self
3138        while isinstance(expression, Subquery):
3139            expression = expression.this
3140        return expression
3141
3142    @property
3143    def is_star(self) -> bool:
3144        return self.this.is_star
3145
3146    @property
3147    def output_name(self) -> str:
3148        return self.alias
def unnest(self):
3133    def unnest(self):
3134        """
3135        Returns the first non subquery.
3136        """
3137        expression = self
3138        while isinstance(expression, Subquery):
3139            expression = expression.this
3140        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class TableSample(Expression):
3151class TableSample(Expression):
3152    arg_types = {
3153        "this": False,
3154        "method": False,
3155        "bucket_numerator": False,
3156        "bucket_denominator": False,
3157        "bucket_field": False,
3158        "percent": False,
3159        "rows": False,
3160        "size": False,
3161        "seed": False,
3162        "kind": False,
3163    }
class Tag(Expression):
3166class Tag(Expression):
3167    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3168
3169    arg_types = {
3170        "this": False,
3171        "prefix": False,
3172        "postfix": False,
3173    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
3178class Pivot(Expression):
3179    arg_types = {
3180        "this": False,
3181        "alias": False,
3182        "expressions": True,
3183        "field": False,
3184        "unpivot": False,
3185        "using": False,
3186        "group": False,
3187        "columns": False,
3188    }
class Window(Expression):
3191class Window(Expression):
3192    arg_types = {
3193        "this": True,
3194        "partition_by": False,
3195        "order": False,
3196        "spec": False,
3197        "alias": False,
3198        "over": False,
3199        "first": False,
3200    }
class WindowSpec(Expression):
3203class WindowSpec(Expression):
3204    arg_types = {
3205        "kind": False,
3206        "start": False,
3207        "start_side": False,
3208        "end": False,
3209        "end_side": False,
3210    }
class Where(Expression):
3213class Where(Expression):
3214    pass
class Star(Expression):
3217class Star(Expression):
3218    arg_types = {"except": False, "replace": False}
3219
3220    @property
3221    def name(self) -> str:
3222        return "*"
3223
3224    @property
3225    def output_name(self) -> str:
3226        return self.name
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Parameter(Condition):
3229class Parameter(Condition):
3230    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Condition):
3233class SessionParameter(Condition):
3234    arg_types = {"this": True, "kind": False}
class Placeholder(Condition):
3237class Placeholder(Condition):
3238    arg_types = {"this": False, "kind": False}
class Null(Condition):
3241class Null(Condition):
3242    arg_types: t.Dict[str, t.Any] = {}
3243
3244    @property
3245    def name(self) -> str:
3246        return "NULL"
class Boolean(Condition):
3249class Boolean(Condition):
3250    pass
class DataTypeSize(Expression):
3253class DataTypeSize(Expression):
3254    arg_types = {"this": True, "expression": False}
class DataType(Expression):
3257class DataType(Expression):
3258    arg_types = {
3259        "this": True,
3260        "expressions": False,
3261        "nested": False,
3262        "values": False,
3263        "prefix": False,
3264    }
3265
3266    class Type(AutoName):
3267        ARRAY = auto()
3268        BIGDECIMAL = auto()
3269        BIGINT = auto()
3270        BIGSERIAL = auto()
3271        BINARY = auto()
3272        BIT = auto()
3273        BOOLEAN = auto()
3274        CHAR = auto()
3275        DATE = auto()
3276        DATETIME = auto()
3277        DATETIME64 = auto()
3278        ENUM = auto()
3279        INT4RANGE = auto()
3280        INT4MULTIRANGE = auto()
3281        INT8RANGE = auto()
3282        INT8MULTIRANGE = auto()
3283        NUMRANGE = auto()
3284        NUMMULTIRANGE = auto()
3285        TSRANGE = auto()
3286        TSMULTIRANGE = auto()
3287        TSTZRANGE = auto()
3288        TSTZMULTIRANGE = auto()
3289        DATERANGE = auto()
3290        DATEMULTIRANGE = auto()
3291        DECIMAL = auto()
3292        DOUBLE = auto()
3293        FLOAT = auto()
3294        GEOGRAPHY = auto()
3295        GEOMETRY = auto()
3296        HLLSKETCH = auto()
3297        HSTORE = auto()
3298        IMAGE = auto()
3299        INET = auto()
3300        INT = auto()
3301        INT128 = auto()
3302        INT256 = auto()
3303        INTERVAL = auto()
3304        JSON = auto()
3305        JSONB = auto()
3306        LONGBLOB = auto()
3307        LONGTEXT = auto()
3308        MAP = auto()
3309        MEDIUMBLOB = auto()
3310        MEDIUMTEXT = auto()
3311        MONEY = auto()
3312        NCHAR = auto()
3313        NULL = auto()
3314        NULLABLE = auto()
3315        NVARCHAR = auto()
3316        OBJECT = auto()
3317        ROWVERSION = auto()
3318        SERIAL = auto()
3319        SET = auto()
3320        SMALLINT = auto()
3321        SMALLMONEY = auto()
3322        SMALLSERIAL = auto()
3323        STRUCT = auto()
3324        SUPER = auto()
3325        TEXT = auto()
3326        TIME = auto()
3327        TIMESTAMP = auto()
3328        TIMESTAMPTZ = auto()
3329        TIMESTAMPLTZ = auto()
3330        TINYINT = auto()
3331        UBIGINT = auto()
3332        UINT = auto()
3333        USMALLINT = auto()
3334        UTINYINT = auto()
3335        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3336        UINT128 = auto()
3337        UINT256 = auto()
3338        UNIQUEIDENTIFIER = auto()
3339        UUID = auto()
3340        VARBINARY = auto()
3341        VARCHAR = auto()
3342        VARIANT = auto()
3343        XML = auto()
3344
3345    TEXT_TYPES = {
3346        Type.CHAR,
3347        Type.NCHAR,
3348        Type.VARCHAR,
3349        Type.NVARCHAR,
3350        Type.TEXT,
3351    }
3352
3353    INTEGER_TYPES = {
3354        Type.INT,
3355        Type.TINYINT,
3356        Type.SMALLINT,
3357        Type.BIGINT,
3358        Type.INT128,
3359        Type.INT256,
3360    }
3361
3362    FLOAT_TYPES = {
3363        Type.FLOAT,
3364        Type.DOUBLE,
3365    }
3366
3367    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3368
3369    TEMPORAL_TYPES = {
3370        Type.TIME,
3371        Type.TIMESTAMP,
3372        Type.TIMESTAMPTZ,
3373        Type.TIMESTAMPLTZ,
3374        Type.DATE,
3375        Type.DATETIME,
3376        Type.DATETIME64,
3377    }
3378
3379    META_TYPES = {"UNKNOWN", "NULL"}
3380
3381    @classmethod
3382    def build(
3383        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3384    ) -> DataType:
3385        from sqlglot import parse_one
3386
3387        if isinstance(dtype, str):
3388            upper = dtype.upper()
3389            if upper in DataType.META_TYPES:
3390                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3391            else:
3392                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3393
3394            if data_type_exp is None:
3395                raise ValueError(f"Unparsable data type value: {dtype}")
3396        elif isinstance(dtype, DataType.Type):
3397            data_type_exp = DataType(this=dtype)
3398        elif isinstance(dtype, DataType):
3399            return dtype
3400        else:
3401            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3402
3403        return DataType(**{**data_type_exp.args, **kwargs})
3404
3405    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3406        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
@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:
3381    @classmethod
3382    def build(
3383        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3384    ) -> DataType:
3385        from sqlglot import parse_one
3386
3387        if isinstance(dtype, str):
3388            upper = dtype.upper()
3389            if upper in DataType.META_TYPES:
3390                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3391            else:
3392                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3393
3394            if data_type_exp is None:
3395                raise ValueError(f"Unparsable data type value: {dtype}")
3396        elif isinstance(dtype, DataType.Type):
3397            data_type_exp = DataType(this=dtype)
3398        elif isinstance(dtype, DataType):
3399            return dtype
3400        else:
3401            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3402
3403        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3405    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3406        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
class DataType.Type(sqlglot.helper.AutoName):
3266    class Type(AutoName):
3267        ARRAY = auto()
3268        BIGDECIMAL = auto()
3269        BIGINT = auto()
3270        BIGSERIAL = auto()
3271        BINARY = auto()
3272        BIT = auto()
3273        BOOLEAN = auto()
3274        CHAR = auto()
3275        DATE = auto()
3276        DATETIME = auto()
3277        DATETIME64 = auto()
3278        ENUM = auto()
3279        INT4RANGE = auto()
3280        INT4MULTIRANGE = auto()
3281        INT8RANGE = auto()
3282        INT8MULTIRANGE = auto()
3283        NUMRANGE = auto()
3284        NUMMULTIRANGE = auto()
3285        TSRANGE = auto()
3286        TSMULTIRANGE = auto()
3287        TSTZRANGE = auto()
3288        TSTZMULTIRANGE = auto()
3289        DATERANGE = auto()
3290        DATEMULTIRANGE = auto()
3291        DECIMAL = auto()
3292        DOUBLE = auto()
3293        FLOAT = auto()
3294        GEOGRAPHY = auto()
3295        GEOMETRY = auto()
3296        HLLSKETCH = auto()
3297        HSTORE = auto()
3298        IMAGE = auto()
3299        INET = auto()
3300        INT = auto()
3301        INT128 = auto()
3302        INT256 = auto()
3303        INTERVAL = auto()
3304        JSON = auto()
3305        JSONB = auto()
3306        LONGBLOB = auto()
3307        LONGTEXT = auto()
3308        MAP = auto()
3309        MEDIUMBLOB = auto()
3310        MEDIUMTEXT = auto()
3311        MONEY = auto()
3312        NCHAR = auto()
3313        NULL = auto()
3314        NULLABLE = auto()
3315        NVARCHAR = auto()
3316        OBJECT = auto()
3317        ROWVERSION = auto()
3318        SERIAL = auto()
3319        SET = auto()
3320        SMALLINT = auto()
3321        SMALLMONEY = auto()
3322        SMALLSERIAL = auto()
3323        STRUCT = auto()
3324        SUPER = auto()
3325        TEXT = auto()
3326        TIME = auto()
3327        TIMESTAMP = auto()
3328        TIMESTAMPTZ = auto()
3329        TIMESTAMPLTZ = auto()
3330        TINYINT = auto()
3331        UBIGINT = auto()
3332        UINT = auto()
3333        USMALLINT = auto()
3334        UTINYINT = auto()
3335        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3336        UINT128 = auto()
3337        UINT256 = auto()
3338        UNIQUEIDENTIFIER = auto()
3339        UUID = auto()
3340        VARBINARY = auto()
3341        VARCHAR = auto()
3342        VARIANT = auto()
3343        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'>
ENUM = <Type.ENUM: 'ENUM'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
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'>
SET = <Type.SET: 'SET'>
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):
3410class PseudoType(Expression):
3411    pass
class SubqueryPredicate(Predicate):
3415class SubqueryPredicate(Predicate):
3416    pass
class All(SubqueryPredicate):
3419class All(SubqueryPredicate):
3420    pass
class Any(SubqueryPredicate):
3423class Any(SubqueryPredicate):
3424    pass
class Exists(SubqueryPredicate):
3427class Exists(SubqueryPredicate):
3428    pass
class Command(Expression):
3433class Command(Expression):
3434    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
3437class Transaction(Expression):
3438    arg_types = {"this": False, "modes": False}
class Commit(Expression):
3441class Commit(Expression):
3442    arg_types = {"chain": False}
class Rollback(Expression):
3445class Rollback(Expression):
3446    arg_types = {"savepoint": False}
class AlterTable(Expression):
3449class AlterTable(Expression):
3450    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
3453class AddConstraint(Expression):
3454    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
3457class DropPartition(Expression):
3458    arg_types = {"expressions": True, "exists": False}
class Binary(Condition):
3462class Binary(Condition):
3463    arg_types = {"this": True, "expression": True}
3464
3465    @property
3466    def left(self):
3467        return self.this
3468
3469    @property
3470    def right(self):
3471        return self.expression
class Add(Binary):
3474class Add(Binary):
3475    pass
class Connector(Binary):
3478class Connector(Binary):
3479    pass
class And(Connector):
3482class And(Connector):
3483    pass
class Or(Connector):
3486class Or(Connector):
3487    pass
class BitwiseAnd(Binary):
3490class BitwiseAnd(Binary):
3491    pass
class BitwiseLeftShift(Binary):
3494class BitwiseLeftShift(Binary):
3495    pass
class BitwiseOr(Binary):
3498class BitwiseOr(Binary):
3499    pass
class BitwiseRightShift(Binary):
3502class BitwiseRightShift(Binary):
3503    pass
class BitwiseXor(Binary):
3506class BitwiseXor(Binary):
3507    pass
class Div(Binary):
3510class Div(Binary):
3511    pass
class Overlaps(Binary):
3514class Overlaps(Binary):
3515    pass
class Dot(Binary):
3518class Dot(Binary):
3519    @property
3520    def name(self) -> str:
3521        return self.expression.name
3522
3523    @property
3524    def output_name(self) -> str:
3525        return self.name
3526
3527    @classmethod
3528    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3529        """Build a Dot object with a sequence of expressions."""
3530        if len(expressions) < 2:
3531            raise ValueError(f"Dot requires >= 2 expressions.")
3532
3533        a, b, *expressions = expressions
3534        dot = Dot(this=a, expression=b)
3535
3536        for expression in expressions:
3537            dot = Dot(this=dot, expression=expression)
3538
3539        return dot
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
''
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3527    @classmethod
3528    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3529        """Build a Dot object with a sequence of expressions."""
3530        if len(expressions) < 2:
3531            raise ValueError(f"Dot requires >= 2 expressions.")
3532
3533        a, b, *expressions = expressions
3534        dot = Dot(this=a, expression=b)
3535
3536        for expression in expressions:
3537            dot = Dot(this=dot, expression=expression)
3538
3539        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3542class DPipe(Binary):
3543    pass
class SafeDPipe(DPipe):
3546class SafeDPipe(DPipe):
3547    pass
class EQ(Binary, Predicate):
3550class EQ(Binary, Predicate):
3551    pass
class NullSafeEQ(Binary, Predicate):
3554class NullSafeEQ(Binary, Predicate):
3555    pass
class NullSafeNEQ(Binary, Predicate):
3558class NullSafeNEQ(Binary, Predicate):
3559    pass
class Distance(Binary):
3562class Distance(Binary):
3563    pass
class Escape(Binary):
3566class Escape(Binary):
3567    pass
class Glob(Binary, Predicate):
3570class Glob(Binary, Predicate):
3571    pass
class GT(Binary, Predicate):
3574class GT(Binary, Predicate):
3575    pass
class GTE(Binary, Predicate):
3578class GTE(Binary, Predicate):
3579    pass
class ILike(Binary, Predicate):
3582class ILike(Binary, Predicate):
3583    pass
class ILikeAny(Binary, Predicate):
3586class ILikeAny(Binary, Predicate):
3587    pass
class IntDiv(Binary):
3590class IntDiv(Binary):
3591    pass
class Is(Binary, Predicate):
3594class Is(Binary, Predicate):
3595    pass
class Kwarg(Binary):
3598class Kwarg(Binary):
3599    """Kwarg in special functions like func(kwarg => y)."""

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

class Like(Binary, Predicate):
3602class Like(Binary, Predicate):
3603    pass
class LikeAny(Binary, Predicate):
3606class LikeAny(Binary, Predicate):
3607    pass
class LT(Binary, Predicate):
3610class LT(Binary, Predicate):
3611    pass
class LTE(Binary, Predicate):
3614class LTE(Binary, Predicate):
3615    pass
class Mod(Binary):
3618class Mod(Binary):
3619    pass
class Mul(Binary):
3622class Mul(Binary):
3623    pass
class NEQ(Binary, Predicate):
3626class NEQ(Binary, Predicate):
3627    pass
class SimilarTo(Binary, Predicate):
3630class SimilarTo(Binary, Predicate):
3631    pass
class Slice(Binary):
3634class Slice(Binary):
3635    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3638class Sub(Binary):
3639    pass
class ArrayOverlaps(Binary):
3642class ArrayOverlaps(Binary):
3643    pass
class Unary(Condition):
3648class Unary(Condition):
3649    pass
class BitwiseNot(Unary):
3652class BitwiseNot(Unary):
3653    pass
class Not(Unary):
3656class Not(Unary):
3657    pass
class Paren(Unary):
3660class Paren(Unary):
3661    arg_types = {"this": True, "with": False}
3662
3663    @property
3664    def output_name(self) -> str:
3665        return self.this.name
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Neg(Unary):
3668class Neg(Unary):
3669    pass
class Alias(Expression):
3672class Alias(Expression):
3673    arg_types = {"this": True, "alias": False}
3674
3675    @property
3676    def output_name(self) -> str:
3677        return self.alias
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Aliases(Expression):
3680class Aliases(Expression):
3681    arg_types = {"this": True, "expressions": True}
3682
3683    @property
3684    def aliases(self):
3685        return self.expressions
class AtTimeZone(Expression):
3688class AtTimeZone(Expression):
3689    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3692class Between(Predicate):
3693    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3696class Bracket(Condition):
3697    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3700class Distinct(Expression):
3701    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3704class In(Predicate):
3705    arg_types = {
3706        "this": True,
3707        "expressions": False,
3708        "query": False,
3709        "unnest": False,
3710        "field": False,
3711        "is_global": False,
3712    }
class TimeUnit(Expression):
3715class TimeUnit(Expression):
3716    """Automatically converts unit arg into a var."""
3717
3718    arg_types = {"unit": False}
3719
3720    def __init__(self, **args):
3721        unit = args.get("unit")
3722        if isinstance(unit, (Column, Literal)):
3723            args["unit"] = Var(this=unit.name)
3724        elif isinstance(unit, Week):
3725            unit.set("this", Var(this=unit.this.name))
3726
3727        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3720    def __init__(self, **args):
3721        unit = args.get("unit")
3722        if isinstance(unit, (Column, Literal)):
3723            args["unit"] = Var(this=unit.name)
3724        elif isinstance(unit, Week):
3725            unit.set("this", Var(this=unit.this.name))
3726
3727        super().__init__(**args)
class Interval(TimeUnit):
3730class Interval(TimeUnit):
3731    arg_types = {"this": False, "unit": False}
3732
3733    @property
3734    def unit(self) -> t.Optional[Var]:
3735        return self.args.get("unit")
class IgnoreNulls(Expression):
3738class IgnoreNulls(Expression):
3739    pass
class RespectNulls(Expression):
3742class RespectNulls(Expression):
3743    pass
class Func(Condition):
3747class Func(Condition):
3748    """
3749    The base class for all function expressions.
3750
3751    Attributes:
3752        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3753            treated as a variable length argument and the argument's value will be stored as a list.
3754        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3755            for this function expression. These values are used to map this node to a name during parsing
3756            as well as to provide the function's name during SQL string generation. By default the SQL
3757            name is set to the expression's class name transformed to snake case.
3758    """
3759
3760    is_var_len_args = False
3761
3762    @classmethod
3763    def from_arg_list(cls, args):
3764        if cls.is_var_len_args:
3765            all_arg_keys = list(cls.arg_types)
3766            # If this function supports variable length argument treat the last argument as such.
3767            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3768            num_non_var = len(non_var_len_arg_keys)
3769
3770            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3771            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3772        else:
3773            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3774
3775        return cls(**args_dict)
3776
3777    @classmethod
3778    def sql_names(cls):
3779        if cls is Func:
3780            raise NotImplementedError(
3781                "SQL name is only supported by concrete function implementations"
3782            )
3783        if "_sql_names" not in cls.__dict__:
3784            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3785        return cls._sql_names
3786
3787    @classmethod
3788    def sql_name(cls):
3789        return cls.sql_names()[0]
3790
3791    @classmethod
3792    def default_parser_mappings(cls):
3793        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):
3762    @classmethod
3763    def from_arg_list(cls, args):
3764        if cls.is_var_len_args:
3765            all_arg_keys = list(cls.arg_types)
3766            # If this function supports variable length argument treat the last argument as such.
3767            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3768            num_non_var = len(non_var_len_arg_keys)
3769
3770            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3771            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3772        else:
3773            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3774
3775        return cls(**args_dict)
@classmethod
def sql_names(cls):
3777    @classmethod
3778    def sql_names(cls):
3779        if cls is Func:
3780            raise NotImplementedError(
3781                "SQL name is only supported by concrete function implementations"
3782            )
3783        if "_sql_names" not in cls.__dict__:
3784            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3785        return cls._sql_names
@classmethod
def sql_name(cls):
3787    @classmethod
3788    def sql_name(cls):
3789        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3791    @classmethod
3792    def default_parser_mappings(cls):
3793        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3796class AggFunc(Func):
3797    pass
class ParameterizedAgg(AggFunc):
3800class ParameterizedAgg(AggFunc):
3801    arg_types = {"this": True, "expressions": True, "params": True}
class Abs(Func):
3804class Abs(Func):
3805    pass
class Anonymous(Func):
3808class Anonymous(Func):
3809    arg_types = {"this": True, "expressions": False}
3810    is_var_len_args = True
class Hll(AggFunc):
3815class Hll(AggFunc):
3816    arg_types = {"this": True, "expressions": False}
3817    is_var_len_args = True
class ApproxDistinct(AggFunc):
3820class ApproxDistinct(AggFunc):
3821    arg_types = {"this": True, "accuracy": False}
3822    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
class Array(Func):
3825class Array(Func):
3826    arg_types = {"expressions": False}
3827    is_var_len_args = True
class ToChar(Func):
3831class ToChar(Func):
3832    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3835class GenerateSeries(Func):
3836    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3839class ArrayAgg(AggFunc):
3840    pass
class ArrayAll(Func):
3843class ArrayAll(Func):
3844    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3847class ArrayAny(Func):
3848    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3851class ArrayConcat(Func):
3852    arg_types = {"this": True, "expressions": False}
3853    is_var_len_args = True
class ArrayContains(Binary, Func):
3856class ArrayContains(Binary, Func):
3857    pass
class ArrayContained(Binary):
3860class ArrayContained(Binary):
3861    pass
class ArrayFilter(Func):
3864class ArrayFilter(Func):
3865    arg_types = {"this": True, "expression": True}
3866    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3869class ArrayJoin(Func):
3870    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3873class ArraySize(Func):
3874    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3877class ArraySort(Func):
3878    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3881class ArraySum(Func):
3882    pass
class ArrayUnionAgg(AggFunc):
3885class ArrayUnionAgg(AggFunc):
3886    pass
class Avg(AggFunc):
3889class Avg(AggFunc):
3890    pass
class AnyValue(AggFunc):
3893class AnyValue(AggFunc):
3894    pass
class Case(Func):
3897class Case(Func):
3898    arg_types = {"this": False, "ifs": True, "default": False}
3899
3900    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3901        instance = _maybe_copy(self, copy)
3902        instance.append(
3903            "ifs",
3904            If(
3905                this=maybe_parse(condition, copy=copy, **opts),
3906                true=maybe_parse(then, copy=copy, **opts),
3907            ),
3908        )
3909        return instance
3910
3911    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3912        instance = _maybe_copy(self, copy)
3913        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3914        return instance
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3900    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3901        instance = _maybe_copy(self, copy)
3902        instance.append(
3903            "ifs",
3904            If(
3905                this=maybe_parse(condition, copy=copy, **opts),
3906                true=maybe_parse(then, copy=copy, **opts),
3907            ),
3908        )
3909        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3911    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3912        instance = _maybe_copy(self, copy)
3913        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3914        return instance
class Cast(Func):
3917class Cast(Func):
3918    arg_types = {"this": True, "to": True}
3919
3920    @property
3921    def name(self) -> str:
3922        return self.this.name
3923
3924    @property
3925    def to(self) -> DataType:
3926        return self.args["to"]
3927
3928    @property
3929    def output_name(self) -> str:
3930        return self.name
3931
3932    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3933        return self.to.is_type(*dtypes)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3932    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3933        return self.to.is_type(*dtypes)
class CastToStrType(Func):
3936class CastToStrType(Func):
3937    arg_types = {"this": True, "expression": True}
class Collate(Binary):
3940class Collate(Binary):
3941    pass
class TryCast(Cast):
3944class TryCast(Cast):
3945    pass
class Ceil(Func):
3948class Ceil(Func):
3949    arg_types = {"this": True, "decimals": False}
3950    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3953class Coalesce(Func):
3954    arg_types = {"this": True, "expressions": False}
3955    is_var_len_args = True
3956    _sql_names = ["COALESCE", "IFNULL", "NVL"]
class Concat(Func):
3959class Concat(Func):
3960    arg_types = {"expressions": True}
3961    is_var_len_args = True
class SafeConcat(Concat):
3964class SafeConcat(Concat):
3965    pass
class ConcatWs(Concat):
3968class ConcatWs(Concat):
3969    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3972class Count(AggFunc):
3973    arg_types = {"this": False, "expressions": False}
3974    is_var_len_args = True
class CountIf(AggFunc):
3977class CountIf(AggFunc):
3978    pass
class CurrentDate(Func):
3981class CurrentDate(Func):
3982    arg_types = {"this": False}
class CurrentDatetime(Func):
3985class CurrentDatetime(Func):
3986    arg_types = {"this": False}
class CurrentTime(Func):
3989class CurrentTime(Func):
3990    arg_types = {"this": False}
class CurrentTimestamp(Func):
3993class CurrentTimestamp(Func):
3994    arg_types = {"this": False}
class CurrentUser(Func):
3997class CurrentUser(Func):
3998    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
4001class DateAdd(Func, TimeUnit):
4002    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
4005class DateSub(Func, TimeUnit):
4006    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
4009class DateDiff(Func, TimeUnit):
4010    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4011    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
4014class DateTrunc(Func):
4015    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
4018class DatetimeAdd(Func, TimeUnit):
4019    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
4022class DatetimeSub(Func, TimeUnit):
4023    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
4026class DatetimeDiff(Func, TimeUnit):
4027    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
4030class DatetimeTrunc(Func, TimeUnit):
4031    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
4034class DayOfWeek(Func):
4035    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
4038class DayOfMonth(Func):
4039    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
4042class DayOfYear(Func):
4043    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
4046class WeekOfYear(Func):
4047    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
4050class LastDateOfMonth(Func):
4051    pass
class Extract(Func):
4054class Extract(Func):
4055    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
4058class TimestampAdd(Func, TimeUnit):
4059    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
4062class TimestampSub(Func, TimeUnit):
4063    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
4066class TimestampDiff(Func, TimeUnit):
4067    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
4070class TimestampTrunc(Func, TimeUnit):
4071    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
4074class TimeAdd(Func, TimeUnit):
4075    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
4078class TimeSub(Func, TimeUnit):
4079    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
4082class TimeDiff(Func, TimeUnit):
4083    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
4086class TimeTrunc(Func, TimeUnit):
4087    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
4090class DateFromParts(Func):
4091    _sql_names = ["DATEFROMPARTS"]
4092    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
4095class DateStrToDate(Func):
4096    pass
class DateToDateStr(Func):
4099class DateToDateStr(Func):
4100    pass
class DateToDi(Func):
4103class DateToDi(Func):
4104    pass
class Date(Func):
4107class Date(Func):
4108    arg_types = {"expressions": True}
4109    is_var_len_args = True
class Day(Func):
4112class Day(Func):
4113    pass
class Decode(Func):
4116class Decode(Func):
4117    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
4120class DiToDate(Func):
4121    pass
class Encode(Func):
4124class Encode(Func):
4125    arg_types = {"this": True, "charset": True}
class Exp(Func):
4128class Exp(Func):
4129    pass
class Explode(Func):
4132class Explode(Func):
4133    pass
class Floor(Func):
4136class Floor(Func):
4137    arg_types = {"this": True, "decimals": False}
class FromBase64(Func):
4140class FromBase64(Func):
4141    pass
class ToBase64(Func):
4144class ToBase64(Func):
4145    pass
class Greatest(Func):
4148class Greatest(Func):
4149    arg_types = {"this": True, "expressions": False}
4150    is_var_len_args = True
class GroupConcat(Func):
4153class GroupConcat(Func):
4154    arg_types = {"this": True, "separator": False}
class Hex(Func):
4157class Hex(Func):
4158    pass
class If(Func):
4161class If(Func):
4162    arg_types = {"this": True, "true": True, "false": False}
class Initcap(Func):
4165class Initcap(Func):
4166    arg_types = {"this": True, "expression": False}
class JSONKeyValue(Expression):
4169class JSONKeyValue(Expression):
4170    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
4173class JSONObject(Func):
4174    arg_types = {
4175        "expressions": False,
4176        "null_handling": False,
4177        "unique_keys": False,
4178        "return_type": False,
4179        "format_json": False,
4180        "encoding": False,
4181    }
class OpenJSONColumnDef(Expression):
4184class OpenJSONColumnDef(Expression):
4185    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
class OpenJSON(Func):
4188class OpenJSON(Func):
4189    arg_types = {"this": True, "path": False, "expressions": False}
class JSONBContains(Binary):
4192class JSONBContains(Binary):
4193    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
4196class JSONExtract(Binary, Func):
4197    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
4200class JSONExtractScalar(JSONExtract):
4201    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
4204class JSONBExtract(JSONExtract):
4205    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
4208class JSONBExtractScalar(JSONExtract):
4209    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
4212class JSONFormat(Func):
4213    arg_types = {"this": False, "options": False}
4214    _sql_names = ["JSON_FORMAT"]
class Least(Func):
4217class Least(Func):
4218    arg_types = {"expressions": False}
4219    is_var_len_args = True
class Left(Func):
4222class Left(Func):
4223    arg_types = {"this": True, "expression": True}
class Length(Func):
4230class Length(Func):
4231    _sql_names = ["LENGTH", "LEN"]
class Levenshtein(Func):
4234class Levenshtein(Func):
4235    arg_types = {
4236        "this": True,
4237        "expression": False,
4238        "ins_cost": False,
4239        "del_cost": False,
4240        "sub_cost": False,
4241    }
class Ln(Func):
4244class Ln(Func):
4245    pass
class Log(Func):
4248class Log(Func):
4249    arg_types = {"this": True, "expression": False}
class Log2(Func):
4252class Log2(Func):
4253    pass
class Log10(Func):
4256class Log10(Func):
4257    pass
class LogicalOr(AggFunc):
4260class LogicalOr(AggFunc):
4261    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
4264class LogicalAnd(AggFunc):
4265    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
4268class Lower(Func):
4269    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
4272class Map(Func):
4273    arg_types = {"keys": False, "values": False}
class StarMap(Func):
4276class StarMap(Func):
4277    pass
class VarMap(Func):
4280class VarMap(Func):
4281    arg_types = {"keys": True, "values": True}
4282    is_var_len_args = True
4283
4284    @property
4285    def keys(self) -> t.List[Expression]:
4286        return self.args["keys"].expressions
4287
4288    @property
4289    def values(self) -> t.List[Expression]:
4290        return self.args["values"].expressions
class MatchAgainst(Func):
4294class MatchAgainst(Func):
4295    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
4298class Max(AggFunc):
4299    arg_types = {"this": True, "expressions": False}
4300    is_var_len_args = True
class MD5(Func):
4303class MD5(Func):
4304    _sql_names = ["MD5"]
class Min(AggFunc):
4307class Min(AggFunc):
4308    arg_types = {"this": True, "expressions": False}
4309    is_var_len_args = True
class Month(Func):
4312class Month(Func):
4313    pass
class Nvl2(Func):
4316class Nvl2(Func):
4317    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
4320class Posexplode(Func):
4321    pass
class Pow(Binary, Func):
4324class Pow(Binary, Func):
4325    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
4328class PercentileCont(AggFunc):
4329    arg_types = {"this": True, "expression": False}
class PercentileDisc(AggFunc):
4332class PercentileDisc(AggFunc):
4333    arg_types = {"this": True, "expression": False}
class Quantile(AggFunc):
4336class Quantile(AggFunc):
4337    arg_types = {"this": True, "quantile": True}
class ApproxQuantile(Quantile):
4340class ApproxQuantile(Quantile):
4341    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
4344class RangeN(Func):
4345    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
4348class ReadCSV(Func):
4349    _sql_names = ["READ_CSV"]
4350    is_var_len_args = True
4351    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
4354class Reduce(Func):
4355    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
4358class RegexpExtract(Func):
4359    arg_types = {
4360        "this": True,
4361        "expression": True,
4362        "position": False,
4363        "occurrence": False,
4364        "group": False,
4365    }
class RegexpLike(Func):
4368class RegexpLike(Func):
4369    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
4372class RegexpILike(Func):
4373    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
4378class RegexpSplit(Func):
4379    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
4382class Repeat(Func):
4383    arg_types = {"this": True, "times": True}
class Round(Func):
4386class Round(Func):
4387    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
4390class RowNumber(Func):
4391    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
4394class SafeDivide(Func):
4395    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
4398class SetAgg(AggFunc):
4399    pass
class SHA(Func):
4402class SHA(Func):
4403    _sql_names = ["SHA", "SHA1"]
class SHA2(Func):
4406class SHA2(Func):
4407    _sql_names = ["SHA2"]
4408    arg_types = {"this": True, "length": False}
class SortArray(Func):
4411class SortArray(Func):
4412    arg_types = {"this": True, "asc": False}
class Split(Func):
4415class Split(Func):
4416    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
4421class Substring(Func):
4422    arg_types = {"this": True, "start": False, "length": False}
class StandardHash(Func):
4425class StandardHash(Func):
4426    arg_types = {"this": True, "expression": False}
class StrPosition(Func):
4429class StrPosition(Func):
4430    arg_types = {
4431        "this": True,
4432        "substr": True,
4433        "position": False,
4434        "instance": False,
4435    }
class StrToDate(Func):
4438class StrToDate(Func):
4439    arg_types = {"this": True, "format": True}
class StrToTime(Func):
4442class StrToTime(Func):
4443    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
4448class StrToUnix(Func):
4449    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
4452class NumberToStr(Func):
4453    arg_types = {"this": True, "format": True}
class FromBase(Func):
4456class FromBase(Func):
4457    arg_types = {"this": True, "expression": True}
class Struct(Func):
4460class Struct(Func):
4461    arg_types = {"expressions": True}
4462    is_var_len_args = True
class StructExtract(Func):
4465class StructExtract(Func):
4466    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
4469class Sum(AggFunc):
4470    pass
class Sqrt(Func):
4473class Sqrt(Func):
4474    pass
class Stddev(AggFunc):
4477class Stddev(AggFunc):
4478    pass
class StddevPop(AggFunc):
4481class StddevPop(AggFunc):
4482    pass
class StddevSamp(AggFunc):
4485class StddevSamp(AggFunc):
4486    pass
class TimeToStr(Func):
4489class TimeToStr(Func):
4490    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
4493class TimeToTimeStr(Func):
4494    pass
class TimeToUnix(Func):
4497class TimeToUnix(Func):
4498    pass
class TimeStrToDate(Func):
4501class TimeStrToDate(Func):
4502    pass
class TimeStrToTime(Func):
4505class TimeStrToTime(Func):
4506    pass
class TimeStrToUnix(Func):
4509class TimeStrToUnix(Func):
4510    pass
class Trim(Func):
4513class Trim(Func):
4514    arg_types = {
4515        "this": True,
4516        "expression": False,
4517        "position": False,
4518        "collation": False,
4519    }
class TsOrDsAdd(Func, TimeUnit):
4522class TsOrDsAdd(Func, TimeUnit):
4523    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
4526class TsOrDsToDateStr(Func):
4527    pass
class TsOrDsToDate(Func):
4530class TsOrDsToDate(Func):
4531    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
4534class TsOrDiToDi(Func):
4535    pass
class Unhex(Func):
4538class Unhex(Func):
4539    pass
class UnixToStr(Func):
4542class UnixToStr(Func):
4543    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
4548class UnixToTime(Func):
4549    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4550
4551    SECONDS = Literal.string("seconds")
4552    MILLIS = Literal.string("millis")
4553    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
4556class UnixToTimeStr(Func):
4557    pass
class Upper(Func):
4560class Upper(Func):
4561    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
4564class Variance(AggFunc):
4565    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
4568class VariancePop(AggFunc):
4569    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
4572class Week(Func):
4573    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
4576class XMLTable(Func):
4577    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4580class Year(Func):
4581    pass
class Use(Expression):
4584class Use(Expression):
4585    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4588class Merge(Expression):
4589    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4592class When(Func):
4593    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
class NextValueFor(Func):
4598class NextValueFor(Func):
4599    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:
4636def maybe_parse(
4637    sql_or_expression: ExpOrStr,
4638    *,
4639    into: t.Optional[IntoType] = None,
4640    dialect: DialectType = None,
4641    prefix: t.Optional[str] = None,
4642    copy: bool = False,
4643    **opts,
4644) -> Expression:
4645    """Gracefully handle a possible string or expression.
4646
4647    Example:
4648        >>> maybe_parse("1")
4649        (LITERAL this: 1, is_string: False)
4650        >>> maybe_parse(to_identifier("x"))
4651        (IDENTIFIER this: x, quoted: False)
4652
4653    Args:
4654        sql_or_expression: the SQL code string or an expression
4655        into: the SQLGlot Expression to parse into
4656        dialect: the dialect used to parse the input expressions (in the case that an
4657            input expression is a SQL string).
4658        prefix: a string to prefix the sql with before it gets parsed
4659            (automatically includes a space)
4660        copy: whether or not to copy the expression.
4661        **opts: other options to use to parse the input expressions (again, in the case
4662            that an input expression is a SQL string).
4663
4664    Returns:
4665        Expression: the parsed or given expression.
4666    """
4667    if isinstance(sql_or_expression, Expression):
4668        if copy:
4669            return sql_or_expression.copy()
4670        return sql_or_expression
4671
4672    if sql_or_expression is None:
4673        raise ParseError(f"SQL cannot be None")
4674
4675    import sqlglot
4676
4677    sql = str(sql_or_expression)
4678    if prefix:
4679        sql = f"{prefix} {sql}"
4680
4681    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Union:
4865def union(
4866    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4867) -> Union:
4868    """
4869    Initializes a syntax tree from one UNION expression.
4870
4871    Example:
4872        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4873        'SELECT * FROM foo UNION SELECT * FROM bla'
4874
4875    Args:
4876        left: the SQL code string corresponding to the left-hand side.
4877            If an `Expression` instance is passed, it will be used as-is.
4878        right: the SQL code string corresponding to the right-hand side.
4879            If an `Expression` instance is passed, it will be used as-is.
4880        distinct: set the DISTINCT flag if and only if this is true.
4881        dialect: the dialect used to parse the input expression.
4882        opts: other options to use to parse the input expressions.
4883
4884    Returns:
4885        The new Union instance.
4886    """
4887    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4888    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4889
4890    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union instance.

def intersect( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Intersect:
4893def intersect(
4894    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4895) -> Intersect:
4896    """
4897    Initializes a syntax tree from one INTERSECT expression.
4898
4899    Example:
4900        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4901        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4902
4903    Args:
4904        left: the SQL code string corresponding to the left-hand side.
4905            If an `Expression` instance is passed, it will be used as-is.
4906        right: the SQL code string corresponding to the right-hand side.
4907            If an `Expression` instance is passed, it will be used as-is.
4908        distinct: set the DISTINCT flag if and only if this is true.
4909        dialect: the dialect used to parse the input expression.
4910        opts: other options to use to parse the input expressions.
4911
4912    Returns:
4913        The new Intersect instance.
4914    """
4915    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4916    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4917
4918    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect instance.

def except_( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Except:
4921def except_(
4922    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4923) -> Except:
4924    """
4925    Initializes a syntax tree from one EXCEPT expression.
4926
4927    Example:
4928        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4929        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4930
4931    Args:
4932        left: the SQL code string corresponding to the left-hand side.
4933            If an `Expression` instance is passed, it will be used as-is.
4934        right: the SQL code string corresponding to the right-hand side.
4935            If an `Expression` instance is passed, it will be used as-is.
4936        distinct: set the DISTINCT flag if and only if this is true.
4937        dialect: the dialect used to parse the input expression.
4938        opts: other options to use to parse the input expressions.
4939
4940    Returns:
4941        The new Except instance.
4942    """
4943    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4944    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4945
4946    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except instance.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4949def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4950    """
4951    Initializes a syntax tree from one or multiple SELECT expressions.
4952
4953    Example:
4954        >>> select("col1", "col2").from_("tbl").sql()
4955        'SELECT col1, col2 FROM tbl'
4956
4957    Args:
4958        *expressions: the SQL code string to parse as the expressions of a
4959            SELECT statement. If an Expression instance is passed, this is used as-is.
4960        dialect: the dialect used to parse the input expressions (in the case that an
4961            input expression is a SQL string).
4962        **opts: other options to use to parse the input expressions (again, in the case
4963            that an input expression is a SQL string).
4964
4965    Returns:
4966        Select: the syntax tree for the SELECT statement.
4967    """
4968    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:
4971def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4972    """
4973    Initializes a syntax tree from a FROM expression.
4974
4975    Example:
4976        >>> from_("tbl").select("col1", "col2").sql()
4977        'SELECT col1, col2 FROM tbl'
4978
4979    Args:
4980        *expression: the SQL code string to parse as the FROM expressions of a
4981            SELECT statement. If an Expression instance is passed, this is used as-is.
4982        dialect: the dialect used to parse the input expression (in the case that the
4983            input expression is a SQL string).
4984        **opts: other options to use to parse the input expressions (again, in the case
4985            that the input expression is a SQL string).
4986
4987    Returns:
4988        Select: the syntax tree for the SELECT statement.
4989    """
4990    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:
4993def update(
4994    table: str | Table,
4995    properties: dict,
4996    where: t.Optional[ExpOrStr] = None,
4997    from_: t.Optional[ExpOrStr] = None,
4998    dialect: DialectType = None,
4999    **opts,
5000) -> Update:
5001    """
5002    Creates an update statement.
5003
5004    Example:
5005        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5006        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5007
5008    Args:
5009        *properties: dictionary of properties to set which are
5010            auto converted to sql objects eg None -> NULL
5011        where: sql conditional parsed into a WHERE statement
5012        from_: sql statement parsed into a FROM statement
5013        dialect: the dialect used to parse the input expressions.
5014        **opts: other options to use to parse the input expressions.
5015
5016    Returns:
5017        Update: the syntax tree for the UPDATE statement.
5018    """
5019    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5020    update_expr.set(
5021        "expressions",
5022        [
5023            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5024            for k, v in properties.items()
5025        ],
5026    )
5027    if from_:
5028        update_expr.set(
5029            "from",
5030            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5031        )
5032    if isinstance(where, Condition):
5033        where = Where(this=where)
5034    if where:
5035        update_expr.set(
5036            "where",
5037            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5038        )
5039    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:
5042def delete(
5043    table: ExpOrStr,
5044    where: t.Optional[ExpOrStr] = None,
5045    returning: t.Optional[ExpOrStr] = None,
5046    dialect: DialectType = None,
5047    **opts,
5048) -> Delete:
5049    """
5050    Builds a delete statement.
5051
5052    Example:
5053        >>> delete("my_table", where="id > 1").sql()
5054        'DELETE FROM my_table WHERE id > 1'
5055
5056    Args:
5057        where: sql conditional parsed into a WHERE statement
5058        returning: sql conditional parsed into a RETURNING statement
5059        dialect: the dialect used to parse the input expressions.
5060        **opts: other options to use to parse the input expressions.
5061
5062    Returns:
5063        Delete: the syntax tree for the DELETE statement.
5064    """
5065    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5066    if where:
5067        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5068    if returning:
5069        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5070    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:
5073def insert(
5074    expression: ExpOrStr,
5075    into: ExpOrStr,
5076    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5077    overwrite: t.Optional[bool] = None,
5078    dialect: DialectType = None,
5079    copy: bool = True,
5080    **opts,
5081) -> Insert:
5082    """
5083    Builds an INSERT statement.
5084
5085    Example:
5086        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5087        'INSERT INTO tbl VALUES (1, 2, 3)'
5088
5089    Args:
5090        expression: the sql string or expression of the INSERT statement
5091        into: the tbl to insert data to.
5092        columns: optionally the table's column names.
5093        overwrite: whether to INSERT OVERWRITE or not.
5094        dialect: the dialect used to parse the input expressions.
5095        copy: whether or not to copy the expression.
5096        **opts: other options to use to parse the input expressions.
5097
5098    Returns:
5099        Insert: the syntax tree for the INSERT statement.
5100    """
5101    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5102    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5103
5104    if columns:
5105        this = _apply_list_builder(
5106            *columns,
5107            instance=Schema(this=this),
5108            arg="expressions",
5109            into=Identifier,
5110            copy=False,
5111            dialect=dialect,
5112            **opts,
5113        )
5114
5115    return Insert(this=this, expression=expr, overwrite=overwrite)

Builds an INSERT statement.

Example:
>>> insert("VALUES (1, 2, 3)", "tbl").sql()
'INSERT INTO tbl VALUES (1, 2, 3)'
Arguments:
  • expression: the sql string or expression of the INSERT statement
  • into: the tbl to insert data to.
  • columns: optionally the table's column names.
  • overwrite: whether to INSERT OVERWRITE or not.
  • dialect: the dialect used to parse the input expressions.
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Insert: the syntax tree for the INSERT statement.

def condition( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5118def condition(
5119    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5120) -> Condition:
5121    """
5122    Initialize a logical condition expression.
5123
5124    Example:
5125        >>> condition("x=1").sql()
5126        'x = 1'
5127
5128        This is helpful for composing larger logical syntax trees:
5129        >>> where = condition("x=1")
5130        >>> where = where.and_("y=1")
5131        >>> Select().from_("tbl").select("*").where(where).sql()
5132        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5133
5134    Args:
5135        *expression: the SQL code string to parse.
5136            If an Expression instance is passed, this is used as-is.
5137        dialect: the dialect used to parse the input expression (in the case that the
5138            input expression is a SQL string).
5139        copy: Whether or not to copy `expression` (only applies to expressions).
5140        **opts: other options to use to parse the input expressions (again, in the case
5141            that the input expression is a SQL string).
5142
5143    Returns:
5144        The new Condition instance
5145    """
5146    return maybe_parse(
5147        expression,
5148        into=Condition,
5149        dialect=dialect,
5150        copy=copy,
5151        **opts,
5152    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • copy: Whether or not to copy expression (only applies to expressions).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

The new Condition instance

def and_( *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5155def and_(
5156    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5157) -> Condition:
5158    """
5159    Combine multiple conditions with an AND logical operator.
5160
5161    Example:
5162        >>> and_("x=1", and_("y=1", "z=1")).sql()
5163        'x = 1 AND (y = 1 AND z = 1)'
5164
5165    Args:
5166        *expressions: the SQL code strings to parse.
5167            If an Expression instance is passed, this is used as-is.
5168        dialect: the dialect used to parse the input expression.
5169        copy: whether or not to copy `expressions` (only applies to Expressions).
5170        **opts: other options to use to parse the input expressions.
5171
5172    Returns:
5173        And: the new condition
5174    """
5175    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_( *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5178def or_(
5179    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5180) -> Condition:
5181    """
5182    Combine multiple conditions with an OR logical operator.
5183
5184    Example:
5185        >>> or_("x=1", or_("y=1", "z=1")).sql()
5186        'x = 1 OR (y = 1 OR z = 1)'
5187
5188    Args:
5189        *expressions: the SQL code strings to parse.
5190            If an Expression instance is passed, this is used as-is.
5191        dialect: the dialect used to parse the input expression.
5192        copy: whether or not to copy `expressions` (only applies to Expressions).
5193        **opts: other options to use to parse the input expressions.
5194
5195    Returns:
5196        Or: the new condition
5197    """
5198    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Not:
5201def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5202    """
5203    Wrap a condition with a NOT operator.
5204
5205    Example:
5206        >>> not_("this_suit='black'").sql()
5207        "NOT this_suit = 'black'"
5208
5209    Args:
5210        expression: the SQL code string to parse.
5211            If an Expression instance is passed, this is used as-is.
5212        dialect: the dialect used to parse the input expression.
5213        copy: whether to copy the expression or not.
5214        **opts: other options to use to parse the input expressions.
5215
5216    Returns:
5217        The new condition.
5218    """
5219    this = condition(
5220        expression,
5221        dialect=dialect,
5222        copy=copy,
5223        **opts,
5224    )
5225    return Not(this=_wrap(this, Connector))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the expression or not.
  • **opts: other options to use to parse the input expressions.
Returns:

The new condition.

def paren( expression: Union[str, sqlglot.expressions.Expression], copy: bool = True) -> sqlglot.expressions.Paren:
5228def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5229    """
5230    Wrap an expression in parentheses.
5231
5232    Example:
5233        >>> paren("5 + 3").sql()
5234        '(5 + 3)'
5235
5236    Args:
5237        expression: the SQL code string to parse.
5238            If an Expression instance is passed, this is used as-is.
5239        copy: whether to copy the expression or not.
5240
5241    Returns:
5242        The wrapped expression.
5243    """
5244    return Paren(this=maybe_parse(expression, copy=copy))

Wrap an expression in parentheses.

Example:
>>> paren("5 + 3").sql()
'(5 + 3)'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • copy: whether to copy the expression or not.
Returns:

The wrapped expression.

def to_identifier(name, quoted=None, copy=True):
5262def to_identifier(name, quoted=None, copy=True):
5263    """Builds an identifier.
5264
5265    Args:
5266        name: The name to turn into an identifier.
5267        quoted: Whether or not force quote the identifier.
5268        copy: Whether or not to copy a passed in Identefier node.
5269
5270    Returns:
5271        The identifier ast node.
5272    """
5273
5274    if name is None:
5275        return None
5276
5277    if isinstance(name, Identifier):
5278        identifier = _maybe_copy(name, copy)
5279    elif isinstance(name, str):
5280        identifier = Identifier(
5281            this=name,
5282            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5283        )
5284    else:
5285        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5286    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:
5292def to_interval(interval: str | Literal) -> Interval:
5293    """Builds an interval expression from a string like '1 day' or '5 months'."""
5294    if isinstance(interval, Literal):
5295        if not interval.is_string:
5296            raise ValueError("Invalid interval string.")
5297
5298        interval = interval.this
5299
5300    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5301
5302    if not interval_parts:
5303        raise ValueError("Invalid interval string.")
5304
5305    return Interval(
5306        this=Literal.string(interval_parts.group(1)),
5307        unit=Var(this=interval_parts.group(2)),
5308    )

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]:
5321def to_table(
5322    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5323) -> t.Optional[Table]:
5324    """
5325    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5326    If a table is passed in then that table is returned.
5327
5328    Args:
5329        sql_path: a `[catalog].[schema].[table]` string.
5330        dialect: the source dialect according to which the table name will be parsed.
5331        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5332
5333    Returns:
5334        A table expression.
5335    """
5336    if sql_path is None or isinstance(sql_path, Table):
5337        return sql_path
5338    if not isinstance(sql_path, str):
5339        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5340
5341    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5342    if table:
5343        for k, v in kwargs.items():
5344            table.set(k, v)
5345
5346    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:
5349def to_column(sql_path: str | Column, **kwargs) -> Column:
5350    """
5351    Create a column from a `[table].[column]` sql path. Schema is optional.
5352
5353    If a column is passed in then that column is returned.
5354
5355    Args:
5356        sql_path: `[table].[column]` string
5357    Returns:
5358        Table: A column expression
5359    """
5360    if sql_path is None or isinstance(sql_path, Column):
5361        return sql_path
5362    if not isinstance(sql_path, str):
5363        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5364    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):
5367def alias_(
5368    expression: ExpOrStr,
5369    alias: str | Identifier,
5370    table: bool | t.Sequence[str | Identifier] = False,
5371    quoted: t.Optional[bool] = None,
5372    dialect: DialectType = None,
5373    copy: bool = True,
5374    **opts,
5375):
5376    """Create an Alias expression.
5377
5378    Example:
5379        >>> alias_('foo', 'bar').sql()
5380        'foo AS bar'
5381
5382        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5383        '(SELECT 1, 2) AS bar(a, b)'
5384
5385    Args:
5386        expression: the SQL code strings to parse.
5387            If an Expression instance is passed, this is used as-is.
5388        alias: the alias name to use. If the name has
5389            special characters it is quoted.
5390        table: Whether or not to create a table alias, can also be a list of columns.
5391        quoted: whether or not to quote the alias
5392        dialect: the dialect used to parse the input expression.
5393        copy: Whether or not to copy the expression.
5394        **opts: other options to use to parse the input expressions.
5395
5396    Returns:
5397        Alias: the aliased expression
5398    """
5399    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5400    alias = to_identifier(alias, quoted=quoted)
5401
5402    if table:
5403        table_alias = TableAlias(this=alias)
5404        exp.set("alias", table_alias)
5405
5406        if not isinstance(table, bool):
5407            for column in table:
5408                table_alias.append("columns", to_identifier(column, quoted=quoted))
5409
5410        return exp
5411
5412    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5413    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5414    # for the complete Window expression.
5415    #
5416    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5417
5418    if "alias" in exp.arg_types and not isinstance(exp, Window):
5419        exp.set("alias", alias)
5420        return exp
5421    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • copy: Whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery( expression: Union[str, sqlglot.expressions.Expression], alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5424def subquery(
5425    expression: ExpOrStr,
5426    alias: t.Optional[Identifier | str] = None,
5427    dialect: DialectType = None,
5428    **opts,
5429) -> Select:
5430    """
5431    Build a subquery expression.
5432
5433    Example:
5434        >>> subquery('select x from tbl', 'bar').select('x').sql()
5435        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5436
5437    Args:
5438        expression: the SQL code strings to parse.
5439            If an Expression instance is passed, this is used as-is.
5440        alias: the alias name to use.
5441        dialect: the dialect used to parse the input expression.
5442        **opts: other options to use to parse the input expressions.
5443
5444    Returns:
5445        A new Select instance with the subquery expression included.
5446    """
5447
5448    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5449    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use.
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

A new Select instance with the subquery expression included.

def column( col: str | sqlglot.expressions.Identifier, table: Union[sqlglot.expressions.Identifier, str, NoneType] = None, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
5452def column(
5453    col: str | Identifier,
5454    table: t.Optional[str | Identifier] = None,
5455    db: t.Optional[str | Identifier] = None,
5456    catalog: t.Optional[str | Identifier] = None,
5457    quoted: t.Optional[bool] = None,
5458) -> Column:
5459    """
5460    Build a Column.
5461
5462    Args:
5463        col: Column name.
5464        table: Table name.
5465        db: Database name.
5466        catalog: Catalog name.
5467        quoted: Whether to force quotes on the column's identifiers.
5468
5469    Returns:
5470        The new Column instance.
5471    """
5472    return Column(
5473        this=to_identifier(col, quoted=quoted),
5474        table=to_identifier(table, quoted=quoted),
5475        db=to_identifier(db, quoted=quoted),
5476        catalog=to_identifier(catalog, quoted=quoted),
5477    )

Build a Column.

Arguments:
  • col: Column name.
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quoted: Whether to force quotes on the column's identifiers.
Returns:

The new Column instance.

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
5480def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5481    """Cast an expression to a data type.
5482
5483    Example:
5484        >>> cast('x + 1', 'int').sql()
5485        'CAST(x + 1 AS INT)'
5486
5487    Args:
5488        expression: The expression to cast.
5489        to: The datatype to cast to.
5490
5491    Returns:
5492        The new Cast instance.
5493    """
5494    expression = maybe_parse(expression, **opts)
5495    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

The new Cast instance.

def table_( table: sqlglot.expressions.Identifier | str, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None, alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None) -> sqlglot.expressions.Table:
5498def table_(
5499    table: Identifier | str,
5500    db: t.Optional[Identifier | str] = None,
5501    catalog: t.Optional[Identifier | str] = None,
5502    quoted: t.Optional[bool] = None,
5503    alias: t.Optional[Identifier | str] = None,
5504) -> Table:
5505    """Build a Table.
5506
5507    Args:
5508        table: Table name.
5509        db: Database name.
5510        catalog: Catalog name.
5511        quote: Whether to force quotes on the table's identifiers.
5512        alias: Table's alias.
5513
5514    Returns:
5515        The new Table instance.
5516    """
5517    return Table(
5518        this=to_identifier(table, quoted=quoted),
5519        db=to_identifier(db, quoted=quoted),
5520        catalog=to_identifier(catalog, quoted=quoted),
5521        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5522    )

Build a Table.

Arguments:
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quote: Whether to force quotes on the table's identifiers.
  • alias: Table's alias.
Returns:

The new Table instance.

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
5525def values(
5526    values: t.Iterable[t.Tuple[t.Any, ...]],
5527    alias: t.Optional[str] = None,
5528    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5529) -> Values:
5530    """Build VALUES statement.
5531
5532    Example:
5533        >>> values([(1, '2')]).sql()
5534        "VALUES (1, '2')"
5535
5536    Args:
5537        values: values statements that will be converted to SQL
5538        alias: optional alias
5539        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5540         If either are provided then an alias is also required.
5541
5542    Returns:
5543        Values: the Values expression object
5544    """
5545    if columns and not alias:
5546        raise ValueError("Alias is required when providing columns")
5547
5548    return Values(
5549        expressions=[convert(tup) for tup in values],
5550        alias=(
5551            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5552            if columns
5553            else (TableAlias(this=to_identifier(alias)) if alias else None)
5554        ),
5555    )

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:
5558def var(name: t.Optional[ExpOrStr]) -> Var:
5559    """Build a SQL variable.
5560
5561    Example:
5562        >>> repr(var('x'))
5563        '(VAR this: x)'
5564
5565        >>> repr(var(column('x', table='y')))
5566        '(VAR this: x)'
5567
5568    Args:
5569        name: The name of the var or an expression who's name will become the var.
5570
5571    Returns:
5572        The new variable node.
5573    """
5574    if not name:
5575        raise ValueError("Cannot convert empty name into var.")
5576
5577    if isinstance(name, Expression):
5578        name = name.name
5579    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:
5582def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5583    """Build ALTER TABLE... RENAME... expression
5584
5585    Args:
5586        old_name: The old name of the table
5587        new_name: The new name of the table
5588
5589    Returns:
5590        Alter table expression
5591    """
5592    old_table = to_table(old_name)
5593    new_table = to_table(new_name)
5594    return AlterTable(
5595        this=old_table,
5596        actions=[
5597            RenameTable(this=new_table),
5598        ],
5599    )

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:
5602def convert(value: t.Any, copy: bool = False) -> Expression:
5603    """Convert a python value into an expression object.
5604
5605    Raises an error if a conversion is not possible.
5606
5607    Args:
5608        value: A python object.
5609        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5610
5611    Returns:
5612        Expression: the equivalent expression object.
5613    """
5614    if isinstance(value, Expression):
5615        return _maybe_copy(value, copy)
5616    if isinstance(value, str):
5617        return Literal.string(value)
5618    if isinstance(value, bool):
5619        return Boolean(this=value)
5620    if value is None or (isinstance(value, float) and math.isnan(value)):
5621        return NULL
5622    if isinstance(value, numbers.Number):
5623        return Literal.number(value)
5624    if isinstance(value, datetime.datetime):
5625        datetime_literal = Literal.string(
5626            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5627        )
5628        return TimeStrToTime(this=datetime_literal)
5629    if isinstance(value, datetime.date):
5630        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5631        return DateStrToDate(this=date_literal)
5632    if isinstance(value, tuple):
5633        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5634    if isinstance(value, list):
5635        return Array(expressions=[convert(v, copy=copy) for v in value])
5636    if isinstance(value, dict):
5637        return Map(
5638            keys=[convert(k, copy=copy) for k in value],
5639            values=[convert(v, copy=copy) for v in value.values()],
5640        )
5641    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value: A python object.
  • copy: Whether or not to copy value (only applies to Expressions and collections).
Returns:

Expression: the equivalent expression object.

def replace_children( expression: sqlglot.expressions.Expression, fun: Callable, *args, **kwargs) -> None:
5644def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5645    """
5646    Replace children of an expression with the result of a lambda fun(child) -> exp.
5647    """
5648    for k, v in expression.args.items():
5649        is_list_arg = type(v) is list
5650
5651        child_nodes = v if is_list_arg else [v]
5652        new_child_nodes = []
5653
5654        for cn in child_nodes:
5655            if isinstance(cn, Expression):
5656                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5657                    new_child_nodes.append(child_node)
5658                    child_node.parent = expression
5659                    child_node.arg_key = k
5660            else:
5661                new_child_nodes.append(cn)
5662
5663        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names( expression: sqlglot.expressions.Expression, exclude: str = '') -> Set[str]:
5666def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5667    """
5668    Return all table names referenced through columns in an expression.
5669
5670    Example:
5671        >>> import sqlglot
5672        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5673        ['a', 'c']
5674
5675    Args:
5676        expression: expression to find table names.
5677        exclude: a table name to exclude
5678
5679    Returns:
5680        A list of unique names.
5681    """
5682    return {
5683        table
5684        for table in (column.table for column in expression.find_all(Column))
5685        if table and table != exclude
5686    }

Return all table names referenced through columns in an expression.

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

A list of unique names.

def table_name(table: sqlglot.expressions.Table | str) -> str:
5689def table_name(table: Table | str) -> str:
5690    """Get the full name of a table as a string.
5691
5692    Args:
5693        table: table expression node or string.
5694
5695    Examples:
5696        >>> from sqlglot import exp, parse_one
5697        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5698        'a.b.c'
5699
5700    Returns:
5701        The table name.
5702    """
5703
5704    table = maybe_parse(table, into=Table)
5705
5706    if not table:
5707        raise ValueError(f"Cannot parse {table}")
5708
5709    return ".".join(part for part in (table.text("catalog"), table.text("db"), table.name) if part)

Get the full name of a table as a string.

Arguments:
  • table: table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression: ~E, mapping: Dict[str, str], copy: bool = True) -> ~E:
5712def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5713    """Replace all tables in expression according to the mapping.
5714
5715    Args:
5716        expression: expression node to be transformed and replaced.
5717        mapping: mapping of table names.
5718        copy: whether or not to copy the expression.
5719
5720    Examples:
5721        >>> from sqlglot import exp, parse_one
5722        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5723        'SELECT * FROM c'
5724
5725    Returns:
5726        The mapped expression.
5727    """
5728
5729    def _replace_tables(node: Expression) -> Expression:
5730        if isinstance(node, Table):
5731            new_name = mapping.get(table_name(node))
5732            if new_name:
5733                return to_table(
5734                    new_name,
5735                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5736                )
5737        return node
5738
5739    return expression.transform(_replace_tables, copy=copy)

Replace all tables in expression according to the mapping.

Arguments:
  • expression: expression node to be transformed and replaced.
  • mapping: mapping of table names.
  • copy: whether or not to copy the expression.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders( expression: sqlglot.expressions.Expression, *args, **kwargs) -> sqlglot.expressions.Expression:
5742def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5743    """Replace placeholders in an expression.
5744
5745    Args:
5746        expression: expression node to be transformed and replaced.
5747        args: positional names that will substitute unnamed placeholders in the given order.
5748        kwargs: keyword arguments that will substitute named placeholders.
5749
5750    Examples:
5751        >>> from sqlglot import exp, parse_one
5752        >>> replace_placeholders(
5753        ...     parse_one("select * from :tbl where ? = ?"),
5754        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5755        ... ).sql()
5756        "SELECT * FROM foo WHERE str_col = 'b'"
5757
5758    Returns:
5759        The mapped expression.
5760    """
5761
5762    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5763        if isinstance(node, Placeholder):
5764            if node.name:
5765                new_name = kwargs.get(node.name)
5766                if new_name:
5767                    return convert(new_name)
5768            else:
5769                try:
5770                    return convert(next(args))
5771                except StopIteration:
5772                    pass
5773        return node
5774
5775    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression: expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy: bool = True) -> sqlglot.expressions.Expression:
5778def expand(
5779    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5780) -> Expression:
5781    """Transforms an expression by expanding all referenced sources into subqueries.
5782
5783    Examples:
5784        >>> from sqlglot import parse_one
5785        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5786        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5787
5788        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5789        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5790
5791    Args:
5792        expression: The expression to expand.
5793        sources: A dictionary of name to Subqueryables.
5794        copy: Whether or not to copy the expression during transformation. Defaults to True.
5795
5796    Returns:
5797        The transformed expression.
5798    """
5799
5800    def _expand(node: Expression):
5801        if isinstance(node, Table):
5802            name = table_name(node)
5803            source = sources.get(name)
5804            if source:
5805                subquery = source.subquery(node.alias or name)
5806                subquery.comments = [f"source: {name}"]
5807                return subquery.transform(_expand, copy=False)
5808        return node
5809
5810    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:
5813def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5814    """
5815    Returns a Func expression.
5816
5817    Examples:
5818        >>> func("abs", 5).sql()
5819        'ABS(5)'
5820
5821        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5822        'CAST(5 AS DOUBLE)'
5823
5824    Args:
5825        name: the name of the function to build.
5826        args: the args used to instantiate the function of interest.
5827        dialect: the source dialect.
5828        kwargs: the kwargs used to instantiate the function of interest.
5829
5830    Note:
5831        The arguments `args` and `kwargs` are mutually exclusive.
5832
5833    Returns:
5834        An instance of the function of interest, or an anonymous function, if `name` doesn't
5835        correspond to an existing `sqlglot.expressions.Func` class.
5836    """
5837    if args and kwargs:
5838        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5839
5840    from sqlglot.dialects.dialect import Dialect
5841
5842    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5843    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5844
5845    parser = Dialect.get_or_raise(dialect)().parser()
5846    from_args_list = parser.FUNCTIONS.get(name.upper())
5847
5848    if from_args_list:
5849        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5850    else:
5851        kwargs = kwargs or {"expressions": converted}
5852        function = Anonymous(this=name, **kwargs)
5853
5854    for error_message in function.error_messages(converted):
5855        raise ValueError(error_message)
5856
5857    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true() -> sqlglot.expressions.Boolean:
5860def true() -> Boolean:
5861    """
5862    Returns a true Boolean expression.
5863    """
5864    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5867def false() -> Boolean:
5868    """
5869    Returns a false Boolean expression.
5870    """
5871    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5874def null() -> Null:
5875    """
5876    Returns a Null expression.
5877    """
5878    return Null()

Returns a Null expression.