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

name: str
alias_or_name: str
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
''
meta: Dict[str, Any]
def copy(self):
249    def copy(self):
250        """
251        Returns a deep copy of the expression.
252        """
253        new = deepcopy(self)
254        new.parent = self.parent
255        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
257    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
258        if self.comments is None:
259            self.comments = []
260        if comments:
261            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
263    def append(self, arg_key: str, value: t.Any) -> None:
264        """
265        Appends value to arg_key if it's a list or sets it as a new list.
266
267        Args:
268            arg_key (str): name of the list expression arg
269            value (Any): value to append to the list
270        """
271        if not isinstance(self.args.get(arg_key), list):
272            self.args[arg_key] = []
273        self.args[arg_key].append(value)
274        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:
276    def set(self, arg_key: str, value: t.Any) -> None:
277        """
278        Sets `arg_key` to `value`.
279
280        Args:
281            arg_key (str): name of the expression arg.
282            value: value to set the arg to.
283        """
284        self.args[arg_key] = value
285        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]]:
306    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
307        """Yields the key and expression for all arguments, exploding list args."""
308        for k, vs in self.args.items():
309            if type(vs) is list:
310                for v in vs:
311                    if hasattr(v, "parent"):
312                        yield k, v
313            else:
314                if hasattr(vs, "parent"):
315                    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]:
317    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
318        """
319        Returns the first node in this tree which matches at least one of
320        the specified types.
321
322        Args:
323            expression_types: the expression type(s) to match.
324            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
325
326        Returns:
327            The node which matches the criteria or None if no such node was found.
328        """
329        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]:
331    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
332        """
333        Returns a generator object which visits all nodes in this tree and only
334        yields those that match at least one of the specified expression types.
335
336        Args:
337            expression_types: the expression type(s) to match.
338            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
339
340        Returns:
341            The generator object.
342        """
343        for expression, *_ in self.walk(bfs=bfs):
344            if isinstance(expression, expression_types):
345                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]:
347    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
348        """
349        Returns a nearest parent matching expression_types.
350
351        Args:
352            expression_types: the expression type(s) to match.
353
354        Returns:
355            The parent node.
356        """
357        ancestor = self.parent
358        while ancestor and not isinstance(ancestor, expression_types):
359            ancestor = ancestor.parent
360        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:
374    def root(self) -> Expression:
375        """
376        Returns the root expression of this tree.
377        """
378        expression = self
379        while expression.parent:
380            expression = expression.parent
381        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
383    def walk(self, bfs=True, prune=None):
384        """
385        Returns a generator object which visits all nodes in this tree.
386
387        Args:
388            bfs (bool): if set to True the BFS traversal order will be applied,
389                otherwise the DFS traversal will be used instead.
390            prune ((node, parent, arg_key) -> bool): callable that returns True if
391                the generator should stop traversing this branch of the tree.
392
393        Returns:
394            the generator object.
395        """
396        if bfs:
397            yield from self.bfs(prune=prune)
398        else:
399            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):
401    def dfs(self, parent=None, key=None, prune=None):
402        """
403        Returns a generator object which visits all nodes in this tree in
404        the DFS (Depth-first) order.
405
406        Returns:
407            The generator object.
408        """
409        parent = parent or self.parent
410        yield self, parent, key
411        if prune and prune(self, parent, key):
412            return
413
414        for k, v in self.iter_expressions():
415            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):
417    def bfs(self, prune=None):
418        """
419        Returns a generator object which visits all nodes in this tree in
420        the BFS (Breadth-first) order.
421
422        Returns:
423            The generator object.
424        """
425        queue = deque([(self, self.parent, None)])
426
427        while queue:
428            item, parent, key = queue.popleft()
429
430            yield item, parent, key
431            if prune and prune(item, parent, key):
432                continue
433
434            for k, v in item.iter_expressions():
435                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):
437    def unnest(self):
438        """
439        Returns the first non parenthesis child or self.
440        """
441        expression = self
442        while type(expression) is Paren:
443            expression = expression.this
444        return expression

Returns the first non parenthesis child or self.

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

Returns the inner expression if this is an Alias.

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

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
460    def flatten(self, unnest=True):
461        """
462        Returns a generator which yields child nodes who's parents are the same class.
463
464        A AND B AND C -> [A, B, C]
465        """
466        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
467            if not type(node) is self.__class__:
468                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:
476    def sql(self, dialect: DialectType = None, **opts) -> str:
477        """
478        Returns SQL string representation of this tree.
479
480        Args:
481            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
482            opts: other `sqlglot.generator.Generator` options.
483
484        Returns:
485            The SQL string.
486        """
487        from sqlglot.dialects import Dialect
488
489        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):
515    def transform(self, fun, *args, copy=True, **kwargs):
516        """
517        Recursively visits all tree nodes (excluding already transformed ones)
518        and applies the given transformation function to each node.
519
520        Args:
521            fun (function): a function which takes a node as an argument and returns a
522                new transformed node or the same node without modifications. If the function
523                returns None, then the corresponding node will be removed from the syntax tree.
524            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
525                modified in place.
526
527        Returns:
528            The transformed tree.
529        """
530        node = self.copy() if copy else self
531        new_node = fun(node, *args, **kwargs)
532
533        if new_node is None or not isinstance(new_node, Expression):
534            return new_node
535        if new_node is not node:
536            new_node.parent = node.parent
537            return new_node
538
539        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
540        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):
550    def replace(self, expression):
551        """
552        Swap out this expression with a new expression.
553
554        For example::
555
556            >>> tree = Select().select("x").from_("tbl")
557            >>> tree.find(Column).replace(Column(this="y"))
558            (COLUMN this: y)
559            >>> tree.sql()
560            'SELECT y FROM tbl'
561
562        Args:
563            expression: new node
564
565        Returns:
566            The new expression or expressions.
567        """
568        if not self.parent:
569            return expression
570
571        parent = self.parent
572        self.parent = None
573
574        replace_children(parent, lambda child: expression if child is self else child)
575        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:
577    def pop(self: E) -> E:
578        """
579        Remove this expression from its AST.
580
581        Returns:
582            The popped expression.
583        """
584        self.replace(None)
585        return self

Remove this expression from its AST.

Returns:

The popped expression.

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

Dump this Expression to a JSON-serializable dict.

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

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

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

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

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

key = 'unionable'
class UDTF(DerivedTable, Unionable):
957class UDTF(DerivedTable, Unionable):
958    @property
959    def selects(self):
960        alias = self.args.get("alias")
961        return alias.columns if alias else []
selects
key = 'udtf'
class Cache(Expression):
964class Cache(Expression):
965    arg_types = {
966        "with": False,
967        "this": True,
968        "lazy": False,
969        "options": False,
970        "expression": False,
971    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
974class Uncache(Expression):
975    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class Create(Expression):
978class Create(Expression):
979    arg_types = {
980        "with": False,
981        "this": True,
982        "kind": True,
983        "expression": False,
984        "exists": False,
985        "properties": False,
986        "replace": False,
987        "unique": False,
988        "indexes": False,
989        "no_schema_binding": False,
990        "begin": False,
991        "clone": False,
992    }
arg_types = {'with': False, 'this': True, 'kind': True, 'expression': False, 'exists': False, 'properties': False, 'replace': False, 'unique': False, 'indexes': False, 'no_schema_binding': False, 'begin': False, 'clone': False}
key = 'create'
class Clone(Expression):
 996class Clone(Expression):
 997    arg_types = {
 998        "this": True,
 999        "when": False,
1000        "kind": False,
1001        "expression": False,
1002    }
arg_types = {'this': True, 'when': False, 'kind': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1005class Describe(Expression):
1006    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'describe'
class Pragma(Expression):
1009class Pragma(Expression):
1010    pass
key = 'pragma'
class Set(Expression):
1013class Set(Expression):
1014    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1017class SetItem(Expression):
1018    arg_types = {
1019        "this": False,
1020        "expressions": False,
1021        "kind": False,
1022        "collate": False,  # MySQL SET NAMES statement
1023        "global": False,
1024    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1027class Show(Expression):
1028    arg_types = {
1029        "this": True,
1030        "target": False,
1031        "offset": False,
1032        "limit": False,
1033        "like": False,
1034        "where": False,
1035        "db": False,
1036        "full": False,
1037        "mutex": False,
1038        "query": False,
1039        "channel": False,
1040        "global": False,
1041        "log": False,
1042        "position": False,
1043        "types": False,
1044    }
arg_types = {'this': True, 'target': False, 'offset': False, 'limit': False, 'like': False, 'where': False, 'db': False, 'full': False, 'mutex': False, 'query': False, 'channel': False, 'global': False, 'log': False, 'position': False, 'types': False}
key = 'show'
class UserDefinedFunction(Expression):
1047class UserDefinedFunction(Expression):
1048    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1051class CharacterSet(Expression):
1052    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1055class With(Expression):
1056    arg_types = {"expressions": True, "recursive": False}
1057
1058    @property
1059    def recursive(self) -> bool:
1060        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1063class WithinGroup(Expression):
1064    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1067class CTE(DerivedTable):
1068    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1071class TableAlias(Expression):
1072    arg_types = {"this": False, "columns": False}
1073
1074    @property
1075    def columns(self):
1076        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1079class BitString(Condition):
1080    pass
key = 'bitstring'
class HexString(Condition):
1083class HexString(Condition):
1084    pass
key = 'hexstring'
class ByteString(Condition):
1087class ByteString(Condition):
1088    pass
key = 'bytestring'
class RawString(Condition):
1091class RawString(Condition):
1092    pass
key = 'rawstring'
class Column(Condition):
1095class Column(Condition):
1096    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1097
1098    @property
1099    def table(self) -> str:
1100        return self.text("table")
1101
1102    @property
1103    def db(self) -> str:
1104        return self.text("db")
1105
1106    @property
1107    def catalog(self) -> str:
1108        return self.text("catalog")
1109
1110    @property
1111    def output_name(self) -> str:
1112        return self.name
1113
1114    @property
1115    def parts(self) -> t.List[Identifier]:
1116        """Return the parts of a column in order catalog, db, table, name."""
1117        return [
1118            t.cast(Identifier, self.args[part])
1119            for part in ("catalog", "db", "table", "this")
1120            if self.args.get(part)
1121        ]
1122
1123    def to_dot(self) -> Dot:
1124        """Converts the column into a dot expression."""
1125        parts = self.parts
1126        parent = self.parent
1127
1128        while parent:
1129            if isinstance(parent, Dot):
1130                parts.append(parent.expression)
1131            parent = parent.parent
1132
1133        return Dot.build(parts)
arg_types = {'this': True, 'table': False, 'db': False, 'catalog': False, 'join_mark': False}
table: str
db: str
catalog: str
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:
1123    def to_dot(self) -> Dot:
1124        """Converts the column into a dot expression."""
1125        parts = self.parts
1126        parent = self.parent
1127
1128        while parent:
1129            if isinstance(parent, Dot):
1130                parts.append(parent.expression)
1131            parent = parent.parent
1132
1133        return Dot.build(parts)

Converts the column into a dot expression.

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

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

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

Delete: the modified expression.

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

Append to or set the WHERE expressions.

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

Delete: the modified expression.

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

Set the RETURNING expression. Not supported by all dialects.

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

Delete: the modified expression.

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

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.

key = 'insert'
class OnConflict(Expression):
1565class OnConflict(Expression):
1566    arg_types = {
1567        "duplicate": False,
1568        "expressions": False,
1569        "nothing": False,
1570        "key": False,
1571        "constraint": False,
1572    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1575class Returning(Expression):
1576    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'returning'
class Introducer(Expression):
1580class Introducer(Expression):
1581    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1585class National(Expression):
1586    pass
key = 'national'
class LoadData(Expression):
1589class LoadData(Expression):
1590    arg_types = {
1591        "this": True,
1592        "local": False,
1593        "overwrite": False,
1594        "inpath": True,
1595        "partition": False,
1596        "input_format": False,
1597        "serde": False,
1598    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1601class Partition(Expression):
1602    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1605class Fetch(Expression):
1606    arg_types = {
1607        "direction": False,
1608        "count": False,
1609        "percent": False,
1610        "with_ties": False,
1611    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1614class Group(Expression):
1615    arg_types = {
1616        "expressions": False,
1617        "grouping_sets": False,
1618        "cube": False,
1619        "rollup": False,
1620        "totals": False,
1621        "all": False,
1622    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1625class Lambda(Expression):
1626    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1629class Limit(Expression):
1630    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1633class Literal(Condition):
1634    arg_types = {"this": True, "is_string": True}
1635
1636    @property
1637    def hashable_args(self) -> t.Any:
1638        return (self.this, self.args.get("is_string"))
1639
1640    @classmethod
1641    def number(cls, number) -> Literal:
1642        return cls(this=str(number), is_string=False)
1643
1644    @classmethod
1645    def string(cls, string) -> Literal:
1646        return cls(this=str(string), is_string=True)
1647
1648    @property
1649    def output_name(self) -> str:
1650        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1640    @classmethod
1641    def number(cls, number) -> Literal:
1642        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1644    @classmethod
1645    def string(cls, string) -> Literal:
1646        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
''
key = 'literal'
class Join(Expression):
1653class Join(Expression):
1654    arg_types = {
1655        "this": True,
1656        "on": False,
1657        "side": False,
1658        "kind": False,
1659        "using": False,
1660        "method": False,
1661        "global": False,
1662        "hint": False,
1663    }
1664
1665    @property
1666    def method(self) -> str:
1667        return self.text("method").upper()
1668
1669    @property
1670    def kind(self) -> str:
1671        return self.text("kind").upper()
1672
1673    @property
1674    def side(self) -> str:
1675        return self.text("side").upper()
1676
1677    @property
1678    def hint(self) -> str:
1679        return self.text("hint").upper()
1680
1681    @property
1682    def alias_or_name(self) -> str:
1683        return self.this.alias_or_name
1684
1685    def on(
1686        self,
1687        *expressions: t.Optional[ExpOrStr],
1688        append: bool = True,
1689        dialect: DialectType = None,
1690        copy: bool = True,
1691        **opts,
1692    ) -> Join:
1693        """
1694        Append to or set the ON expressions.
1695
1696        Example:
1697            >>> import sqlglot
1698            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1699            'JOIN x ON y = 1'
1700
1701        Args:
1702            *expressions: the SQL code strings to parse.
1703                If an `Expression` instance is passed, it will be used as-is.
1704                Multiple expressions are combined with an AND operator.
1705            append: if `True`, AND the new expressions to any existing expression.
1706                Otherwise, this resets the expression.
1707            dialect: the dialect used to parse the input expressions.
1708            copy: if `False`, modify this expression instance in-place.
1709            opts: other options to use to parse the input expressions.
1710
1711        Returns:
1712            The modified Join expression.
1713        """
1714        join = _apply_conjunction_builder(
1715            *expressions,
1716            instance=self,
1717            arg="on",
1718            append=append,
1719            dialect=dialect,
1720            copy=copy,
1721            **opts,
1722        )
1723
1724        if join.kind == "CROSS":
1725            join.set("kind", None)
1726
1727        return join
1728
1729    def using(
1730        self,
1731        *expressions: t.Optional[ExpOrStr],
1732        append: bool = True,
1733        dialect: DialectType = None,
1734        copy: bool = True,
1735        **opts,
1736    ) -> Join:
1737        """
1738        Append to or set the USING expressions.
1739
1740        Example:
1741            >>> import sqlglot
1742            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1743            'JOIN x USING (foo, bla)'
1744
1745        Args:
1746            *expressions: the SQL code strings to parse.
1747                If an `Expression` instance is passed, it will be used as-is.
1748            append: if `True`, concatenate the new expressions to the existing "using" list.
1749                Otherwise, this resets the expression.
1750            dialect: the dialect used to parse the input expressions.
1751            copy: if `False`, modify this expression instance in-place.
1752            opts: other options to use to parse the input expressions.
1753
1754        Returns:
1755            The modified Join expression.
1756        """
1757        join = _apply_list_builder(
1758            *expressions,
1759            instance=self,
1760            arg="using",
1761            append=append,
1762            dialect=dialect,
1763            copy=copy,
1764            **opts,
1765        )
1766
1767        if join.kind == "CROSS":
1768            join.set("kind", None)
1769
1770        return join
arg_types = {'this': True, 'on': False, 'side': False, 'kind': False, 'using': False, 'method': False, 'global': False, 'hint': False}
method: str
kind: str
side: str
hint: str
alias_or_name: str
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:
1685    def on(
1686        self,
1687        *expressions: t.Optional[ExpOrStr],
1688        append: bool = True,
1689        dialect: DialectType = None,
1690        copy: bool = True,
1691        **opts,
1692    ) -> Join:
1693        """
1694        Append to or set the ON expressions.
1695
1696        Example:
1697            >>> import sqlglot
1698            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1699            'JOIN x ON y = 1'
1700
1701        Args:
1702            *expressions: the SQL code strings to parse.
1703                If an `Expression` instance is passed, it will be used as-is.
1704                Multiple expressions are combined with an AND operator.
1705            append: if `True`, AND the new expressions to any existing expression.
1706                Otherwise, this resets the expression.
1707            dialect: the dialect used to parse the input expressions.
1708            copy: if `False`, modify this expression instance in-place.
1709            opts: other options to use to parse the input expressions.
1710
1711        Returns:
1712            The modified Join expression.
1713        """
1714        join = _apply_conjunction_builder(
1715            *expressions,
1716            instance=self,
1717            arg="on",
1718            append=append,
1719            dialect=dialect,
1720            copy=copy,
1721            **opts,
1722        )
1723
1724        if join.kind == "CROSS":
1725            join.set("kind", None)
1726
1727        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:
1729    def using(
1730        self,
1731        *expressions: t.Optional[ExpOrStr],
1732        append: bool = True,
1733        dialect: DialectType = None,
1734        copy: bool = True,
1735        **opts,
1736    ) -> Join:
1737        """
1738        Append to or set the USING expressions.
1739
1740        Example:
1741            >>> import sqlglot
1742            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1743            'JOIN x USING (foo, bla)'
1744
1745        Args:
1746            *expressions: the SQL code strings to parse.
1747                If an `Expression` instance is passed, it will be used as-is.
1748            append: if `True`, concatenate the new expressions to the existing "using" list.
1749                Otherwise, this resets the expression.
1750            dialect: the dialect used to parse the input expressions.
1751            copy: if `False`, modify this expression instance in-place.
1752            opts: other options to use to parse the input expressions.
1753
1754        Returns:
1755            The modified Join expression.
1756        """
1757        join = _apply_list_builder(
1758            *expressions,
1759            instance=self,
1760            arg="using",
1761            append=append,
1762            dialect=dialect,
1763            copy=copy,
1764            **opts,
1765        )
1766
1767        if join.kind == "CROSS":
1768            join.set("kind", None)
1769
1770        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.

key = 'join'
class Lateral(UDTF):
1773class Lateral(UDTF):
1774    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
arg_types = {'this': True, 'view': False, 'outer': False, 'alias': False}
key = 'lateral'
class MatchRecognize(Expression):
1777class MatchRecognize(Expression):
1778    arg_types = {
1779        "partition_by": False,
1780        "order": False,
1781        "measures": False,
1782        "rows": False,
1783        "after": False,
1784        "pattern": False,
1785        "define": False,
1786        "alias": False,
1787    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1792class Final(Expression):
1793    pass
key = 'final'
class Offset(Expression):
1796class Offset(Expression):
1797    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1800class Order(Expression):
1801    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1806class Cluster(Order):
1807    pass
key = 'cluster'
class Distribute(Order):
1810class Distribute(Order):
1811    pass
key = 'distribute'
class Sort(Order):
1814class Sort(Order):
1815    pass
key = 'sort'
class Ordered(Expression):
1818class Ordered(Expression):
1819    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1822class Property(Expression):
1823    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1826class AlgorithmProperty(Property):
1827    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1830class AutoIncrementProperty(Property):
1831    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1834class BlockCompressionProperty(Property):
1835    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
arg_types = {'autotemp': False, 'always': False, 'default': True, 'manual': True, 'never': True}
key = 'blockcompressionproperty'
class CharacterSetProperty(Property):
1838class CharacterSetProperty(Property):
1839    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1842class ChecksumProperty(Property):
1843    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1846class CollateProperty(Property):
1847    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1850class CopyGrantsProperty(Property):
1851    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1854class DataBlocksizeProperty(Property):
1855    arg_types = {
1856        "size": False,
1857        "units": False,
1858        "minimum": False,
1859        "maximum": False,
1860        "default": False,
1861    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1864class DefinerProperty(Property):
1865    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1868class DistKeyProperty(Property):
1869    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1872class DistStyleProperty(Property):
1873    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1876class EngineProperty(Property):
1877    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1880class ToTableProperty(Property):
1881    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1884class ExecuteAsProperty(Property):
1885    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1888class ExternalProperty(Property):
1889    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1892class FallbackProperty(Property):
1893    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1896class FileFormatProperty(Property):
1897    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1900class FreespaceProperty(Property):
1901    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1904class InputOutputFormat(Expression):
1905    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1908class IsolatedLoadingProperty(Property):
1909    arg_types = {
1910        "no": True,
1911        "concurrent": True,
1912        "for_all": True,
1913        "for_insert": True,
1914        "for_none": True,
1915    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1918class JournalProperty(Property):
1919    arg_types = {
1920        "no": False,
1921        "dual": False,
1922        "before": False,
1923        "local": False,
1924        "after": False,
1925    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1928class LanguageProperty(Property):
1929    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1933class ClusteredByProperty(Property):
1934    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1937class DictProperty(Property):
1938    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1941class DictSubProperty(Property):
1942    pass
key = 'dictsubproperty'
class DictRange(Property):
1945class DictRange(Property):
1946    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1951class OnCluster(Property):
1952    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1955class LikeProperty(Property):
1956    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1959class LocationProperty(Property):
1960    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
1963class LockingProperty(Property):
1964    arg_types = {
1965        "this": False,
1966        "kind": True,
1967        "for_or_in": True,
1968        "lock_type": True,
1969        "override": False,
1970    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
1973class LogProperty(Property):
1974    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
1977class MaterializedProperty(Property):
1978    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
1981class MergeBlockRatioProperty(Property):
1982    arg_types = {"this": False, "no": False, "default": False, "percent": False}
arg_types = {'this': False, 'no': False, 'default': False, 'percent': False}
key = 'mergeblockratioproperty'
class NoPrimaryIndexProperty(Property):
1985class NoPrimaryIndexProperty(Property):
1986    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
1989class OnCommitProperty(Property):
1990    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
1993class PartitionedByProperty(Property):
1994    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
1997class ReturnsProperty(Property):
1998    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2001class RowFormatProperty(Property):
2002    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2005class RowFormatDelimitedProperty(Property):
2006    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2007    arg_types = {
2008        "fields": False,
2009        "escaped": False,
2010        "collection_items": False,
2011        "map_keys": False,
2012        "lines": False,
2013        "null": False,
2014        "serde": False,
2015    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2018class RowFormatSerdeProperty(Property):
2019    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatserdeproperty'
class SchemaCommentProperty(Property):
2022class SchemaCommentProperty(Property):
2023    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2026class SerdeProperties(Property):
2027    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2030class SetProperty(Property):
2031    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2034class SettingsProperty(Property):
2035    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2038class SortKeyProperty(Property):
2039    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2042class SqlSecurityProperty(Property):
2043    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2046class StabilityProperty(Property):
2047    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2050class TemporaryProperty(Property):
2051    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2054class TransientProperty(Property):
2055    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2058class VolatileProperty(Property):
2059    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2062class WithDataProperty(Property):
2063    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2066class WithJournalTableProperty(Property):
2067    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2070class Properties(Expression):
2071    arg_types = {"expressions": True}
2072
2073    NAME_TO_PROPERTY = {
2074        "ALGORITHM": AlgorithmProperty,
2075        "AUTO_INCREMENT": AutoIncrementProperty,
2076        "CHARACTER SET": CharacterSetProperty,
2077        "CLUSTERED_BY": ClusteredByProperty,
2078        "COLLATE": CollateProperty,
2079        "COMMENT": SchemaCommentProperty,
2080        "DEFINER": DefinerProperty,
2081        "DISTKEY": DistKeyProperty,
2082        "DISTSTYLE": DistStyleProperty,
2083        "ENGINE": EngineProperty,
2084        "EXECUTE AS": ExecuteAsProperty,
2085        "FORMAT": FileFormatProperty,
2086        "LANGUAGE": LanguageProperty,
2087        "LOCATION": LocationProperty,
2088        "PARTITIONED_BY": PartitionedByProperty,
2089        "RETURNS": ReturnsProperty,
2090        "ROW_FORMAT": RowFormatProperty,
2091        "SORTKEY": SortKeyProperty,
2092    }
2093
2094    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2095
2096    # CREATE property locations
2097    # Form: schema specified
2098    #   create [POST_CREATE]
2099    #     table a [POST_NAME]
2100    #     (b int) [POST_SCHEMA]
2101    #     with ([POST_WITH])
2102    #     index (b) [POST_INDEX]
2103    #
2104    # Form: alias selection
2105    #   create [POST_CREATE]
2106    #     table a [POST_NAME]
2107    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2108    #     index (c) [POST_INDEX]
2109    class Location(AutoName):
2110        POST_CREATE = auto()
2111        POST_NAME = auto()
2112        POST_SCHEMA = auto()
2113        POST_WITH = auto()
2114        POST_ALIAS = auto()
2115        POST_EXPRESSION = auto()
2116        POST_INDEX = auto()
2117        UNSUPPORTED = auto()
2118
2119    @classmethod
2120    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2121        expressions = []
2122        for key, value in properties_dict.items():
2123            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2124            if property_cls:
2125                expressions.append(property_cls(this=convert(value)))
2126            else:
2127                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2128
2129        return cls(expressions=expressions)
arg_types = {'expressions': True}
NAME_TO_PROPERTY = {'ALGORITHM': <class 'sqlglot.expressions.AlgorithmProperty'>, 'AUTO_INCREMENT': <class 'sqlglot.expressions.AutoIncrementProperty'>, 'CHARACTER SET': <class 'sqlglot.expressions.CharacterSetProperty'>, 'CLUSTERED_BY': <class 'sqlglot.expressions.ClusteredByProperty'>, 'COLLATE': <class 'sqlglot.expressions.CollateProperty'>, 'COMMENT': <class 'sqlglot.expressions.SchemaCommentProperty'>, 'DEFINER': <class 'sqlglot.expressions.DefinerProperty'>, 'DISTKEY': <class 'sqlglot.expressions.DistKeyProperty'>, 'DISTSTYLE': <class 'sqlglot.expressions.DistStyleProperty'>, 'ENGINE': <class 'sqlglot.expressions.EngineProperty'>, 'EXECUTE AS': <class 'sqlglot.expressions.ExecuteAsProperty'>, 'FORMAT': <class 'sqlglot.expressions.FileFormatProperty'>, 'LANGUAGE': <class 'sqlglot.expressions.LanguageProperty'>, 'LOCATION': <class 'sqlglot.expressions.LocationProperty'>, 'PARTITIONED_BY': <class 'sqlglot.expressions.PartitionedByProperty'>, 'RETURNS': <class 'sqlglot.expressions.ReturnsProperty'>, 'ROW_FORMAT': <class 'sqlglot.expressions.RowFormatProperty'>, 'SORTKEY': <class 'sqlglot.expressions.SortKeyProperty'>}
PROPERTY_TO_NAME = {<class 'sqlglot.expressions.AlgorithmProperty'>: 'ALGORITHM', <class 'sqlglot.expressions.AutoIncrementProperty'>: 'AUTO_INCREMENT', <class 'sqlglot.expressions.CharacterSetProperty'>: 'CHARACTER SET', <class 'sqlglot.expressions.ClusteredByProperty'>: 'CLUSTERED_BY', <class 'sqlglot.expressions.CollateProperty'>: 'COLLATE', <class 'sqlglot.expressions.SchemaCommentProperty'>: 'COMMENT', <class 'sqlglot.expressions.DefinerProperty'>: 'DEFINER', <class 'sqlglot.expressions.DistKeyProperty'>: 'DISTKEY', <class 'sqlglot.expressions.DistStyleProperty'>: 'DISTSTYLE', <class 'sqlglot.expressions.EngineProperty'>: 'ENGINE', <class 'sqlglot.expressions.ExecuteAsProperty'>: 'EXECUTE AS', <class 'sqlglot.expressions.FileFormatProperty'>: 'FORMAT', <class 'sqlglot.expressions.LanguageProperty'>: 'LANGUAGE', <class 'sqlglot.expressions.LocationProperty'>: 'LOCATION', <class 'sqlglot.expressions.PartitionedByProperty'>: 'PARTITIONED_BY', <class 'sqlglot.expressions.ReturnsProperty'>: 'RETURNS', <class 'sqlglot.expressions.RowFormatProperty'>: 'ROW_FORMAT', <class 'sqlglot.expressions.SortKeyProperty'>: 'SORTKEY'}
@classmethod
def from_dict(cls, properties_dict: Dict) -> sqlglot.expressions.Properties:
2119    @classmethod
2120    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2121        expressions = []
2122        for key, value in properties_dict.items():
2123            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2124            if property_cls:
2125                expressions.append(property_cls(this=convert(value)))
2126            else:
2127                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2128
2129        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2109    class Location(AutoName):
2110        POST_CREATE = auto()
2111        POST_NAME = auto()
2112        POST_SCHEMA = auto()
2113        POST_WITH = auto()
2114        POST_ALIAS = auto()
2115        POST_EXPRESSION = auto()
2116        POST_INDEX = auto()
2117        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):
2132class Qualify(Expression):
2133    pass
key = 'qualify'
class Return(Expression):
2137class Return(Expression):
2138    pass
key = 'return'
class Reference(Expression):
2141class Reference(Expression):
2142    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2145class Tuple(Expression):
2146    arg_types = {"expressions": False}
2147
2148    def isin(
2149        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2150    ) -> In:
2151        return In(
2152            this=_maybe_copy(self, copy),
2153            expressions=[convert(e, copy=copy) for e in expressions],
2154            query=maybe_parse(query, copy=copy, **opts) if query else None,
2155        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2148    def isin(
2149        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2150    ) -> In:
2151        return In(
2152            this=_maybe_copy(self, copy),
2153            expressions=[convert(e, copy=copy) for e in expressions],
2154            query=maybe_parse(query, copy=copy, **opts) if query else None,
2155        )
key = 'tuple'
class Subqueryable(Unionable):
2158class Subqueryable(Unionable):
2159    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2160        """
2161        Convert this expression to an aliased expression that can be used as a Subquery.
2162
2163        Example:
2164            >>> subquery = Select().select("x").from_("tbl").subquery()
2165            >>> Select().select("x").from_(subquery).sql()
2166            'SELECT x FROM (SELECT x FROM tbl)'
2167
2168        Args:
2169            alias (str | Identifier): an optional alias for the subquery
2170            copy (bool): if `False`, modify this expression instance in-place.
2171
2172        Returns:
2173            Alias: the subquery
2174        """
2175        instance = _maybe_copy(self, copy)
2176        if not isinstance(alias, Expression):
2177            alias = TableAlias(this=to_identifier(alias)) if alias else None
2178
2179        return Subquery(this=instance, alias=alias)
2180
2181    def limit(
2182        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2183    ) -> Select:
2184        raise NotImplementedError
2185
2186    @property
2187    def ctes(self):
2188        with_ = self.args.get("with")
2189        if not with_:
2190            return []
2191        return with_.expressions
2192
2193    @property
2194    def selects(self):
2195        raise NotImplementedError("Subqueryable objects must implement `selects`")
2196
2197    @property
2198    def named_selects(self):
2199        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2200
2201    def with_(
2202        self,
2203        alias: ExpOrStr,
2204        as_: ExpOrStr,
2205        recursive: t.Optional[bool] = None,
2206        append: bool = True,
2207        dialect: DialectType = None,
2208        copy: bool = True,
2209        **opts,
2210    ) -> Subqueryable:
2211        """
2212        Append to or set the common table expressions.
2213
2214        Example:
2215            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2216            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2217
2218        Args:
2219            alias: the SQL code string to parse as the table name.
2220                If an `Expression` instance is passed, this is used as-is.
2221            as_: the SQL code string to parse as the table expression.
2222                If an `Expression` instance is passed, it will be used as-is.
2223            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2224            append: if `True`, add to any existing expressions.
2225                Otherwise, this resets the expressions.
2226            dialect: the dialect used to parse the input expression.
2227            copy: if `False`, modify this expression instance in-place.
2228            opts: other options to use to parse the input expressions.
2229
2230        Returns:
2231            The modified expression.
2232        """
2233        return _apply_cte_builder(
2234            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2235        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2159    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2160        """
2161        Convert this expression to an aliased expression that can be used as a Subquery.
2162
2163        Example:
2164            >>> subquery = Select().select("x").from_("tbl").subquery()
2165            >>> Select().select("x").from_(subquery).sql()
2166            'SELECT x FROM (SELECT x FROM tbl)'
2167
2168        Args:
2169            alias (str | Identifier): an optional alias for the subquery
2170            copy (bool): if `False`, modify this expression instance in-place.
2171
2172        Returns:
2173            Alias: the subquery
2174        """
2175        instance = _maybe_copy(self, copy)
2176        if not isinstance(alias, Expression):
2177            alias = TableAlias(this=to_identifier(alias)) if alias else None
2178
2179        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:
2181    def limit(
2182        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2183    ) -> Select:
2184        raise NotImplementedError
ctes
selects
named_selects
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:
2201    def with_(
2202        self,
2203        alias: ExpOrStr,
2204        as_: ExpOrStr,
2205        recursive: t.Optional[bool] = None,
2206        append: bool = True,
2207        dialect: DialectType = None,
2208        copy: bool = True,
2209        **opts,
2210    ) -> Subqueryable:
2211        """
2212        Append to or set the common table expressions.
2213
2214        Example:
2215            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2216            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2217
2218        Args:
2219            alias: the SQL code string to parse as the table name.
2220                If an `Expression` instance is passed, this is used as-is.
2221            as_: the SQL code string to parse as the table expression.
2222                If an `Expression` instance is passed, it will be used as-is.
2223            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2224            append: if `True`, add to any existing expressions.
2225                Otherwise, this resets the expressions.
2226            dialect: the dialect used to parse the input expression.
2227            copy: if `False`, modify this expression instance in-place.
2228            opts: other options to use to parse the input expressions.
2229
2230        Returns:
2231            The modified expression.
2232        """
2233        return _apply_cte_builder(
2234            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2235        )

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.

key = 'subqueryable'
QUERY_MODIFIERS = {'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
class WithTableHint(Expression):
2262class WithTableHint(Expression):
2263    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2267class IndexTableHint(Expression):
2268    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2271class Table(Expression):
2272    arg_types = {
2273        "this": True,
2274        "alias": False,
2275        "db": False,
2276        "catalog": False,
2277        "laterals": False,
2278        "joins": False,
2279        "pivots": False,
2280        "hints": False,
2281        "system_time": False,
2282    }
2283
2284    @property
2285    def name(self) -> str:
2286        if isinstance(self.this, Func):
2287            return ""
2288        return self.this.name
2289
2290    @property
2291    def db(self) -> str:
2292        return self.text("db")
2293
2294    @property
2295    def catalog(self) -> str:
2296        return self.text("catalog")
2297
2298    @property
2299    def parts(self) -> t.List[Identifier]:
2300        """Return the parts of a table in order catalog, db, table."""
2301        return [
2302            t.cast(Identifier, self.args[part])
2303            for part in ("catalog", "db", "this")
2304            if self.args.get(part)
2305        ]
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False}
name: str
db: str
catalog: str

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

key = 'table'
class SystemTime(Expression):
2309class SystemTime(Expression):
2310    arg_types = {
2311        "this": False,
2312        "expression": False,
2313        "kind": True,
2314    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2317class Union(Subqueryable):
2318    arg_types = {
2319        "with": False,
2320        "this": True,
2321        "expression": True,
2322        "distinct": False,
2323        **QUERY_MODIFIERS,
2324    }
2325
2326    def limit(
2327        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2328    ) -> Select:
2329        """
2330        Set the LIMIT expression.
2331
2332        Example:
2333            >>> select("1").union(select("1")).limit(1).sql()
2334            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2335
2336        Args:
2337            expression: the SQL code string to parse.
2338                This can also be an integer.
2339                If a `Limit` instance is passed, this is used as-is.
2340                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2341            dialect: the dialect used to parse the input expression.
2342            copy: if `False`, modify this expression instance in-place.
2343            opts: other options to use to parse the input expressions.
2344
2345        Returns:
2346            The limited subqueryable.
2347        """
2348        return (
2349            select("*")
2350            .from_(self.subquery(alias="_l_0", copy=copy))
2351            .limit(expression, dialect=dialect, copy=False, **opts)
2352        )
2353
2354    def select(
2355        self,
2356        *expressions: t.Optional[ExpOrStr],
2357        append: bool = True,
2358        dialect: DialectType = None,
2359        copy: bool = True,
2360        **opts,
2361    ) -> Union:
2362        """Append to or set the SELECT of the union recursively.
2363
2364        Example:
2365            >>> from sqlglot import parse_one
2366            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2367            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2368
2369        Args:
2370            *expressions: the SQL code strings to parse.
2371                If an `Expression` instance is passed, it will be used as-is.
2372            append: if `True`, add to any existing expressions.
2373                Otherwise, this resets the expressions.
2374            dialect: the dialect used to parse the input expressions.
2375            copy: if `False`, modify this expression instance in-place.
2376            opts: other options to use to parse the input expressions.
2377
2378        Returns:
2379            Union: the modified expression.
2380        """
2381        this = self.copy() if copy else self
2382        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2383        this.expression.unnest().select(
2384            *expressions, append=append, dialect=dialect, copy=False, **opts
2385        )
2386        return this
2387
2388    @property
2389    def named_selects(self):
2390        return self.this.unnest().named_selects
2391
2392    @property
2393    def is_star(self) -> bool:
2394        return self.this.is_star or self.expression.is_star
2395
2396    @property
2397    def selects(self):
2398        return self.this.unnest().selects
2399
2400    @property
2401    def left(self):
2402        return self.this
2403
2404    @property
2405    def right(self):
2406        return self.expression
arg_types = {'with': False, 'this': True, 'expression': True, 'distinct': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
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:
2326    def limit(
2327        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2328    ) -> Select:
2329        """
2330        Set the LIMIT expression.
2331
2332        Example:
2333            >>> select("1").union(select("1")).limit(1).sql()
2334            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2335
2336        Args:
2337            expression: the SQL code string to parse.
2338                This can also be an integer.
2339                If a `Limit` instance is passed, this is used as-is.
2340                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2341            dialect: the dialect used to parse the input expression.
2342            copy: if `False`, modify this expression instance in-place.
2343            opts: other options to use to parse the input expressions.
2344
2345        Returns:
2346            The limited subqueryable.
2347        """
2348        return (
2349            select("*")
2350            .from_(self.subquery(alias="_l_0", copy=copy))
2351            .limit(expression, dialect=dialect, copy=False, **opts)
2352        )

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:
2354    def select(
2355        self,
2356        *expressions: t.Optional[ExpOrStr],
2357        append: bool = True,
2358        dialect: DialectType = None,
2359        copy: bool = True,
2360        **opts,
2361    ) -> Union:
2362        """Append to or set the SELECT of the union recursively.
2363
2364        Example:
2365            >>> from sqlglot import parse_one
2366            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2367            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2368
2369        Args:
2370            *expressions: the SQL code strings to parse.
2371                If an `Expression` instance is passed, it will be used as-is.
2372            append: if `True`, add to any existing expressions.
2373                Otherwise, this resets the expressions.
2374            dialect: the dialect used to parse the input expressions.
2375            copy: if `False`, modify this expression instance in-place.
2376            opts: other options to use to parse the input expressions.
2377
2378        Returns:
2379            Union: the modified expression.
2380        """
2381        this = self.copy() if copy else self
2382        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2383        this.expression.unnest().select(
2384            *expressions, append=append, dialect=dialect, copy=False, **opts
2385        )
2386        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.

named_selects
is_star: bool

Checks whether an expression is a star.

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

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:
2504    def group_by(
2505        self,
2506        *expressions: t.Optional[ExpOrStr],
2507        append: bool = True,
2508        dialect: DialectType = None,
2509        copy: bool = True,
2510        **opts,
2511    ) -> Select:
2512        """
2513        Set the GROUP BY expression.
2514
2515        Example:
2516            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2517            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2518
2519        Args:
2520            *expressions: the SQL code strings to parse.
2521                If a `Group` instance is passed, this is used as-is.
2522                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2523                If nothing is passed in then a group by is not applied to the expression
2524            append: if `True`, add to any existing expressions.
2525                Otherwise, this flattens all the `Group` expression into a single expression.
2526            dialect: the dialect used to parse the input expression.
2527            copy: if `False`, modify this expression instance in-place.
2528            opts: other options to use to parse the input expressions.
2529
2530        Returns:
2531            The modified Select expression.
2532        """
2533        if not expressions:
2534            return self if not copy else self.copy()
2535
2536        return _apply_child_list_builder(
2537            *expressions,
2538            instance=self,
2539            arg="group",
2540            append=append,
2541            copy=copy,
2542            prefix="GROUP BY",
2543            into=Group,
2544            dialect=dialect,
2545            **opts,
2546        )

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

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

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:
2628    def cluster_by(
2629        self,
2630        *expressions: t.Optional[ExpOrStr],
2631        append: bool = True,
2632        dialect: DialectType = None,
2633        copy: bool = True,
2634        **opts,
2635    ) -> Select:
2636        """
2637        Set the CLUSTER BY expression.
2638
2639        Example:
2640            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2641            'SELECT x FROM tbl CLUSTER BY x DESC'
2642
2643        Args:
2644            *expressions: the SQL code strings to parse.
2645                If a `Group` instance is passed, this is used as-is.
2646                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2647            append: if `True`, add to any existing expressions.
2648                Otherwise, this flattens all the `Order` expression into a single expression.
2649            dialect: the dialect used to parse the input expression.
2650            copy: if `False`, modify this expression instance in-place.
2651            opts: other options to use to parse the input expressions.
2652
2653        Returns:
2654            The modified Select expression.
2655        """
2656        return _apply_child_list_builder(
2657            *expressions,
2658            instance=self,
2659            arg="cluster",
2660            append=append,
2661            copy=copy,
2662            prefix="CLUSTER BY",
2663            into=Cluster,
2664            dialect=dialect,
2665            **opts,
2666        )

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:
2668    def limit(
2669        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2670    ) -> Select:
2671        """
2672        Set the LIMIT expression.
2673
2674        Example:
2675            >>> Select().from_("tbl").select("x").limit(10).sql()
2676            'SELECT x FROM tbl LIMIT 10'
2677
2678        Args:
2679            expression: the SQL code string to parse.
2680                This can also be an integer.
2681                If a `Limit` instance is passed, this is used as-is.
2682                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2683            dialect: the dialect used to parse the input expression.
2684            copy: if `False`, modify this expression instance in-place.
2685            opts: other options to use to parse the input expressions.
2686
2687        Returns:
2688            Select: the modified expression.
2689        """
2690        return _apply_builder(
2691            expression=expression,
2692            instance=self,
2693            arg="limit",
2694            into=Limit,
2695            prefix="LIMIT",
2696            dialect=dialect,
2697            copy=copy,
2698            **opts,
2699        )

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:
2701    def offset(
2702        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2703    ) -> Select:
2704        """
2705        Set the OFFSET expression.
2706
2707        Example:
2708            >>> Select().from_("tbl").select("x").offset(10).sql()
2709            'SELECT x FROM tbl OFFSET 10'
2710
2711        Args:
2712            expression: the SQL code string to parse.
2713                This can also be an integer.
2714                If a `Offset` instance is passed, this is used as-is.
2715                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2716            dialect: the dialect used to parse the input expression.
2717            copy: if `False`, modify this expression instance in-place.
2718            opts: other options to use to parse the input expressions.
2719
2720        Returns:
2721            The modified Select expression.
2722        """
2723        return _apply_builder(
2724            expression=expression,
2725            instance=self,
2726            arg="offset",
2727            into=Offset,
2728            prefix="OFFSET",
2729            dialect=dialect,
2730            copy=copy,
2731            **opts,
2732        )

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:
2734    def select(
2735        self,
2736        *expressions: t.Optional[ExpOrStr],
2737        append: bool = True,
2738        dialect: DialectType = None,
2739        copy: bool = True,
2740        **opts,
2741    ) -> Select:
2742        """
2743        Append to or set the SELECT expressions.
2744
2745        Example:
2746            >>> Select().select("x", "y").sql()
2747            'SELECT x, y'
2748
2749        Args:
2750            *expressions: the SQL code strings to parse.
2751                If an `Expression` instance is passed, it will be used as-is.
2752            append: if `True`, add to any existing expressions.
2753                Otherwise, this resets the expressions.
2754            dialect: the dialect used to parse the input expressions.
2755            copy: if `False`, modify this expression instance in-place.
2756            opts: other options to use to parse the input expressions.
2757
2758        Returns:
2759            The modified Select expression.
2760        """
2761        return _apply_list_builder(
2762            *expressions,
2763            instance=self,
2764            arg="expressions",
2765            append=append,
2766            dialect=dialect,
2767            copy=copy,
2768            **opts,
2769        )

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:
2771    def lateral(
2772        self,
2773        *expressions: t.Optional[ExpOrStr],
2774        append: bool = True,
2775        dialect: DialectType = None,
2776        copy: bool = True,
2777        **opts,
2778    ) -> Select:
2779        """
2780        Append to or set the LATERAL expressions.
2781
2782        Example:
2783            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2784            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2785
2786        Args:
2787            *expressions: the SQL code strings to parse.
2788                If an `Expression` instance is passed, it will be used as-is.
2789            append: if `True`, add to any existing expressions.
2790                Otherwise, this resets the expressions.
2791            dialect: the dialect used to parse the input expressions.
2792            copy: if `False`, modify this expression instance in-place.
2793            opts: other options to use to parse the input expressions.
2794
2795        Returns:
2796            The modified Select expression.
2797        """
2798        return _apply_list_builder(
2799            *expressions,
2800            instance=self,
2801            arg="laterals",
2802            append=append,
2803            into=Lateral,
2804            prefix="LATERAL VIEW",
2805            dialect=dialect,
2806            copy=copy,
2807            **opts,
2808        )

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:
2810    def join(
2811        self,
2812        expression: ExpOrStr,
2813        on: t.Optional[ExpOrStr] = None,
2814        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2815        append: bool = True,
2816        join_type: t.Optional[str] = None,
2817        join_alias: t.Optional[Identifier | str] = None,
2818        dialect: DialectType = None,
2819        copy: bool = True,
2820        **opts,
2821    ) -> Select:
2822        """
2823        Append to or set the JOIN expressions.
2824
2825        Example:
2826            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2827            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2828
2829            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2830            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2831
2832            Use `join_type` to change the type of join:
2833
2834            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2835            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2836
2837        Args:
2838            expression: the SQL code string to parse.
2839                If an `Expression` instance is passed, it will be used as-is.
2840            on: optionally specify the join "on" criteria as a SQL string.
2841                If an `Expression` instance is passed, it will be used as-is.
2842            using: optionally specify the join "using" criteria as a SQL string.
2843                If an `Expression` instance is passed, it will be used as-is.
2844            append: if `True`, add to any existing expressions.
2845                Otherwise, this resets the expressions.
2846            join_type: if set, alter the parsed join type.
2847            join_alias: an optional alias for the joined source.
2848            dialect: the dialect used to parse the input expressions.
2849            copy: if `False`, modify this expression instance in-place.
2850            opts: other options to use to parse the input expressions.
2851
2852        Returns:
2853            Select: the modified expression.
2854        """
2855        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2856
2857        try:
2858            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2859        except ParseError:
2860            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2861
2862        join = expression if isinstance(expression, Join) else Join(this=expression)
2863
2864        if isinstance(join.this, Select):
2865            join.this.replace(join.this.subquery())
2866
2867        if join_type:
2868            method: t.Optional[Token]
2869            side: t.Optional[Token]
2870            kind: t.Optional[Token]
2871
2872            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2873
2874            if method:
2875                join.set("method", method.text)
2876            if side:
2877                join.set("side", side.text)
2878            if kind:
2879                join.set("kind", kind.text)
2880
2881        if on:
2882            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2883            join.set("on", on)
2884
2885        if using:
2886            join = _apply_list_builder(
2887                *ensure_list(using),
2888                instance=join,
2889                arg="using",
2890                append=append,
2891                copy=copy,
2892                **opts,
2893            )
2894
2895        if join_alias:
2896            join.set("this", alias_(join.this, join_alias, table=True))
2897
2898        return _apply_list_builder(
2899            join,
2900            instance=self,
2901            arg="joins",
2902            append=append,
2903            copy=copy,
2904            **opts,
2905        )

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:
2907    def where(
2908        self,
2909        *expressions: t.Optional[ExpOrStr],
2910        append: bool = True,
2911        dialect: DialectType = None,
2912        copy: bool = True,
2913        **opts,
2914    ) -> Select:
2915        """
2916        Append to or set the WHERE expressions.
2917
2918        Example:
2919            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2920            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2921
2922        Args:
2923            *expressions: the SQL code strings to parse.
2924                If an `Expression` instance is passed, it will be used as-is.
2925                Multiple expressions are combined with an AND operator.
2926            append: if `True`, AND the new expressions to any existing expression.
2927                Otherwise, this resets the expression.
2928            dialect: the dialect used to parse the input expressions.
2929            copy: if `False`, modify this expression instance in-place.
2930            opts: other options to use to parse the input expressions.
2931
2932        Returns:
2933            Select: the modified expression.
2934        """
2935        return _apply_conjunction_builder(
2936            *expressions,
2937            instance=self,
2938            arg="where",
2939            append=append,
2940            into=Where,
2941            dialect=dialect,
2942            copy=copy,
2943            **opts,
2944        )

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:
2946    def having(
2947        self,
2948        *expressions: t.Optional[ExpOrStr],
2949        append: bool = True,
2950        dialect: DialectType = None,
2951        copy: bool = True,
2952        **opts,
2953    ) -> Select:
2954        """
2955        Append to or set the HAVING expressions.
2956
2957        Example:
2958            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2959            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2960
2961        Args:
2962            *expressions: the SQL code strings to parse.
2963                If an `Expression` instance is passed, it will be used as-is.
2964                Multiple expressions are combined with an AND operator.
2965            append: if `True`, AND the new expressions to any existing expression.
2966                Otherwise, this resets the expression.
2967            dialect: the dialect used to parse the input expressions.
2968            copy: if `False`, modify this expression instance in-place.
2969            opts: other options to use to parse the input expressions.
2970
2971        Returns:
2972            The modified Select expression.
2973        """
2974        return _apply_conjunction_builder(
2975            *expressions,
2976            instance=self,
2977            arg="having",
2978            append=append,
2979            into=Having,
2980            dialect=dialect,
2981            copy=copy,
2982            **opts,
2983        )

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:
2985    def window(
2986        self,
2987        *expressions: t.Optional[ExpOrStr],
2988        append: bool = True,
2989        dialect: DialectType = None,
2990        copy: bool = True,
2991        **opts,
2992    ) -> Select:
2993        return _apply_list_builder(
2994            *expressions,
2995            instance=self,
2996            arg="windows",
2997            append=append,
2998            into=Window,
2999            dialect=dialect,
3000            copy=copy,
3001            **opts,
3002        )
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:
3004    def qualify(
3005        self,
3006        *expressions: t.Optional[ExpOrStr],
3007        append: bool = True,
3008        dialect: DialectType = None,
3009        copy: bool = True,
3010        **opts,
3011    ) -> Select:
3012        return _apply_conjunction_builder(
3013            *expressions,
3014            instance=self,
3015            arg="qualify",
3016            append=append,
3017            into=Qualify,
3018            dialect=dialect,
3019            copy=copy,
3020            **opts,
3021        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3023    def distinct(
3024        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3025    ) -> Select:
3026        """
3027        Set the OFFSET expression.
3028
3029        Example:
3030            >>> Select().from_("tbl").select("x").distinct().sql()
3031            'SELECT DISTINCT x FROM tbl'
3032
3033        Args:
3034            ons: the expressions to distinct on
3035            distinct: whether the Select should be distinct
3036            copy: if `False`, modify this expression instance in-place.
3037
3038        Returns:
3039            Select: the modified expression.
3040        """
3041        instance = _maybe_copy(self, copy)
3042        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3043        instance.set("distinct", Distinct(on=on) if distinct else None)
3044        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:
3046    def ctas(
3047        self,
3048        table: ExpOrStr,
3049        properties: t.Optional[t.Dict] = None,
3050        dialect: DialectType = None,
3051        copy: bool = True,
3052        **opts,
3053    ) -> Create:
3054        """
3055        Convert this expression to a CREATE TABLE AS statement.
3056
3057        Example:
3058            >>> Select().select("*").from_("tbl").ctas("x").sql()
3059            'CREATE TABLE x AS SELECT * FROM tbl'
3060
3061        Args:
3062            table: the SQL code string to parse as the table name.
3063                If another `Expression` instance is passed, it will be used as-is.
3064            properties: an optional mapping of table properties
3065            dialect: the dialect used to parse the input table.
3066            copy: if `False`, modify this expression instance in-place.
3067            opts: other options to use to parse the input table.
3068
3069        Returns:
3070            The new Create expression.
3071        """
3072        instance = _maybe_copy(self, copy)
3073        table_expression = maybe_parse(
3074            table,
3075            into=Table,
3076            dialect=dialect,
3077            **opts,
3078        )
3079        properties_expression = None
3080        if properties:
3081            properties_expression = Properties.from_dict(properties)
3082
3083        return Create(
3084            this=table_expression,
3085            kind="table",
3086            expression=instance,
3087            properties=properties_expression,
3088        )

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:
3090    def lock(self, update: bool = True, copy: bool = True) -> Select:
3091        """
3092        Set the locking read mode for this expression.
3093
3094        Examples:
3095            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3096            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3097
3098            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3099            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3100
3101        Args:
3102            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3103            copy: if `False`, modify this expression instance in-place.
3104
3105        Returns:
3106            The modified expression.
3107        """
3108        inst = _maybe_copy(self, copy)
3109        inst.set("locks", [Lock(update=update)])
3110
3111        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:
3113    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3114        """
3115        Set hints for this expression.
3116
3117        Examples:
3118            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3119            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3120
3121        Args:
3122            hints: The SQL code strings to parse as the hints.
3123                If an `Expression` instance is passed, it will be used as-is.
3124            dialect: The dialect used to parse the hints.
3125            copy: If `False`, modify this expression instance in-place.
3126
3127        Returns:
3128            The modified expression.
3129        """
3130        inst = _maybe_copy(self, copy)
3131        inst.set(
3132            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3133        )
3134
3135        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.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

key = 'select'
class Subquery(DerivedTable, Unionable):
3150class Subquery(DerivedTable, Unionable):
3151    arg_types = {
3152        "this": True,
3153        "alias": False,
3154        "with": False,
3155        **QUERY_MODIFIERS,
3156    }
3157
3158    def unnest(self):
3159        """
3160        Returns the first non subquery.
3161        """
3162        expression = self
3163        while isinstance(expression, Subquery):
3164            expression = expression.this
3165        return expression
3166
3167    @property
3168    def is_star(self) -> bool:
3169        return self.this.is_star
3170
3171    @property
3172    def output_name(self) -> str:
3173        return self.alias
arg_types = {'this': True, 'alias': False, 'with': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def unnest(self):
3158    def unnest(self):
3159        """
3160        Returns the first non subquery.
3161        """
3162        expression = self
3163        while isinstance(expression, Subquery):
3164            expression = expression.this
3165        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
''
key = 'subquery'
class TableSample(Expression):
3176class TableSample(Expression):
3177    arg_types = {
3178        "this": False,
3179        "method": False,
3180        "bucket_numerator": False,
3181        "bucket_denominator": False,
3182        "bucket_field": False,
3183        "percent": False,
3184        "rows": False,
3185        "size": False,
3186        "seed": False,
3187        "kind": False,
3188    }
arg_types = {'this': False, 'method': False, 'bucket_numerator': False, 'bucket_denominator': False, 'bucket_field': False, 'percent': False, 'rows': False, 'size': False, 'seed': False, 'kind': False}
key = 'tablesample'
class Tag(Expression):
3191class Tag(Expression):
3192    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3193
3194    arg_types = {
3195        "this": False,
3196        "prefix": False,
3197        "postfix": False,
3198    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3203class Pivot(Expression):
3204    arg_types = {
3205        "this": False,
3206        "alias": False,
3207        "expressions": True,
3208        "field": False,
3209        "unpivot": False,
3210        "using": False,
3211        "group": False,
3212        "columns": False,
3213    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3216class Window(Expression):
3217    arg_types = {
3218        "this": True,
3219        "partition_by": False,
3220        "order": False,
3221        "spec": False,
3222        "alias": False,
3223        "over": False,
3224        "first": False,
3225    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3228class WindowSpec(Expression):
3229    arg_types = {
3230        "kind": False,
3231        "start": False,
3232        "start_side": False,
3233        "end": False,
3234        "end_side": False,
3235    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3238class Where(Expression):
3239    pass
key = 'where'
class Star(Expression):
3242class Star(Expression):
3243    arg_types = {"except": False, "replace": False}
3244
3245    @property
3246    def name(self) -> str:
3247        return "*"
3248
3249    @property
3250    def output_name(self) -> str:
3251        return self.name
arg_types = {'except': False, 'replace': False}
name: str
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
''
key = 'star'
class Parameter(Condition):
3254class Parameter(Condition):
3255    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3258class SessionParameter(Condition):
3259    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3262class Placeholder(Condition):
3263    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3266class Null(Condition):
3267    arg_types: t.Dict[str, t.Any] = {}
3268
3269    @property
3270    def name(self) -> str:
3271        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3274class Boolean(Condition):
3275    pass
key = 'boolean'
class DataTypeSize(Expression):
3278class DataTypeSize(Expression):
3279    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3282class DataType(Expression):
3283    arg_types = {
3284        "this": True,
3285        "expressions": False,
3286        "nested": False,
3287        "values": False,
3288        "prefix": False,
3289    }
3290
3291    class Type(AutoName):
3292        ARRAY = auto()
3293        BIGDECIMAL = auto()
3294        BIGINT = auto()
3295        BIGSERIAL = auto()
3296        BINARY = auto()
3297        BIT = auto()
3298        BOOLEAN = auto()
3299        CHAR = auto()
3300        DATE = auto()
3301        DATETIME = auto()
3302        DATETIME64 = auto()
3303        ENUM = auto()
3304        INT4RANGE = auto()
3305        INT4MULTIRANGE = auto()
3306        INT8RANGE = auto()
3307        INT8MULTIRANGE = auto()
3308        NUMRANGE = auto()
3309        NUMMULTIRANGE = auto()
3310        TSRANGE = auto()
3311        TSMULTIRANGE = auto()
3312        TSTZRANGE = auto()
3313        TSTZMULTIRANGE = auto()
3314        DATERANGE = auto()
3315        DATEMULTIRANGE = auto()
3316        DECIMAL = auto()
3317        DOUBLE = auto()
3318        FLOAT = auto()
3319        GEOGRAPHY = auto()
3320        GEOMETRY = auto()
3321        HLLSKETCH = auto()
3322        HSTORE = auto()
3323        IMAGE = auto()
3324        INET = auto()
3325        INT = auto()
3326        INT128 = auto()
3327        INT256 = auto()
3328        INTERVAL = auto()
3329        JSON = auto()
3330        JSONB = auto()
3331        LONGBLOB = auto()
3332        LONGTEXT = auto()
3333        MAP = auto()
3334        MEDIUMBLOB = auto()
3335        MEDIUMTEXT = auto()
3336        MONEY = auto()
3337        NCHAR = auto()
3338        NULL = auto()
3339        NULLABLE = auto()
3340        NVARCHAR = auto()
3341        OBJECT = auto()
3342        ROWVERSION = auto()
3343        SERIAL = auto()
3344        SET = auto()
3345        SMALLINT = auto()
3346        SMALLMONEY = auto()
3347        SMALLSERIAL = auto()
3348        STRUCT = auto()
3349        SUPER = auto()
3350        TEXT = auto()
3351        TIME = auto()
3352        TIMESTAMP = auto()
3353        TIMESTAMPTZ = auto()
3354        TIMESTAMPLTZ = auto()
3355        TINYINT = auto()
3356        UBIGINT = auto()
3357        UINT = auto()
3358        USMALLINT = auto()
3359        UTINYINT = auto()
3360        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3361        UINT128 = auto()
3362        UINT256 = auto()
3363        UNIQUEIDENTIFIER = auto()
3364        USERDEFINED = "USER-DEFINED"
3365        UUID = auto()
3366        VARBINARY = auto()
3367        VARCHAR = auto()
3368        VARIANT = auto()
3369        XML = auto()
3370
3371    TEXT_TYPES = {
3372        Type.CHAR,
3373        Type.NCHAR,
3374        Type.VARCHAR,
3375        Type.NVARCHAR,
3376        Type.TEXT,
3377    }
3378
3379    INTEGER_TYPES = {
3380        Type.INT,
3381        Type.TINYINT,
3382        Type.SMALLINT,
3383        Type.BIGINT,
3384        Type.INT128,
3385        Type.INT256,
3386    }
3387
3388    FLOAT_TYPES = {
3389        Type.FLOAT,
3390        Type.DOUBLE,
3391    }
3392
3393    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3394
3395    TEMPORAL_TYPES = {
3396        Type.TIME,
3397        Type.TIMESTAMP,
3398        Type.TIMESTAMPTZ,
3399        Type.TIMESTAMPLTZ,
3400        Type.DATE,
3401        Type.DATETIME,
3402        Type.DATETIME64,
3403    }
3404
3405    META_TYPES = {"UNKNOWN", "NULL"}
3406
3407    @classmethod
3408    def build(
3409        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3410    ) -> DataType:
3411        from sqlglot import parse_one
3412
3413        if isinstance(dtype, str):
3414            upper = dtype.upper()
3415            if upper in DataType.META_TYPES:
3416                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3417            else:
3418                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3419
3420            if data_type_exp is None:
3421                raise ValueError(f"Unparsable data type value: {dtype}")
3422        elif isinstance(dtype, DataType.Type):
3423            data_type_exp = DataType(this=dtype)
3424        elif isinstance(dtype, DataType):
3425            return dtype
3426        else:
3427            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3428
3429        return DataType(**{**data_type_exp.args, **kwargs})
3430
3431    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3432        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False}
TEXT_TYPES = {<Type.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.TEXT: 'TEXT'>, <Type.NVARCHAR: 'NVARCHAR'>}
INTEGER_TYPES = {<Type.INT256: 'INT256'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT: 'INT'>, <Type.BIGINT: 'BIGINT'>, <Type.INT128: 'INT128'>, <Type.TINYINT: 'TINYINT'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.INT256: 'INT256'>, <Type.SMALLINT: 'SMALLINT'>, <Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.INT128: 'INT128'>, <Type.INT: 'INT'>, <Type.BIGINT: 'BIGINT'>, <Type.TINYINT: 'TINYINT'>}
TEMPORAL_TYPES = {<Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATETIME64: 'DATETIME64'>, <Type.TIME: 'TIME'>, <Type.DATE: 'DATE'>, <Type.DATETIME: 'DATETIME'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>}
META_TYPES = {'NULL', 'UNKNOWN'}
@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:
3407    @classmethod
3408    def build(
3409        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3410    ) -> DataType:
3411        from sqlglot import parse_one
3412
3413        if isinstance(dtype, str):
3414            upper = dtype.upper()
3415            if upper in DataType.META_TYPES:
3416                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3417            else:
3418                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3419
3420            if data_type_exp is None:
3421                raise ValueError(f"Unparsable data type value: {dtype}")
3422        elif isinstance(dtype, DataType.Type):
3423            data_type_exp = DataType(this=dtype)
3424        elif isinstance(dtype, DataType):
3425            return dtype
3426        else:
3427            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3428
3429        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3431    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3432        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3291    class Type(AutoName):
3292        ARRAY = auto()
3293        BIGDECIMAL = auto()
3294        BIGINT = auto()
3295        BIGSERIAL = auto()
3296        BINARY = auto()
3297        BIT = auto()
3298        BOOLEAN = auto()
3299        CHAR = auto()
3300        DATE = auto()
3301        DATETIME = auto()
3302        DATETIME64 = auto()
3303        ENUM = auto()
3304        INT4RANGE = auto()
3305        INT4MULTIRANGE = auto()
3306        INT8RANGE = auto()
3307        INT8MULTIRANGE = auto()
3308        NUMRANGE = auto()
3309        NUMMULTIRANGE = auto()
3310        TSRANGE = auto()
3311        TSMULTIRANGE = auto()
3312        TSTZRANGE = auto()
3313        TSTZMULTIRANGE = auto()
3314        DATERANGE = auto()
3315        DATEMULTIRANGE = auto()
3316        DECIMAL = auto()
3317        DOUBLE = auto()
3318        FLOAT = auto()
3319        GEOGRAPHY = auto()
3320        GEOMETRY = auto()
3321        HLLSKETCH = auto()
3322        HSTORE = auto()
3323        IMAGE = auto()
3324        INET = auto()
3325        INT = auto()
3326        INT128 = auto()
3327        INT256 = auto()
3328        INTERVAL = auto()
3329        JSON = auto()
3330        JSONB = auto()
3331        LONGBLOB = auto()
3332        LONGTEXT = auto()
3333        MAP = auto()
3334        MEDIUMBLOB = auto()
3335        MEDIUMTEXT = auto()
3336        MONEY = auto()
3337        NCHAR = auto()
3338        NULL = auto()
3339        NULLABLE = auto()
3340        NVARCHAR = auto()
3341        OBJECT = auto()
3342        ROWVERSION = auto()
3343        SERIAL = auto()
3344        SET = auto()
3345        SMALLINT = auto()
3346        SMALLMONEY = auto()
3347        SMALLSERIAL = auto()
3348        STRUCT = auto()
3349        SUPER = auto()
3350        TEXT = auto()
3351        TIME = auto()
3352        TIMESTAMP = auto()
3353        TIMESTAMPTZ = auto()
3354        TIMESTAMPLTZ = auto()
3355        TINYINT = auto()
3356        UBIGINT = auto()
3357        UINT = auto()
3358        USMALLINT = auto()
3359        UTINYINT = auto()
3360        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3361        UINT128 = auto()
3362        UINT256 = auto()
3363        UNIQUEIDENTIFIER = auto()
3364        USERDEFINED = "USER-DEFINED"
3365        UUID = auto()
3366        VARBINARY = auto()
3367        VARCHAR = auto()
3368        VARIANT = auto()
3369        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'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
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):
3436class PseudoType(Expression):
3437    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3441class SubqueryPredicate(Predicate):
3442    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3445class All(SubqueryPredicate):
3446    pass
key = 'all'
class Any(SubqueryPredicate):
3449class Any(SubqueryPredicate):
3450    pass
key = 'any'
class Exists(SubqueryPredicate):
3453class Exists(SubqueryPredicate):
3454    pass
key = 'exists'
class Command(Expression):
3459class Command(Expression):
3460    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3463class Transaction(Expression):
3464    arg_types = {"this": False, "modes": False}
arg_types = {'this': False, 'modes': False}
key = 'transaction'
class Commit(Expression):
3467class Commit(Expression):
3468    arg_types = {"chain": False}
arg_types = {'chain': False}
key = 'commit'
class Rollback(Expression):
3471class Rollback(Expression):
3472    arg_types = {"savepoint": False}
arg_types = {'savepoint': False}
key = 'rollback'
class AlterTable(Expression):
3475class AlterTable(Expression):
3476    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3479class AddConstraint(Expression):
3480    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3483class DropPartition(Expression):
3484    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3488class Binary(Condition):
3489    arg_types = {"this": True, "expression": True}
3490
3491    @property
3492    def left(self):
3493        return self.this
3494
3495    @property
3496    def right(self):
3497        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3500class Add(Binary):
3501    pass
key = 'add'
class Connector(Binary):
3504class Connector(Binary):
3505    pass
key = 'connector'
class And(Connector):
3508class And(Connector):
3509    pass
key = 'and'
class Or(Connector):
3512class Or(Connector):
3513    pass
key = 'or'
class BitwiseAnd(Binary):
3516class BitwiseAnd(Binary):
3517    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3520class BitwiseLeftShift(Binary):
3521    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3524class BitwiseOr(Binary):
3525    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3528class BitwiseRightShift(Binary):
3529    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3532class BitwiseXor(Binary):
3533    pass
key = 'bitwisexor'
class Div(Binary):
3536class Div(Binary):
3537    pass
key = 'div'
class Overlaps(Binary):
3540class Overlaps(Binary):
3541    pass
key = 'overlaps'
class Dot(Binary):
3544class Dot(Binary):
3545    @property
3546    def name(self) -> str:
3547        return self.expression.name
3548
3549    @property
3550    def output_name(self) -> str:
3551        return self.name
3552
3553    @classmethod
3554    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3555        """Build a Dot object with a sequence of expressions."""
3556        if len(expressions) < 2:
3557            raise ValueError(f"Dot requires >= 2 expressions.")
3558
3559        a, b, *expressions = expressions
3560        dot = Dot(this=a, expression=b)
3561
3562        for expression in expressions:
3563            dot = Dot(this=dot, expression=expression)
3564
3565        return dot
name: str
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:
3553    @classmethod
3554    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3555        """Build a Dot object with a sequence of expressions."""
3556        if len(expressions) < 2:
3557            raise ValueError(f"Dot requires >= 2 expressions.")
3558
3559        a, b, *expressions = expressions
3560        dot = Dot(this=a, expression=b)
3561
3562        for expression in expressions:
3563            dot = Dot(this=dot, expression=expression)
3564
3565        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3568class DPipe(Binary):
3569    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3572class SafeDPipe(DPipe):
3573    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3576class EQ(Binary, Predicate):
3577    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3580class NullSafeEQ(Binary, Predicate):
3581    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3584class NullSafeNEQ(Binary, Predicate):
3585    pass
key = 'nullsafeneq'
class Distance(Binary):
3588class Distance(Binary):
3589    pass
key = 'distance'
class Escape(Binary):
3592class Escape(Binary):
3593    pass
key = 'escape'
class Glob(Binary, Predicate):
3596class Glob(Binary, Predicate):
3597    pass
key = 'glob'
class GT(Binary, Predicate):
3600class GT(Binary, Predicate):
3601    pass
key = 'gt'
class GTE(Binary, Predicate):
3604class GTE(Binary, Predicate):
3605    pass
key = 'gte'
class ILike(Binary, Predicate):
3608class ILike(Binary, Predicate):
3609    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3612class ILikeAny(Binary, Predicate):
3613    pass
key = 'ilikeany'
class IntDiv(Binary):
3616class IntDiv(Binary):
3617    pass
key = 'intdiv'
class Is(Binary, Predicate):
3620class Is(Binary, Predicate):
3621    pass
key = 'is'
class Kwarg(Binary):
3624class Kwarg(Binary):
3625    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3628class Like(Binary, Predicate):
3629    pass
key = 'like'
class LikeAny(Binary, Predicate):
3632class LikeAny(Binary, Predicate):
3633    pass
key = 'likeany'
class LT(Binary, Predicate):
3636class LT(Binary, Predicate):
3637    pass
key = 'lt'
class LTE(Binary, Predicate):
3640class LTE(Binary, Predicate):
3641    pass
key = 'lte'
class Mod(Binary):
3644class Mod(Binary):
3645    pass
key = 'mod'
class Mul(Binary):
3648class Mul(Binary):
3649    pass
key = 'mul'
class NEQ(Binary, Predicate):
3652class NEQ(Binary, Predicate):
3653    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3656class SimilarTo(Binary, Predicate):
3657    pass
key = 'similarto'
class Slice(Binary):
3660class Slice(Binary):
3661    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3664class Sub(Binary):
3665    pass
key = 'sub'
class ArrayOverlaps(Binary):
3668class ArrayOverlaps(Binary):
3669    pass
key = 'arrayoverlaps'
class Unary(Condition):
3674class Unary(Condition):
3675    pass
key = 'unary'
class BitwiseNot(Unary):
3678class BitwiseNot(Unary):
3679    pass
key = 'bitwisenot'
class Not(Unary):
3682class Not(Unary):
3683    pass
key = 'not'
class Paren(Unary):
3686class Paren(Unary):
3687    arg_types = {"this": True, "with": False}
3688
3689    @property
3690    def output_name(self) -> str:
3691        return self.this.name
arg_types = {'this': True, 'with': False}
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
''
key = 'paren'
class Neg(Unary):
3694class Neg(Unary):
3695    pass
key = 'neg'
class Alias(Expression):
3698class Alias(Expression):
3699    arg_types = {"this": True, "alias": False}
3700
3701    @property
3702    def output_name(self) -> str:
3703        return self.alias
arg_types = {'this': True, 'alias': False}
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
''
key = 'alias'
class Aliases(Expression):
3706class Aliases(Expression):
3707    arg_types = {"this": True, "expressions": True}
3708
3709    @property
3710    def aliases(self):
3711        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3714class AtTimeZone(Expression):
3715    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3718class Between(Predicate):
3719    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3722class Bracket(Condition):
3723    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3726class SafeBracket(Bracket):
3727    """Represents array lookup where OOB index yields NULL instead of causing a failure."""

Represents array lookup where OOB index yields NULL instead of causing a failure.

key = 'safebracket'
class Distinct(Expression):
3730class Distinct(Expression):
3731    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3734class In(Predicate):
3735    arg_types = {
3736        "this": True,
3737        "expressions": False,
3738        "query": False,
3739        "unnest": False,
3740        "field": False,
3741        "is_global": False,
3742    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3745class TimeUnit(Expression):
3746    """Automatically converts unit arg into a var."""
3747
3748    arg_types = {"unit": False}
3749
3750    def __init__(self, **args):
3751        unit = args.get("unit")
3752        if isinstance(unit, (Column, Literal)):
3753            args["unit"] = Var(this=unit.name)
3754        elif isinstance(unit, Week):
3755            unit.set("this", Var(this=unit.this.name))
3756
3757        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3750    def __init__(self, **args):
3751        unit = args.get("unit")
3752        if isinstance(unit, (Column, Literal)):
3753            args["unit"] = Var(this=unit.name)
3754        elif isinstance(unit, Week):
3755            unit.set("this", Var(this=unit.this.name))
3756
3757        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3760class Interval(TimeUnit):
3761    arg_types = {"this": False, "unit": False}
3762
3763    @property
3764    def unit(self) -> t.Optional[Var]:
3765        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3768class IgnoreNulls(Expression):
3769    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3772class RespectNulls(Expression):
3773    pass
key = 'respectnulls'
class Func(Condition):
3777class Func(Condition):
3778    """
3779    The base class for all function expressions.
3780
3781    Attributes:
3782        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3783            treated as a variable length argument and the argument's value will be stored as a list.
3784        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3785            for this function expression. These values are used to map this node to a name during parsing
3786            as well as to provide the function's name during SQL string generation. By default the SQL
3787            name is set to the expression's class name transformed to snake case.
3788    """
3789
3790    is_var_len_args = False
3791
3792    @classmethod
3793    def from_arg_list(cls, args):
3794        if cls.is_var_len_args:
3795            all_arg_keys = list(cls.arg_types)
3796            # If this function supports variable length argument treat the last argument as such.
3797            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3798            num_non_var = len(non_var_len_arg_keys)
3799
3800            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3801            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3802        else:
3803            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3804
3805        return cls(**args_dict)
3806
3807    @classmethod
3808    def sql_names(cls):
3809        if cls is Func:
3810            raise NotImplementedError(
3811                "SQL name is only supported by concrete function implementations"
3812            )
3813        if "_sql_names" not in cls.__dict__:
3814            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3815        return cls._sql_names
3816
3817    @classmethod
3818    def sql_name(cls):
3819        return cls.sql_names()[0]
3820
3821    @classmethod
3822    def default_parser_mappings(cls):
3823        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.
is_var_len_args = False
@classmethod
def from_arg_list(cls, args):
3792    @classmethod
3793    def from_arg_list(cls, args):
3794        if cls.is_var_len_args:
3795            all_arg_keys = list(cls.arg_types)
3796            # If this function supports variable length argument treat the last argument as such.
3797            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3798            num_non_var = len(non_var_len_arg_keys)
3799
3800            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3801            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3802        else:
3803            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3804
3805        return cls(**args_dict)
@classmethod
def sql_names(cls):
3807    @classmethod
3808    def sql_names(cls):
3809        if cls is Func:
3810            raise NotImplementedError(
3811                "SQL name is only supported by concrete function implementations"
3812            )
3813        if "_sql_names" not in cls.__dict__:
3814            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3815        return cls._sql_names
@classmethod
def sql_name(cls):
3817    @classmethod
3818    def sql_name(cls):
3819        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3821    @classmethod
3822    def default_parser_mappings(cls):
3823        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3826class AggFunc(Func):
3827    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3830class ParameterizedAgg(AggFunc):
3831    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3834class Abs(Func):
3835    pass
key = 'abs'
class Anonymous(Func):
3838class Anonymous(Func):
3839    arg_types = {"this": True, "expressions": False}
3840    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3845class Hll(AggFunc):
3846    arg_types = {"this": True, "expressions": False}
3847    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3850class ApproxDistinct(AggFunc):
3851    arg_types = {"this": True, "accuracy": False}
3852    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3855class Array(Func):
3856    arg_types = {"expressions": False}
3857    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3861class ToChar(Func):
3862    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3865class GenerateSeries(Func):
3866    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3869class ArrayAgg(AggFunc):
3870    pass
key = 'arrayagg'
class ArrayAll(Func):
3873class ArrayAll(Func):
3874    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3877class ArrayAny(Func):
3878    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3881class ArrayConcat(Func):
3882    arg_types = {"this": True, "expressions": False}
3883    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3886class ArrayContains(Binary, Func):
3887    pass
key = 'arraycontains'
class ArrayContained(Binary):
3890class ArrayContained(Binary):
3891    pass
key = 'arraycontained'
class ArrayFilter(Func):
3894class ArrayFilter(Func):
3895    arg_types = {"this": True, "expression": True}
3896    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3899class ArrayJoin(Func):
3900    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3903class ArraySize(Func):
3904    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3907class ArraySort(Func):
3908    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3911class ArraySum(Func):
3912    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3915class ArrayUnionAgg(AggFunc):
3916    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3919class Avg(AggFunc):
3920    pass
key = 'avg'
class AnyValue(AggFunc):
3923class AnyValue(AggFunc):
3924    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
3927class Case(Func):
3928    arg_types = {"this": False, "ifs": True, "default": False}
3929
3930    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3931        instance = _maybe_copy(self, copy)
3932        instance.append(
3933            "ifs",
3934            If(
3935                this=maybe_parse(condition, copy=copy, **opts),
3936                true=maybe_parse(then, copy=copy, **opts),
3937            ),
3938        )
3939        return instance
3940
3941    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3942        instance = _maybe_copy(self, copy)
3943        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3944        return instance
arg_types = {'this': False, 'ifs': True, 'default': False}
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3930    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3931        instance = _maybe_copy(self, copy)
3932        instance.append(
3933            "ifs",
3934            If(
3935                this=maybe_parse(condition, copy=copy, **opts),
3936                true=maybe_parse(then, copy=copy, **opts),
3937            ),
3938        )
3939        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3941    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3942        instance = _maybe_copy(self, copy)
3943        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3944        return instance
key = 'case'
class Cast(Func):
3947class Cast(Func):
3948    arg_types = {"this": True, "to": True, "format": False}
3949
3950    @property
3951    def name(self) -> str:
3952        return self.this.name
3953
3954    @property
3955    def to(self) -> DataType:
3956        return self.args["to"]
3957
3958    @property
3959    def output_name(self) -> str:
3960        return self.name
3961
3962    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3963        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True, 'format': False}
name: str
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:
3962    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3963        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
3966class CastToStrType(Func):
3967    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
3970class Collate(Binary):
3971    pass
key = 'collate'
class TryCast(Cast):
3974class TryCast(Cast):
3975    pass
key = 'trycast'
class Ceil(Func):
3978class Ceil(Func):
3979    arg_types = {"this": True, "decimals": False}
3980    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
3983class Coalesce(Func):
3984    arg_types = {"this": True, "expressions": False}
3985    is_var_len_args = True
3986    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
3989class Concat(Func):
3990    arg_types = {"expressions": True}
3991    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
3994class SafeConcat(Concat):
3995    pass
key = 'safeconcat'
class ConcatWs(Concat):
3998class ConcatWs(Concat):
3999    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4002class Count(AggFunc):
4003    arg_types = {"this": False, "expressions": False}
4004    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4007class CountIf(AggFunc):
4008    pass
key = 'countif'
class CurrentDate(Func):
4011class CurrentDate(Func):
4012    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4015class CurrentDatetime(Func):
4016    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4019class CurrentTime(Func):
4020    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4023class CurrentTimestamp(Func):
4024    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4027class CurrentUser(Func):
4028    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4031class DateAdd(Func, TimeUnit):
4032    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4035class DateSub(Func, TimeUnit):
4036    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4039class DateDiff(Func, TimeUnit):
4040    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4041    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4044class DateTrunc(Func):
4045    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4048class DatetimeAdd(Func, TimeUnit):
4049    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4052class DatetimeSub(Func, TimeUnit):
4053    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4056class DatetimeDiff(Func, TimeUnit):
4057    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4060class DatetimeTrunc(Func, TimeUnit):
4061    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4064class DayOfWeek(Func):
4065    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4068class DayOfMonth(Func):
4069    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4072class DayOfYear(Func):
4073    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4076class WeekOfYear(Func):
4077    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class LastDateOfMonth(Func):
4080class LastDateOfMonth(Func):
4081    pass
key = 'lastdateofmonth'
class Extract(Func):
4084class Extract(Func):
4085    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4088class TimestampAdd(Func, TimeUnit):
4089    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4092class TimestampSub(Func, TimeUnit):
4093    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4096class TimestampDiff(Func, TimeUnit):
4097    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4100class TimestampTrunc(Func, TimeUnit):
4101    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4104class TimeAdd(Func, TimeUnit):
4105    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4108class TimeSub(Func, TimeUnit):
4109    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4112class TimeDiff(Func, TimeUnit):
4113    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4116class TimeTrunc(Func, TimeUnit):
4117    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4120class DateFromParts(Func):
4121    _sql_names = ["DATEFROMPARTS"]
4122    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4125class DateStrToDate(Func):
4126    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4129class DateToDateStr(Func):
4130    pass
key = 'datetodatestr'
class DateToDi(Func):
4133class DateToDi(Func):
4134    pass
key = 'datetodi'
class Date(Func):
4138class Date(Func):
4139    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4142class Day(Func):
4143    pass
key = 'day'
class Decode(Func):
4146class Decode(Func):
4147    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4150class DiToDate(Func):
4151    pass
key = 'ditodate'
class Encode(Func):
4154class Encode(Func):
4155    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4158class Exp(Func):
4159    pass
key = 'exp'
class Explode(Func):
4162class Explode(Func):
4163    pass
key = 'explode'
class Floor(Func):
4166class Floor(Func):
4167    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4170class FromBase64(Func):
4171    pass
key = 'frombase64'
class ToBase64(Func):
4174class ToBase64(Func):
4175    pass
key = 'tobase64'
class Greatest(Func):
4178class Greatest(Func):
4179    arg_types = {"this": True, "expressions": False}
4180    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4183class GroupConcat(Func):
4184    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4187class Hex(Func):
4188    pass
key = 'hex'
class If(Func):
4191class If(Func):
4192    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4195class Initcap(Func):
4196    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4199class JSONKeyValue(Expression):
4200    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4203class JSONObject(Func):
4204    arg_types = {
4205        "expressions": False,
4206        "null_handling": False,
4207        "unique_keys": False,
4208        "return_type": False,
4209        "format_json": False,
4210        "encoding": False,
4211    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4214class OpenJSONColumnDef(Expression):
4215    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
arg_types = {'this': True, 'kind': True, 'path': False, 'as_json': False}
key = 'openjsoncolumndef'
class OpenJSON(Func):
4218class OpenJSON(Func):
4219    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4222class JSONBContains(Binary):
4223    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4226class JSONExtract(Binary, Func):
4227    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4230class JSONExtractScalar(JSONExtract):
4231    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4234class JSONBExtract(JSONExtract):
4235    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4238class JSONBExtractScalar(JSONExtract):
4239    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4242class JSONFormat(Func):
4243    arg_types = {"this": False, "options": False}
4244    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4248class JSONArrayContains(Binary, Predicate, Func):
4249    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4252class Least(Func):
4253    arg_types = {"expressions": False}
4254    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4257class Left(Func):
4258    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4265class Length(Func):
4266    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4269class Levenshtein(Func):
4270    arg_types = {
4271        "this": True,
4272        "expression": False,
4273        "ins_cost": False,
4274        "del_cost": False,
4275        "sub_cost": False,
4276    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4279class Ln(Func):
4280    pass
key = 'ln'
class Log(Func):
4283class Log(Func):
4284    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4287class Log2(Func):
4288    pass
key = 'log2'
class Log10(Func):
4291class Log10(Func):
4292    pass
key = 'log10'
class LogicalOr(AggFunc):
4295class LogicalOr(AggFunc):
4296    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4299class LogicalAnd(AggFunc):
4300    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4303class Lower(Func):
4304    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4307class Map(Func):
4308    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4311class MapFromEntries(Func):
4312    pass
key = 'mapfromentries'
class StarMap(Func):
4315class StarMap(Func):
4316    pass
key = 'starmap'
class VarMap(Func):
4319class VarMap(Func):
4320    arg_types = {"keys": True, "values": True}
4321    is_var_len_args = True
4322
4323    @property
4324    def keys(self) -> t.List[Expression]:
4325        return self.args["keys"].expressions
4326
4327    @property
4328    def values(self) -> t.List[Expression]:
4329        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4333class MatchAgainst(Func):
4334    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4337class Max(AggFunc):
4338    arg_types = {"this": True, "expressions": False}
4339    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4342class MD5(Func):
4343    _sql_names = ["MD5"]
key = 'md5'
class Min(AggFunc):
4346class Min(AggFunc):
4347    arg_types = {"this": True, "expressions": False}
4348    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4351class Month(Func):
4352    pass
key = 'month'
class Nvl2(Func):
4355class Nvl2(Func):
4356    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4359class Posexplode(Func):
4360    pass
key = 'posexplode'
class Pow(Binary, Func):
4363class Pow(Binary, Func):
4364    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4367class PercentileCont(AggFunc):
4368    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4371class PercentileDisc(AggFunc):
4372    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4375class Quantile(AggFunc):
4376    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4379class ApproxQuantile(Quantile):
4380    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
arg_types = {'this': True, 'quantile': True, 'accuracy': False, 'weight': False}
key = 'approxquantile'
class RangeN(Func):
4383class RangeN(Func):
4384    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4387class ReadCSV(Func):
4388    _sql_names = ["READ_CSV"]
4389    is_var_len_args = True
4390    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4393class Reduce(Func):
4394    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
arg_types = {'this': True, 'initial': True, 'merge': True, 'finish': False}
key = 'reduce'
class RegexpExtract(Func):
4397class RegexpExtract(Func):
4398    arg_types = {
4399        "this": True,
4400        "expression": True,
4401        "position": False,
4402        "occurrence": False,
4403        "group": False,
4404    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'group': False}
key = 'regexpextract'
class RegexpLike(Func):
4407class RegexpLike(Func):
4408    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4411class RegexpILike(Func):
4412    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4417class RegexpSplit(Func):
4418    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4421class Repeat(Func):
4422    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4425class Round(Func):
4426    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4429class RowNumber(Func):
4430    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4433class SafeDivide(Func):
4434    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4437class SetAgg(AggFunc):
4438    pass
key = 'setagg'
class SHA(Func):
4441class SHA(Func):
4442    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4445class SHA2(Func):
4446    _sql_names = ["SHA2"]
4447    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4450class SortArray(Func):
4451    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4454class Split(Func):
4455    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4460class Substring(Func):
4461    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4464class StandardHash(Func):
4465    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4468class StrPosition(Func):
4469    arg_types = {
4470        "this": True,
4471        "substr": True,
4472        "position": False,
4473        "instance": False,
4474    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4477class StrToDate(Func):
4478    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4481class StrToTime(Func):
4482    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4487class StrToUnix(Func):
4488    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4491class NumberToStr(Func):
4492    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4495class FromBase(Func):
4496    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4499class Struct(Func):
4500    arg_types = {"expressions": True}
4501    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4504class StructExtract(Func):
4505    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4508class Sum(AggFunc):
4509    pass
key = 'sum'
class Sqrt(Func):
4512class Sqrt(Func):
4513    pass
key = 'sqrt'
class Stddev(AggFunc):
4516class Stddev(AggFunc):
4517    pass
key = 'stddev'
class StddevPop(AggFunc):
4520class StddevPop(AggFunc):
4521    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4524class StddevSamp(AggFunc):
4525    pass
key = 'stddevsamp'
class TimeToStr(Func):
4528class TimeToStr(Func):
4529    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4532class TimeToTimeStr(Func):
4533    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4536class TimeToUnix(Func):
4537    pass
key = 'timetounix'
class TimeStrToDate(Func):
4540class TimeStrToDate(Func):
4541    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4544class TimeStrToTime(Func):
4545    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4548class TimeStrToUnix(Func):
4549    pass
key = 'timestrtounix'
class Trim(Func):
4552class Trim(Func):
4553    arg_types = {
4554        "this": True,
4555        "expression": False,
4556        "position": False,
4557        "collation": False,
4558    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4561class TsOrDsAdd(Func, TimeUnit):
4562    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4565class TsOrDsToDateStr(Func):
4566    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4569class TsOrDsToDate(Func):
4570    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4573class TsOrDiToDi(Func):
4574    pass
key = 'tsorditodi'
class Unhex(Func):
4577class Unhex(Func):
4578    pass
key = 'unhex'
class UnixToStr(Func):
4581class UnixToStr(Func):
4582    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4587class UnixToTime(Func):
4588    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4589
4590    SECONDS = Literal.string("seconds")
4591    MILLIS = Literal.string("millis")
4592    MICROS = Literal.string("micros")
arg_types = {'this': True, 'scale': False, 'zone': False, 'hours': False, 'minutes': False}
SECONDS = (LITERAL this: seconds, is_string: True)
MILLIS = (LITERAL this: millis, is_string: True)
MICROS = (LITERAL this: micros, is_string: True)
key = 'unixtotime'
class UnixToTimeStr(Func):
4595class UnixToTimeStr(Func):
4596    pass
key = 'unixtotimestr'
class Upper(Func):
4599class Upper(Func):
4600    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4603class Variance(AggFunc):
4604    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4607class VariancePop(AggFunc):
4608    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4611class Week(Func):
4612    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4615class XMLTable(Func):
4616    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
arg_types = {'this': True, 'passing': False, 'columns': False, 'by_ref': False}
key = 'xmltable'
class Year(Func):
4619class Year(Func):
4620    pass
key = 'year'
class Use(Expression):
4623class Use(Expression):
4624    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4627class Merge(Expression):
4628    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
arg_types = {'this': True, 'using': True, 'on': True, 'expressions': True}
key = 'merge'
class When(Func):
4631class When(Func):
4632    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
arg_types = {'matched': True, 'source': False, 'condition': False, 'then': True}
key = 'when'
class NextValueFor(Func):
4637class NextValueFor(Func):
4638    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.JSONArrayContains'>, <class 'sqlglot.expressions.JSONBExtract'>, <class 'sqlglot.expressions.JSONBExtractScalar'>, <class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.JSONExtractScalar'>, <class 'sqlglot.expressions.JSONFormat'>, <class 'sqlglot.expressions.JSONObject'>, <class 'sqlglot.expressions.LastDateOfMonth'>, <class 'sqlglot.expressions.Least'>, <class 'sqlglot.expressions.Left'>, <class 'sqlglot.expressions.Length'>, <class 'sqlglot.expressions.Levenshtein'>, <class 'sqlglot.expressions.Ln'>, <class 'sqlglot.expressions.Log'>, <class 'sqlglot.expressions.Log10'>, <class 'sqlglot.expressions.Log2'>, <class 'sqlglot.expressions.LogicalAnd'>, <class 'sqlglot.expressions.LogicalOr'>, <class 'sqlglot.expressions.Lower'>, <class 'sqlglot.expressions.MD5'>, <class 'sqlglot.expressions.Map'>, <class 'sqlglot.expressions.MapFromEntries'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <class 'sqlglot.expressions.NextValueFor'>, <class 'sqlglot.expressions.NumberToStr'>, <class 'sqlglot.expressions.Nvl2'>, <class 'sqlglot.expressions.OpenJSON'>, <class 'sqlglot.expressions.ParameterizedAgg'>, <class 'sqlglot.expressions.PercentileCont'>, <class 'sqlglot.expressions.PercentileDisc'>, <class 'sqlglot.expressions.Posexplode'>, <class 'sqlglot.expressions.Pow'>, <class 'sqlglot.expressions.Quantile'>, <class 'sqlglot.expressions.RangeN'>, <class 'sqlglot.expressions.ReadCSV'>, <class 'sqlglot.expressions.Reduce'>, <class 'sqlglot.expressions.RegexpExtract'>, <class 'sqlglot.expressions.RegexpILike'>, <class 'sqlglot.expressions.RegexpLike'>, <class 'sqlglot.expressions.RegexpSplit'>, <class 'sqlglot.expressions.Repeat'>, <class 'sqlglot.expressions.Right'>, <class 'sqlglot.expressions.Round'>, <class 'sqlglot.expressions.RowNumber'>, <class 'sqlglot.expressions.SHA'>, <class 'sqlglot.expressions.SHA2'>, <class 'sqlglot.expressions.SafeConcat'>, <class 'sqlglot.expressions.SafeDivide'>, <class 'sqlglot.expressions.SetAgg'>, <class 'sqlglot.expressions.SortArray'>, <class 'sqlglot.expressions.Split'>, <class 'sqlglot.expressions.Sqrt'>, <class 'sqlglot.expressions.StandardHash'>, <class 'sqlglot.expressions.StarMap'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.Trim'>, <class 'sqlglot.expressions.TryCast'>, <class 'sqlglot.expressions.TsOrDiToDi'>, <class 'sqlglot.expressions.TsOrDsAdd'>, <class 'sqlglot.expressions.TsOrDsToDate'>, <class 'sqlglot.expressions.TsOrDsToDateStr'>, <class 'sqlglot.expressions.Unhex'>, <class 'sqlglot.expressions.UnixToStr'>, <class 'sqlglot.expressions.UnixToTime'>, <class 'sqlglot.expressions.UnixToTimeStr'>, <class 'sqlglot.expressions.Upper'>, <class 'sqlglot.expressions.VarMap'>, <class 'sqlglot.expressions.Variance'>, <class 'sqlglot.expressions.VariancePop'>, <class 'sqlglot.expressions.Week'>, <class 'sqlglot.expressions.WeekOfYear'>, <class 'sqlglot.expressions.When'>, <class 'sqlglot.expressions.XMLTable'>, <class 'sqlglot.expressions.Year'>]
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:
4675def maybe_parse(
4676    sql_or_expression: ExpOrStr,
4677    *,
4678    into: t.Optional[IntoType] = None,
4679    dialect: DialectType = None,
4680    prefix: t.Optional[str] = None,
4681    copy: bool = False,
4682    **opts,
4683) -> Expression:
4684    """Gracefully handle a possible string or expression.
4685
4686    Example:
4687        >>> maybe_parse("1")
4688        (LITERAL this: 1, is_string: False)
4689        >>> maybe_parse(to_identifier("x"))
4690        (IDENTIFIER this: x, quoted: False)
4691
4692    Args:
4693        sql_or_expression: the SQL code string or an expression
4694        into: the SQLGlot Expression to parse into
4695        dialect: the dialect used to parse the input expressions (in the case that an
4696            input expression is a SQL string).
4697        prefix: a string to prefix the sql with before it gets parsed
4698            (automatically includes a space)
4699        copy: whether or not to copy the expression.
4700        **opts: other options to use to parse the input expressions (again, in the case
4701            that an input expression is a SQL string).
4702
4703    Returns:
4704        Expression: the parsed or given expression.
4705    """
4706    if isinstance(sql_or_expression, Expression):
4707        if copy:
4708            return sql_or_expression.copy()
4709        return sql_or_expression
4710
4711    if sql_or_expression is None:
4712        raise ParseError(f"SQL cannot be None")
4713
4714    import sqlglot
4715
4716    sql = str(sql_or_expression)
4717    if prefix:
4718        sql = f"{prefix} {sql}"
4719
4720    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:
4904def union(
4905    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4906) -> Union:
4907    """
4908    Initializes a syntax tree from one UNION expression.
4909
4910    Example:
4911        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4912        'SELECT * FROM foo UNION SELECT * FROM bla'
4913
4914    Args:
4915        left: the SQL code string corresponding to the left-hand side.
4916            If an `Expression` instance is passed, it will be used as-is.
4917        right: the SQL code string corresponding to the right-hand side.
4918            If an `Expression` instance is passed, it will be used as-is.
4919        distinct: set the DISTINCT flag if and only if this is true.
4920        dialect: the dialect used to parse the input expression.
4921        opts: other options to use to parse the input expressions.
4922
4923    Returns:
4924        The new Union instance.
4925    """
4926    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4927    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4928
4929    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:
4932def intersect(
4933    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4934) -> Intersect:
4935    """
4936    Initializes a syntax tree from one INTERSECT expression.
4937
4938    Example:
4939        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4940        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4941
4942    Args:
4943        left: the SQL code string corresponding to the left-hand side.
4944            If an `Expression` instance is passed, it will be used as-is.
4945        right: the SQL code string corresponding to the right-hand side.
4946            If an `Expression` instance is passed, it will be used as-is.
4947        distinct: set the DISTINCT flag if and only if this is true.
4948        dialect: the dialect used to parse the input expression.
4949        opts: other options to use to parse the input expressions.
4950
4951    Returns:
4952        The new Intersect instance.
4953    """
4954    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4955    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4956
4957    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:
4960def except_(
4961    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4962) -> Except:
4963    """
4964    Initializes a syntax tree from one EXCEPT expression.
4965
4966    Example:
4967        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4968        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4969
4970    Args:
4971        left: the SQL code string corresponding to the left-hand side.
4972            If an `Expression` instance is passed, it will be used as-is.
4973        right: the SQL code string corresponding to the right-hand side.
4974            If an `Expression` instance is passed, it will be used as-is.
4975        distinct: set the DISTINCT flag if and only if this is true.
4976        dialect: the dialect used to parse the input expression.
4977        opts: other options to use to parse the input expressions.
4978
4979    Returns:
4980        The new Except instance.
4981    """
4982    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4983    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4984
4985    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:
4988def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4989    """
4990    Initializes a syntax tree from one or multiple SELECT expressions.
4991
4992    Example:
4993        >>> select("col1", "col2").from_("tbl").sql()
4994        'SELECT col1, col2 FROM tbl'
4995
4996    Args:
4997        *expressions: the SQL code string to parse as the expressions of a
4998            SELECT statement. If an Expression instance is passed, this is used as-is.
4999        dialect: the dialect used to parse the input expressions (in the case that an
5000            input expression is a SQL string).
5001        **opts: other options to use to parse the input expressions (again, in the case
5002            that an input expression is a SQL string).
5003
5004    Returns:
5005        Select: the syntax tree for the SELECT statement.
5006    """
5007    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:
5010def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5011    """
5012    Initializes a syntax tree from a FROM expression.
5013
5014    Example:
5015        >>> from_("tbl").select("col1", "col2").sql()
5016        'SELECT col1, col2 FROM tbl'
5017
5018    Args:
5019        *expression: the SQL code string to parse as the FROM expressions of a
5020            SELECT statement. If an Expression instance is passed, this is used as-is.
5021        dialect: the dialect used to parse the input expression (in the case that the
5022            input expression is a SQL string).
5023        **opts: other options to use to parse the input expressions (again, in the case
5024            that the input expression is a SQL string).
5025
5026    Returns:
5027        Select: the syntax tree for the SELECT statement.
5028    """
5029    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:
5032def update(
5033    table: str | Table,
5034    properties: dict,
5035    where: t.Optional[ExpOrStr] = None,
5036    from_: t.Optional[ExpOrStr] = None,
5037    dialect: DialectType = None,
5038    **opts,
5039) -> Update:
5040    """
5041    Creates an update statement.
5042
5043    Example:
5044        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5045        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5046
5047    Args:
5048        *properties: dictionary of properties to set which are
5049            auto converted to sql objects eg None -> NULL
5050        where: sql conditional parsed into a WHERE statement
5051        from_: sql statement parsed into a FROM statement
5052        dialect: the dialect used to parse the input expressions.
5053        **opts: other options to use to parse the input expressions.
5054
5055    Returns:
5056        Update: the syntax tree for the UPDATE statement.
5057    """
5058    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5059    update_expr.set(
5060        "expressions",
5061        [
5062            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5063            for k, v in properties.items()
5064        ],
5065    )
5066    if from_:
5067        update_expr.set(
5068            "from",
5069            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5070        )
5071    if isinstance(where, Condition):
5072        where = Where(this=where)
5073    if where:
5074        update_expr.set(
5075            "where",
5076            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5077        )
5078    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:
5081def delete(
5082    table: ExpOrStr,
5083    where: t.Optional[ExpOrStr] = None,
5084    returning: t.Optional[ExpOrStr] = None,
5085    dialect: DialectType = None,
5086    **opts,
5087) -> Delete:
5088    """
5089    Builds a delete statement.
5090
5091    Example:
5092        >>> delete("my_table", where="id > 1").sql()
5093        'DELETE FROM my_table WHERE id > 1'
5094
5095    Args:
5096        where: sql conditional parsed into a WHERE statement
5097        returning: sql conditional parsed into a RETURNING statement
5098        dialect: the dialect used to parse the input expressions.
5099        **opts: other options to use to parse the input expressions.
5100
5101    Returns:
5102        Delete: the syntax tree for the DELETE statement.
5103    """
5104    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5105    if where:
5106        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5107    if returning:
5108        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5109    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:
5112def insert(
5113    expression: ExpOrStr,
5114    into: ExpOrStr,
5115    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5116    overwrite: t.Optional[bool] = None,
5117    dialect: DialectType = None,
5118    copy: bool = True,
5119    **opts,
5120) -> Insert:
5121    """
5122    Builds an INSERT statement.
5123
5124    Example:
5125        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5126        'INSERT INTO tbl VALUES (1, 2, 3)'
5127
5128    Args:
5129        expression: the sql string or expression of the INSERT statement
5130        into: the tbl to insert data to.
5131        columns: optionally the table's column names.
5132        overwrite: whether to INSERT OVERWRITE or not.
5133        dialect: the dialect used to parse the input expressions.
5134        copy: whether or not to copy the expression.
5135        **opts: other options to use to parse the input expressions.
5136
5137    Returns:
5138        Insert: the syntax tree for the INSERT statement.
5139    """
5140    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5141    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5142
5143    if columns:
5144        this = _apply_list_builder(
5145            *columns,
5146            instance=Schema(this=this),
5147            arg="expressions",
5148            into=Identifier,
5149            copy=False,
5150            dialect=dialect,
5151            **opts,
5152        )
5153
5154    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:
5157def condition(
5158    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5159) -> Condition:
5160    """
5161    Initialize a logical condition expression.
5162
5163    Example:
5164        >>> condition("x=1").sql()
5165        'x = 1'
5166
5167        This is helpful for composing larger logical syntax trees:
5168        >>> where = condition("x=1")
5169        >>> where = where.and_("y=1")
5170        >>> Select().from_("tbl").select("*").where(where).sql()
5171        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5172
5173    Args:
5174        *expression: the SQL code string to parse.
5175            If an Expression instance is passed, this is used as-is.
5176        dialect: the dialect used to parse the input expression (in the case that the
5177            input expression is a SQL string).
5178        copy: Whether or not to copy `expression` (only applies to expressions).
5179        **opts: other options to use to parse the input expressions (again, in the case
5180            that the input expression is a SQL string).
5181
5182    Returns:
5183        The new Condition instance
5184    """
5185    return maybe_parse(
5186        expression,
5187        into=Condition,
5188        dialect=dialect,
5189        copy=copy,
5190        **opts,
5191    )

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:
5194def and_(
5195    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5196) -> Condition:
5197    """
5198    Combine multiple conditions with an AND logical operator.
5199
5200    Example:
5201        >>> and_("x=1", and_("y=1", "z=1")).sql()
5202        'x = 1 AND (y = 1 AND z = 1)'
5203
5204    Args:
5205        *expressions: the SQL code strings to parse.
5206            If an Expression instance is passed, this is used as-is.
5207        dialect: the dialect used to parse the input expression.
5208        copy: whether or not to copy `expressions` (only applies to Expressions).
5209        **opts: other options to use to parse the input expressions.
5210
5211    Returns:
5212        And: the new condition
5213    """
5214    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:
5217def or_(
5218    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5219) -> Condition:
5220    """
5221    Combine multiple conditions with an OR logical operator.
5222
5223    Example:
5224        >>> or_("x=1", or_("y=1", "z=1")).sql()
5225        'x = 1 OR (y = 1 OR z = 1)'
5226
5227    Args:
5228        *expressions: the SQL code strings to parse.
5229            If an Expression instance is passed, this is used as-is.
5230        dialect: the dialect used to parse the input expression.
5231        copy: whether or not to copy `expressions` (only applies to Expressions).
5232        **opts: other options to use to parse the input expressions.
5233
5234    Returns:
5235        Or: the new condition
5236    """
5237    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:
5240def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5241    """
5242    Wrap a condition with a NOT operator.
5243
5244    Example:
5245        >>> not_("this_suit='black'").sql()
5246        "NOT this_suit = 'black'"
5247
5248    Args:
5249        expression: the SQL code string to parse.
5250            If an Expression instance is passed, this is used as-is.
5251        dialect: the dialect used to parse the input expression.
5252        copy: whether to copy the expression or not.
5253        **opts: other options to use to parse the input expressions.
5254
5255    Returns:
5256        The new condition.
5257    """
5258    this = condition(
5259        expression,
5260        dialect=dialect,
5261        copy=copy,
5262        **opts,
5263    )
5264    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:
5267def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5268    """
5269    Wrap an expression in parentheses.
5270
5271    Example:
5272        >>> paren("5 + 3").sql()
5273        '(5 + 3)'
5274
5275    Args:
5276        expression: the SQL code string to parse.
5277            If an Expression instance is passed, this is used as-is.
5278        copy: whether to copy the expression or not.
5279
5280    Returns:
5281        The wrapped expression.
5282    """
5283    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.

SAFE_IDENTIFIER_RE = re.compile('^[_a-zA-Z][\\w]*$')
def to_identifier(name, quoted=None, copy=True):
5301def to_identifier(name, quoted=None, copy=True):
5302    """Builds an identifier.
5303
5304    Args:
5305        name: The name to turn into an identifier.
5306        quoted: Whether or not force quote the identifier.
5307        copy: Whether or not to copy a passed in Identefier node.
5308
5309    Returns:
5310        The identifier ast node.
5311    """
5312
5313    if name is None:
5314        return None
5315
5316    if isinstance(name, Identifier):
5317        identifier = _maybe_copy(name, copy)
5318    elif isinstance(name, str):
5319        identifier = Identifier(
5320            this=name,
5321            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5322        )
5323    else:
5324        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5325    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.

INTERVAL_STRING_RE = re.compile('\\s*([0-9]+)\\s*([a-zA-Z]+)\\s*')
def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
5331def to_interval(interval: str | Literal) -> Interval:
5332    """Builds an interval expression from a string like '1 day' or '5 months'."""
5333    if isinstance(interval, Literal):
5334        if not interval.is_string:
5335            raise ValueError("Invalid interval string.")
5336
5337        interval = interval.this
5338
5339    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5340
5341    if not interval_parts:
5342        raise ValueError("Invalid interval string.")
5343
5344    return Interval(
5345        this=Literal.string(interval_parts.group(1)),
5346        unit=Var(this=interval_parts.group(2)),
5347    )

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]:
5360def to_table(
5361    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5362) -> t.Optional[Table]:
5363    """
5364    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5365    If a table is passed in then that table is returned.
5366
5367    Args:
5368        sql_path: a `[catalog].[schema].[table]` string.
5369        dialect: the source dialect according to which the table name will be parsed.
5370        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5371
5372    Returns:
5373        A table expression.
5374    """
5375    if sql_path is None or isinstance(sql_path, Table):
5376        return sql_path
5377    if not isinstance(sql_path, str):
5378        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5379
5380    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5381    if table:
5382        for k, v in kwargs.items():
5383            table.set(k, v)
5384
5385    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:
5388def to_column(sql_path: str | Column, **kwargs) -> Column:
5389    """
5390    Create a column from a `[table].[column]` sql path. Schema is optional.
5391
5392    If a column is passed in then that column is returned.
5393
5394    Args:
5395        sql_path: `[table].[column]` string
5396    Returns:
5397        Table: A column expression
5398    """
5399    if sql_path is None or isinstance(sql_path, Column):
5400        return sql_path
5401    if not isinstance(sql_path, str):
5402        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5403    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):
5406def alias_(
5407    expression: ExpOrStr,
5408    alias: str | Identifier,
5409    table: bool | t.Sequence[str | Identifier] = False,
5410    quoted: t.Optional[bool] = None,
5411    dialect: DialectType = None,
5412    copy: bool = True,
5413    **opts,
5414):
5415    """Create an Alias expression.
5416
5417    Example:
5418        >>> alias_('foo', 'bar').sql()
5419        'foo AS bar'
5420
5421        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5422        '(SELECT 1, 2) AS bar(a, b)'
5423
5424    Args:
5425        expression: the SQL code strings to parse.
5426            If an Expression instance is passed, this is used as-is.
5427        alias: the alias name to use. If the name has
5428            special characters it is quoted.
5429        table: Whether or not to create a table alias, can also be a list of columns.
5430        quoted: whether or not to quote the alias
5431        dialect: the dialect used to parse the input expression.
5432        copy: Whether or not to copy the expression.
5433        **opts: other options to use to parse the input expressions.
5434
5435    Returns:
5436        Alias: the aliased expression
5437    """
5438    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5439    alias = to_identifier(alias, quoted=quoted)
5440
5441    if table:
5442        table_alias = TableAlias(this=alias)
5443        exp.set("alias", table_alias)
5444
5445        if not isinstance(table, bool):
5446            for column in table:
5447                table_alias.append("columns", to_identifier(column, quoted=quoted))
5448
5449        return exp
5450
5451    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5452    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5453    # for the complete Window expression.
5454    #
5455    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5456
5457    if "alias" in exp.arg_types and not isinstance(exp, Window):
5458        exp.set("alias", alias)
5459        return exp
5460    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:
5463def subquery(
5464    expression: ExpOrStr,
5465    alias: t.Optional[Identifier | str] = None,
5466    dialect: DialectType = None,
5467    **opts,
5468) -> Select:
5469    """
5470    Build a subquery expression.
5471
5472    Example:
5473        >>> subquery('select x from tbl', 'bar').select('x').sql()
5474        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5475
5476    Args:
5477        expression: the SQL code strings to parse.
5478            If an Expression instance is passed, this is used as-is.
5479        alias: the alias name to use.
5480        dialect: the dialect used to parse the input expression.
5481        **opts: other options to use to parse the input expressions.
5482
5483    Returns:
5484        A new Select instance with the subquery expression included.
5485    """
5486
5487    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5488    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:
5491def column(
5492    col: str | Identifier,
5493    table: t.Optional[str | Identifier] = None,
5494    db: t.Optional[str | Identifier] = None,
5495    catalog: t.Optional[str | Identifier] = None,
5496    quoted: t.Optional[bool] = None,
5497) -> Column:
5498    """
5499    Build a Column.
5500
5501    Args:
5502        col: Column name.
5503        table: Table name.
5504        db: Database name.
5505        catalog: Catalog name.
5506        quoted: Whether to force quotes on the column's identifiers.
5507
5508    Returns:
5509        The new Column instance.
5510    """
5511    return Column(
5512        this=to_identifier(col, quoted=quoted),
5513        table=to_identifier(table, quoted=quoted),
5514        db=to_identifier(db, quoted=quoted),
5515        catalog=to_identifier(catalog, quoted=quoted),
5516    )

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:
5519def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5520    """Cast an expression to a data type.
5521
5522    Example:
5523        >>> cast('x + 1', 'int').sql()
5524        'CAST(x + 1 AS INT)'
5525
5526    Args:
5527        expression: The expression to cast.
5528        to: The datatype to cast to.
5529
5530    Returns:
5531        The new Cast instance.
5532    """
5533    expression = maybe_parse(expression, **opts)
5534    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:
5537def table_(
5538    table: Identifier | str,
5539    db: t.Optional[Identifier | str] = None,
5540    catalog: t.Optional[Identifier | str] = None,
5541    quoted: t.Optional[bool] = None,
5542    alias: t.Optional[Identifier | str] = None,
5543) -> Table:
5544    """Build a Table.
5545
5546    Args:
5547        table: Table name.
5548        db: Database name.
5549        catalog: Catalog name.
5550        quote: Whether to force quotes on the table's identifiers.
5551        alias: Table's alias.
5552
5553    Returns:
5554        The new Table instance.
5555    """
5556    return Table(
5557        this=to_identifier(table, quoted=quoted),
5558        db=to_identifier(db, quoted=quoted),
5559        catalog=to_identifier(catalog, quoted=quoted),
5560        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5561    )

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:
5564def values(
5565    values: t.Iterable[t.Tuple[t.Any, ...]],
5566    alias: t.Optional[str] = None,
5567    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5568) -> Values:
5569    """Build VALUES statement.
5570
5571    Example:
5572        >>> values([(1, '2')]).sql()
5573        "VALUES (1, '2')"
5574
5575    Args:
5576        values: values statements that will be converted to SQL
5577        alias: optional alias
5578        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5579         If either are provided then an alias is also required.
5580
5581    Returns:
5582        Values: the Values expression object
5583    """
5584    if columns and not alias:
5585        raise ValueError("Alias is required when providing columns")
5586
5587    return Values(
5588        expressions=[convert(tup) for tup in values],
5589        alias=(
5590            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5591            if columns
5592            else (TableAlias(this=to_identifier(alias)) if alias else None)
5593        ),
5594    )

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:
5597def var(name: t.Optional[ExpOrStr]) -> Var:
5598    """Build a SQL variable.
5599
5600    Example:
5601        >>> repr(var('x'))
5602        '(VAR this: x)'
5603
5604        >>> repr(var(column('x', table='y')))
5605        '(VAR this: x)'
5606
5607    Args:
5608        name: The name of the var or an expression who's name will become the var.
5609
5610    Returns:
5611        The new variable node.
5612    """
5613    if not name:
5614        raise ValueError("Cannot convert empty name into var.")
5615
5616    if isinstance(name, Expression):
5617        name = name.name
5618    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:
5621def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5622    """Build ALTER TABLE... RENAME... expression
5623
5624    Args:
5625        old_name: The old name of the table
5626        new_name: The new name of the table
5627
5628    Returns:
5629        Alter table expression
5630    """
5631    old_table = to_table(old_name)
5632    new_table = to_table(new_name)
5633    return AlterTable(
5634        this=old_table,
5635        actions=[
5636            RenameTable(this=new_table),
5637        ],
5638    )

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:
5641def convert(value: t.Any, copy: bool = False) -> Expression:
5642    """Convert a python value into an expression object.
5643
5644    Raises an error if a conversion is not possible.
5645
5646    Args:
5647        value: A python object.
5648        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5649
5650    Returns:
5651        Expression: the equivalent expression object.
5652    """
5653    if isinstance(value, Expression):
5654        return _maybe_copy(value, copy)
5655    if isinstance(value, str):
5656        return Literal.string(value)
5657    if isinstance(value, bool):
5658        return Boolean(this=value)
5659    if value is None or (isinstance(value, float) and math.isnan(value)):
5660        return NULL
5661    if isinstance(value, numbers.Number):
5662        return Literal.number(value)
5663    if isinstance(value, datetime.datetime):
5664        datetime_literal = Literal.string(
5665            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5666        )
5667        return TimeStrToTime(this=datetime_literal)
5668    if isinstance(value, datetime.date):
5669        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5670        return DateStrToDate(this=date_literal)
5671    if isinstance(value, tuple):
5672        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5673    if isinstance(value, list):
5674        return Array(expressions=[convert(v, copy=copy) for v in value])
5675    if isinstance(value, dict):
5676        return Map(
5677            keys=[convert(k, copy=copy) for k in value],
5678            values=[convert(v, copy=copy) for v in value.values()],
5679        )
5680    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:
5683def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5684    """
5685    Replace children of an expression with the result of a lambda fun(child) -> exp.
5686    """
5687    for k, v in expression.args.items():
5688        is_list_arg = type(v) is list
5689
5690        child_nodes = v if is_list_arg else [v]
5691        new_child_nodes = []
5692
5693        for cn in child_nodes:
5694            if isinstance(cn, Expression):
5695                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5696                    new_child_nodes.append(child_node)
5697                    child_node.parent = expression
5698                    child_node.arg_key = k
5699            else:
5700                new_child_nodes.append(cn)
5701
5702        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]:
5705def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5706    """
5707    Return all table names referenced through columns in an expression.
5708
5709    Example:
5710        >>> import sqlglot
5711        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5712        ['a', 'c']
5713
5714    Args:
5715        expression: expression to find table names.
5716        exclude: a table name to exclude
5717
5718    Returns:
5719        A list of unique names.
5720    """
5721    return {
5722        table
5723        for table in (column.table for column in expression.find_all(Column))
5724        if table and table != exclude
5725    }

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, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None) -> str:
5728def table_name(table: Table | str, dialect: DialectType = None) -> str:
5729    """Get the full name of a table as a string.
5730
5731    Args:
5732        table: Table expression node or string.
5733        dialect: The dialect to generate the table name for.
5734
5735    Examples:
5736        >>> from sqlglot import exp, parse_one
5737        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5738        'a.b.c'
5739
5740    Returns:
5741        The table name.
5742    """
5743
5744    table = maybe_parse(table, into=Table)
5745
5746    if not table:
5747        raise ValueError(f"Cannot parse {table}")
5748
5749    return ".".join(
5750        part.sql(dialect=dialect) if not SAFE_IDENTIFIER_RE.match(part.name) else part.name
5751        for part in table.parts
5752    )

Get the full name of a table as a string.

Arguments:
  • table: Table expression node or string.
  • dialect: The dialect to generate the table name for.
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:
5755def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5756    """Replace all tables in expression according to the mapping.
5757
5758    Args:
5759        expression: expression node to be transformed and replaced.
5760        mapping: mapping of table names.
5761        copy: whether or not to copy the expression.
5762
5763    Examples:
5764        >>> from sqlglot import exp, parse_one
5765        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5766        'SELECT * FROM c'
5767
5768    Returns:
5769        The mapped expression.
5770    """
5771
5772    def _replace_tables(node: Expression) -> Expression:
5773        if isinstance(node, Table):
5774            new_name = mapping.get(table_name(node))
5775            if new_name:
5776                return to_table(
5777                    new_name,
5778                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5779                )
5780        return node
5781
5782    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:
5785def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5786    """Replace placeholders in an expression.
5787
5788    Args:
5789        expression: expression node to be transformed and replaced.
5790        args: positional names that will substitute unnamed placeholders in the given order.
5791        kwargs: keyword arguments that will substitute named placeholders.
5792
5793    Examples:
5794        >>> from sqlglot import exp, parse_one
5795        >>> replace_placeholders(
5796        ...     parse_one("select * from :tbl where ? = ?"),
5797        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5798        ... ).sql()
5799        "SELECT * FROM foo WHERE str_col = 'b'"
5800
5801    Returns:
5802        The mapped expression.
5803    """
5804
5805    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5806        if isinstance(node, Placeholder):
5807            if node.name:
5808                new_name = kwargs.get(node.name)
5809                if new_name:
5810                    return convert(new_name)
5811            else:
5812                try:
5813                    return convert(next(args))
5814                except StopIteration:
5815                    pass
5816        return node
5817
5818    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:
5821def expand(
5822    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5823) -> Expression:
5824    """Transforms an expression by expanding all referenced sources into subqueries.
5825
5826    Examples:
5827        >>> from sqlglot import parse_one
5828        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5829        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5830
5831        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5832        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5833
5834    Args:
5835        expression: The expression to expand.
5836        sources: A dictionary of name to Subqueryables.
5837        copy: Whether or not to copy the expression during transformation. Defaults to True.
5838
5839    Returns:
5840        The transformed expression.
5841    """
5842
5843    def _expand(node: Expression):
5844        if isinstance(node, Table):
5845            name = table_name(node)
5846            source = sources.get(name)
5847            if source:
5848                subquery = source.subquery(node.alias or name)
5849                subquery.comments = [f"source: {name}"]
5850                return subquery.transform(_expand, copy=False)
5851        return node
5852
5853    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:
5856def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5857    """
5858    Returns a Func expression.
5859
5860    Examples:
5861        >>> func("abs", 5).sql()
5862        'ABS(5)'
5863
5864        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5865        'CAST(5 AS DOUBLE)'
5866
5867    Args:
5868        name: the name of the function to build.
5869        args: the args used to instantiate the function of interest.
5870        dialect: the source dialect.
5871        kwargs: the kwargs used to instantiate the function of interest.
5872
5873    Note:
5874        The arguments `args` and `kwargs` are mutually exclusive.
5875
5876    Returns:
5877        An instance of the function of interest, or an anonymous function, if `name` doesn't
5878        correspond to an existing `sqlglot.expressions.Func` class.
5879    """
5880    if args and kwargs:
5881        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5882
5883    from sqlglot.dialects.dialect import Dialect
5884
5885    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5886    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5887
5888    parser = Dialect.get_or_raise(dialect)().parser()
5889    from_args_list = parser.FUNCTIONS.get(name.upper())
5890
5891    if from_args_list:
5892        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5893    else:
5894        kwargs = kwargs or {"expressions": converted}
5895        function = Anonymous(this=name, **kwargs)
5896
5897    for error_message in function.error_messages(converted):
5898        raise ValueError(error_message)
5899
5900    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:
5903def true() -> Boolean:
5904    """
5905    Returns a true Boolean expression.
5906    """
5907    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5910def false() -> Boolean:
5911    """
5912    Returns a false Boolean expression.
5913    """
5914    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5917def null() -> Null:
5918    """
5919    Returns a Null expression.
5920    """
5921    return Null()

Returns a Null expression.

TRUE = (BOOLEAN this: True)
FALSE = (BOOLEAN this: False)
NULL = (NULL )