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

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

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
Expression(**args: Any)
 90    def __init__(self, **args: t.Any):
 91        self.args: t.Dict[str, t.Any] = args
 92        self.parent: t.Optional[Expression] = None
 93        self.arg_key: t.Optional[str] = None
 94        self.comments: t.Optional[t.List[str]] = None
 95        self._type: t.Optional[DataType] = None
 96        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 97        self._hash: t.Optional[int] = None
 98
 99        for arg_key, value in self.args.items():
100            self._set_parent(arg_key, value)
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:
140    def text(self, key) -> str:
141        """
142        Returns a textual representation of the argument corresponding to "key". This can only be used
143        for args that are strings or leaf Expression instances, such as identifiers and literals.
144        """
145        field = self.args.get(key)
146        if isinstance(field, str):
147            return field
148        if isinstance(field, (Identifier, Literal, Var)):
149            return field.this
150        if isinstance(field, (Star, Null)):
151            return field.name
152        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.

alias_column_names: List[str]
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):
257    def copy(self):
258        """
259        Returns a deep copy of the expression.
260        """
261        new = deepcopy(self)
262        new.parent = self.parent
263        return new

Returns a deep copy of the expression.

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

Sets arg_key to value.

Arguments:
  • arg_key: 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]]:
318    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
319        """Yields the key and expression for all arguments, exploding list args."""
320        for k, vs in self.args.items():
321            if type(vs) is list:
322                for v in vs:
323                    if hasattr(v, "parent"):
324                        yield k, v
325            else:
326                if hasattr(vs, "parent"):
327                    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]:
329    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
330        """
331        Returns the first node in this tree which matches at least one of
332        the specified types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
337
338        Returns:
339            The node which matches the criteria or None if no such node was found.
340        """
341        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]:
343    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
344        """
345        Returns a generator object which visits all nodes in this tree and only
346        yields those that match at least one of the specified expression types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
351
352        Returns:
353            The generator object.
354        """
355        for expression, *_ in self.walk(bfs=bfs):
356            if isinstance(expression, expression_types):
357                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]:
359    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
360        """
361        Returns a nearest parent matching expression_types.
362
363        Args:
364            expression_types: the expression type(s) to match.
365
366        Returns:
367            The parent node.
368        """
369        ancestor = self.parent
370        while ancestor and not isinstance(ancestor, expression_types):
371            ancestor = ancestor.parent
372        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:
386    def root(self) -> Expression:
387        """
388        Returns the root expression of this tree.
389        """
390        expression = self
391        while expression.parent:
392            expression = expression.parent
393        return expression

Returns the root expression of this tree.

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

Returns the first non parenthesis child or self.

def unalias(self):
458    def unalias(self):
459        """
460        Returns the inner expression if this is an Alias.
461        """
462        if isinstance(self, Alias):
463            return self.this
464        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
466    def unnest_operands(self):
467        """
468        Returns unnested operands as a tuple.
469        """
470        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
472    def flatten(self, unnest=True):
473        """
474        Returns a generator which yields child nodes who's parents are the same class.
475
476        A AND B AND C -> [A, B, C]
477        """
478        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
479            if not type(node) is self.__class__:
480                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:
488    def sql(self, dialect: DialectType = None, **opts) -> str:
489        """
490        Returns SQL string representation of this tree.
491
492        Args:
493            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
494            opts: other `sqlglot.generator.Generator` options.
495
496        Returns:
497            The SQL string.
498        """
499        from sqlglot.dialects import Dialect
500
501        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):
527    def transform(self, fun, *args, copy=True, **kwargs):
528        """
529        Recursively visits all tree nodes (excluding already transformed ones)
530        and applies the given transformation function to each node.
531
532        Args:
533            fun (function): a function which takes a node as an argument and returns a
534                new transformed node or the same node without modifications. If the function
535                returns None, then the corresponding node will be removed from the syntax tree.
536            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
537                modified in place.
538
539        Returns:
540            The transformed tree.
541        """
542        node = self.copy() if copy else self
543        new_node = fun(node, *args, **kwargs)
544
545        if new_node is None or not isinstance(new_node, Expression):
546            return new_node
547        if new_node is not node:
548            new_node.parent = node.parent
549            return new_node
550
551        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
552        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):
562    def replace(self, expression):
563        """
564        Swap out this expression with a new expression.
565
566        For example::
567
568            >>> tree = Select().select("x").from_("tbl")
569            >>> tree.find(Column).replace(Column(this="y"))
570            (COLUMN this: y)
571            >>> tree.sql()
572            'SELECT y FROM tbl'
573
574        Args:
575            expression: new node
576
577        Returns:
578            The new expression or expressions.
579        """
580        if not self.parent:
581            return expression
582
583        parent = self.parent
584        self.parent = None
585
586        replace_children(parent, lambda child: expression if child is self else child)
587        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:
589    def pop(self: E) -> E:
590        """
591        Remove this expression from its AST.
592
593        Returns:
594            The popped expression.
595        """
596        self.replace(None)
597        return self

Remove this expression from its AST.

Returns:

The popped expression.

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

Dump this Expression to a JSON-serializable dict.

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

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

key = 'predicate'
class DerivedTable(Expression):
893class DerivedTable(Expression):
894    @property
895    def selects(self) -> t.List[Expression]:
896        return self.this.selects if isinstance(self.this, Subqueryable) else []
897
898    @property
899    def named_selects(self) -> t.List[str]:
900        return [select.output_name for select in self.selects]
named_selects: List[str]
key = 'derivedtable'
class Unionable(Expression):
903class Unionable(Expression):
904    def union(
905        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
906    ) -> Unionable:
907        """
908        Builds a UNION expression.
909
910        Example:
911            >>> import sqlglot
912            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
913            'SELECT * FROM foo UNION SELECT * FROM bla'
914
915        Args:
916            expression: the SQL code string.
917                If an `Expression` instance is passed, it will be used as-is.
918            distinct: set the DISTINCT flag if and only if this is true.
919            dialect: the dialect used to parse the input expression.
920            opts: other options to use to parse the input expressions.
921
922        Returns:
923            The new Union expression.
924        """
925        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
926
927    def intersect(
928        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
929    ) -> Unionable:
930        """
931        Builds an INTERSECT expression.
932
933        Example:
934            >>> import sqlglot
935            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
936            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
937
938        Args:
939            expression: the SQL code string.
940                If an `Expression` instance is passed, it will be used as-is.
941            distinct: set the DISTINCT flag if and only if this is true.
942            dialect: the dialect used to parse the input expression.
943            opts: other options to use to parse the input expressions.
944
945        Returns:
946            The new Intersect expression.
947        """
948        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
949
950    def except_(
951        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
952    ) -> Unionable:
953        """
954        Builds an EXCEPT expression.
955
956        Example:
957            >>> import sqlglot
958            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
959            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
960
961        Args:
962            expression: the SQL code string.
963                If an `Expression` instance is passed, it will be used as-is.
964            distinct: set the DISTINCT flag if and only if this is true.
965            dialect: the dialect used to parse the input expression.
966            opts: other options to use to parse the input expressions.
967
968        Returns:
969            The new Except expression.
970        """
971        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:
904    def union(
905        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
906    ) -> Unionable:
907        """
908        Builds a UNION expression.
909
910        Example:
911            >>> import sqlglot
912            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
913            'SELECT * FROM foo UNION SELECT * FROM bla'
914
915        Args:
916            expression: the SQL code string.
917                If an `Expression` instance is passed, it will be used as-is.
918            distinct: set the DISTINCT flag if and only if this is true.
919            dialect: the dialect used to parse the input expression.
920            opts: other options to use to parse the input expressions.
921
922        Returns:
923            The new Union expression.
924        """
925        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:
927    def intersect(
928        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
929    ) -> Unionable:
930        """
931        Builds an INTERSECT expression.
932
933        Example:
934            >>> import sqlglot
935            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
936            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
937
938        Args:
939            expression: the SQL code string.
940                If an `Expression` instance is passed, it will be used as-is.
941            distinct: set the DISTINCT flag if and only if this is true.
942            dialect: the dialect used to parse the input expression.
943            opts: other options to use to parse the input expressions.
944
945        Returns:
946            The new Intersect expression.
947        """
948        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:
950    def except_(
951        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
952    ) -> Unionable:
953        """
954        Builds an EXCEPT expression.
955
956        Example:
957            >>> import sqlglot
958            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
959            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
960
961        Args:
962            expression: the SQL code string.
963                If an `Expression` instance is passed, it will be used as-is.
964            distinct: set the DISTINCT flag if and only if this is true.
965            dialect: the dialect used to parse the input expression.
966            opts: other options to use to parse the input expressions.
967
968        Returns:
969            The new Except expression.
970        """
971        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):
974class UDTF(DerivedTable, Unionable):
975    @property
976    def selects(self) -> t.List[Expression]:
977        alias = self.args.get("alias")
978        return alias.columns if alias else []
key = 'udtf'
class Cache(Expression):
981class Cache(Expression):
982    arg_types = {
983        "with": False,
984        "this": True,
985        "lazy": False,
986        "options": False,
987        "expression": False,
988    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
991class Uncache(Expression):
992    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class DDL(Expression):
 995class DDL(Expression):
 996    @property
 997    def ctes(self):
 998        with_ = self.args.get("with")
 999        if not with_:
1000            return []
1001        return with_.expressions
1002
1003    @property
1004    def named_selects(self) -> t.List[str]:
1005        if isinstance(self.expression, Subqueryable):
1006            return self.expression.named_selects
1007        return []
1008
1009    @property
1010    def selects(self) -> t.List[Expression]:
1011        if isinstance(self.expression, Subqueryable):
1012            return self.expression.selects
1013        return []
ctes
named_selects: List[str]
key = 'ddl'
class Create(DDL):
1016class Create(DDL):
1017    arg_types = {
1018        "with": False,
1019        "this": True,
1020        "kind": True,
1021        "expression": False,
1022        "exists": False,
1023        "properties": False,
1024        "replace": False,
1025        "unique": False,
1026        "indexes": False,
1027        "no_schema_binding": False,
1028        "begin": False,
1029        "clone": False,
1030    }
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):
1034class Clone(Expression):
1035    arg_types = {
1036        "this": True,
1037        "when": False,
1038        "kind": False,
1039        "expression": False,
1040    }
arg_types = {'this': True, 'when': False, 'kind': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1043class Describe(Expression):
1044    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'describe'
class Pragma(Expression):
1047class Pragma(Expression):
1048    pass
key = 'pragma'
class Set(Expression):
1051class Set(Expression):
1052    arg_types = {"expressions": False, "unset": False, "tag": False}
arg_types = {'expressions': False, 'unset': False, 'tag': False}
key = 'set'
class SetItem(Expression):
1055class SetItem(Expression):
1056    arg_types = {
1057        "this": False,
1058        "expressions": False,
1059        "kind": False,
1060        "collate": False,  # MySQL SET NAMES statement
1061        "global": False,
1062    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1065class Show(Expression):
1066    arg_types = {
1067        "this": True,
1068        "target": False,
1069        "offset": False,
1070        "limit": False,
1071        "like": False,
1072        "where": False,
1073        "db": False,
1074        "full": False,
1075        "mutex": False,
1076        "query": False,
1077        "channel": False,
1078        "global": False,
1079        "log": False,
1080        "position": False,
1081        "types": False,
1082    }
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):
1085class UserDefinedFunction(Expression):
1086    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1089class CharacterSet(Expression):
1090    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1093class With(Expression):
1094    arg_types = {"expressions": True, "recursive": False}
1095
1096    @property
1097    def recursive(self) -> bool:
1098        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1101class WithinGroup(Expression):
1102    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1105class CTE(DerivedTable):
1106    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1109class TableAlias(Expression):
1110    arg_types = {"this": False, "columns": False}
1111
1112    @property
1113    def columns(self):
1114        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1117class BitString(Condition):
1118    pass
key = 'bitstring'
class HexString(Condition):
1121class HexString(Condition):
1122    pass
key = 'hexstring'
class ByteString(Condition):
1125class ByteString(Condition):
1126    pass
key = 'bytestring'
class RawString(Condition):
1129class RawString(Condition):
1130    pass
key = 'rawstring'
class Column(Condition):
1133class Column(Condition):
1134    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1135
1136    @property
1137    def table(self) -> str:
1138        return self.text("table")
1139
1140    @property
1141    def db(self) -> str:
1142        return self.text("db")
1143
1144    @property
1145    def catalog(self) -> str:
1146        return self.text("catalog")
1147
1148    @property
1149    def output_name(self) -> str:
1150        return self.name
1151
1152    @property
1153    def parts(self) -> t.List[Identifier]:
1154        """Return the parts of a column in order catalog, db, table, name."""
1155        return [
1156            t.cast(Identifier, self.args[part])
1157            for part in ("catalog", "db", "table", "this")
1158            if self.args.get(part)
1159        ]
1160
1161    def to_dot(self) -> Dot:
1162        """Converts the column into a dot expression."""
1163        parts = self.parts
1164        parent = self.parent
1165
1166        while parent:
1167            if isinstance(parent, Dot):
1168                parts.append(parent.expression)
1169            parent = parent.parent
1170
1171        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:
1161    def to_dot(self) -> Dot:
1162        """Converts the column into a dot expression."""
1163        parts = self.parts
1164        parent = self.parent
1165
1166        while parent:
1167            if isinstance(parent, Dot):
1168                parts.append(parent.expression)
1169            parent = parent.parent
1170
1171        return Dot.build(parts)

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1174class ColumnPosition(Expression):
1175    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1178class ColumnDef(Expression):
1179    arg_types = {
1180        "this": True,
1181        "kind": False,
1182        "constraints": False,
1183        "exists": False,
1184        "position": False,
1185    }
1186
1187    @property
1188    def constraints(self) -> t.List[ColumnConstraint]:
1189        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
key = 'columndef'
class AlterColumn(Expression):
1192class AlterColumn(Expression):
1193    arg_types = {
1194        "this": True,
1195        "dtype": False,
1196        "collate": False,
1197        "using": False,
1198        "default": False,
1199        "drop": False,
1200    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1203class RenameTable(Expression):
1204    pass
key = 'renametable'
class Comment(Expression):
1207class Comment(Expression):
1208    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):
1212class MergeTreeTTLAction(Expression):
1213    arg_types = {
1214        "this": True,
1215        "delete": False,
1216        "recompress": False,
1217        "to_disk": False,
1218        "to_volume": False,
1219    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1223class MergeTreeTTL(Expression):
1224    arg_types = {
1225        "expressions": True,
1226        "where": False,
1227        "group": False,
1228        "aggregates": False,
1229    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class IndexConstraintOption(Expression):
1233class IndexConstraintOption(Expression):
1234    arg_types = {
1235        "key_block_size": False,
1236        "using": False,
1237        "parser": False,
1238        "comment": False,
1239        "visible": False,
1240        "engine_attr": False,
1241        "secondary_engine_attr": False,
1242    }
arg_types = {'key_block_size': False, 'using': False, 'parser': False, 'comment': False, 'visible': False, 'engine_attr': False, 'secondary_engine_attr': False}
key = 'indexconstraintoption'
class ColumnConstraint(Expression):
1245class ColumnConstraint(Expression):
1246    arg_types = {"this": False, "kind": True}
1247
1248    @property
1249    def kind(self) -> ColumnConstraintKind:
1250        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1253class ColumnConstraintKind(Expression):
1254    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1257class AutoIncrementColumnConstraint(ColumnConstraintKind):
1258    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1261class CaseSpecificColumnConstraint(ColumnConstraintKind):
1262    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1265class CharacterSetColumnConstraint(ColumnConstraintKind):
1266    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1269class CheckColumnConstraint(ColumnConstraintKind):
1270    pass
key = 'checkcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1273class CollateColumnConstraint(ColumnConstraintKind):
1274    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1277class CommentColumnConstraint(ColumnConstraintKind):
1278    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1281class CompressColumnConstraint(ColumnConstraintKind):
1282    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1285class DateFormatColumnConstraint(ColumnConstraintKind):
1286    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1289class DefaultColumnConstraint(ColumnConstraintKind):
1290    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1293class EncodeColumnConstraint(ColumnConstraintKind):
1294    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1297class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1298    # this: True -> ALWAYS, this: False -> BY DEFAULT
1299    arg_types = {
1300        "this": False,
1301        "expression": False,
1302        "on_null": False,
1303        "start": False,
1304        "increment": False,
1305        "minvalue": False,
1306        "maxvalue": False,
1307        "cycle": False,
1308    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class IndexColumnConstraint(ColumnConstraintKind):
1312class IndexColumnConstraint(ColumnConstraintKind):
1313    arg_types = {"this": False, "schema": True, "kind": False, "type": False, "options": False}
arg_types = {'this': False, 'schema': True, 'kind': False, 'type': False, 'options': False}
key = 'indexcolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1316class InlineLengthColumnConstraint(ColumnConstraintKind):
1317    pass
key = 'inlinelengthcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1320class NotNullColumnConstraint(ColumnConstraintKind):
1321    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1325class OnUpdateColumnConstraint(ColumnConstraintKind):
1326    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1329class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1330    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1333class TitleColumnConstraint(ColumnConstraintKind):
1334    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1337class UniqueColumnConstraint(ColumnConstraintKind):
1338    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1341class UppercaseColumnConstraint(ColumnConstraintKind):
1342    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1345class PathColumnConstraint(ColumnConstraintKind):
1346    pass
key = 'pathcolumnconstraint'
class Constraint(Expression):
1349class Constraint(Expression):
1350    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1353class Delete(Expression):
1354    arg_types = {
1355        "with": False,
1356        "this": False,
1357        "using": False,
1358        "where": False,
1359        "returning": False,
1360        "limit": False,
1361        "tables": False,  # Multiple-Table Syntax (MySQL)
1362    }
1363
1364    def delete(
1365        self,
1366        table: ExpOrStr,
1367        dialect: DialectType = None,
1368        copy: bool = True,
1369        **opts,
1370    ) -> Delete:
1371        """
1372        Create a DELETE expression or replace the table on an existing DELETE expression.
1373
1374        Example:
1375            >>> delete("tbl").sql()
1376            'DELETE FROM tbl'
1377
1378        Args:
1379            table: the table from which to delete.
1380            dialect: the dialect used to parse the input expression.
1381            copy: if `False`, modify this expression instance in-place.
1382            opts: other options to use to parse the input expressions.
1383
1384        Returns:
1385            Delete: the modified expression.
1386        """
1387        return _apply_builder(
1388            expression=table,
1389            instance=self,
1390            arg="this",
1391            dialect=dialect,
1392            into=Table,
1393            copy=copy,
1394            **opts,
1395        )
1396
1397    def where(
1398        self,
1399        *expressions: t.Optional[ExpOrStr],
1400        append: bool = True,
1401        dialect: DialectType = None,
1402        copy: bool = True,
1403        **opts,
1404    ) -> Delete:
1405        """
1406        Append to or set the WHERE expressions.
1407
1408        Example:
1409            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1410            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1411
1412        Args:
1413            *expressions: the SQL code strings to parse.
1414                If an `Expression` instance is passed, it will be used as-is.
1415                Multiple expressions are combined with an AND operator.
1416            append: if `True`, AND the new expressions to any existing expression.
1417                Otherwise, this resets the expression.
1418            dialect: the dialect used to parse the input expressions.
1419            copy: if `False`, modify this expression instance in-place.
1420            opts: other options to use to parse the input expressions.
1421
1422        Returns:
1423            Delete: the modified expression.
1424        """
1425        return _apply_conjunction_builder(
1426            *expressions,
1427            instance=self,
1428            arg="where",
1429            append=append,
1430            into=Where,
1431            dialect=dialect,
1432            copy=copy,
1433            **opts,
1434        )
1435
1436    def returning(
1437        self,
1438        expression: ExpOrStr,
1439        dialect: DialectType = None,
1440        copy: bool = True,
1441        **opts,
1442    ) -> Delete:
1443        """
1444        Set the RETURNING expression. Not supported by all dialects.
1445
1446        Example:
1447            >>> delete("tbl").returning("*", dialect="postgres").sql()
1448            'DELETE FROM tbl RETURNING *'
1449
1450        Args:
1451            expression: the SQL code strings to parse.
1452                If an `Expression` instance is passed, it will be used as-is.
1453            dialect: the dialect used to parse the input expressions.
1454            copy: if `False`, modify this expression instance in-place.
1455            opts: other options to use to parse the input expressions.
1456
1457        Returns:
1458            Delete: the modified expression.
1459        """
1460        return _apply_builder(
1461            expression=expression,
1462            instance=self,
1463            arg="returning",
1464            prefix="RETURNING",
1465            dialect=dialect,
1466            copy=copy,
1467            into=Returning,
1468            **opts,
1469        )
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:
1364    def delete(
1365        self,
1366        table: ExpOrStr,
1367        dialect: DialectType = None,
1368        copy: bool = True,
1369        **opts,
1370    ) -> Delete:
1371        """
1372        Create a DELETE expression or replace the table on an existing DELETE expression.
1373
1374        Example:
1375            >>> delete("tbl").sql()
1376            'DELETE FROM tbl'
1377
1378        Args:
1379            table: the table from which to delete.
1380            dialect: the dialect used to parse the input expression.
1381            copy: if `False`, modify this expression instance in-place.
1382            opts: other options to use to parse the input expressions.
1383
1384        Returns:
1385            Delete: the modified expression.
1386        """
1387        return _apply_builder(
1388            expression=table,
1389            instance=self,
1390            arg="this",
1391            dialect=dialect,
1392            into=Table,
1393            copy=copy,
1394            **opts,
1395        )

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:
1397    def where(
1398        self,
1399        *expressions: t.Optional[ExpOrStr],
1400        append: bool = True,
1401        dialect: DialectType = None,
1402        copy: bool = True,
1403        **opts,
1404    ) -> Delete:
1405        """
1406        Append to or set the WHERE expressions.
1407
1408        Example:
1409            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1410            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1411
1412        Args:
1413            *expressions: the SQL code strings to parse.
1414                If an `Expression` instance is passed, it will be used as-is.
1415                Multiple expressions are combined with an AND operator.
1416            append: if `True`, AND the new expressions to any existing expression.
1417                Otherwise, this resets the expression.
1418            dialect: the dialect used to parse the input expressions.
1419            copy: if `False`, modify this expression instance in-place.
1420            opts: other options to use to parse the input expressions.
1421
1422        Returns:
1423            Delete: the modified expression.
1424        """
1425        return _apply_conjunction_builder(
1426            *expressions,
1427            instance=self,
1428            arg="where",
1429            append=append,
1430            into=Where,
1431            dialect=dialect,
1432            copy=copy,
1433            **opts,
1434        )

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:
1436    def returning(
1437        self,
1438        expression: ExpOrStr,
1439        dialect: DialectType = None,
1440        copy: bool = True,
1441        **opts,
1442    ) -> Delete:
1443        """
1444        Set the RETURNING expression. Not supported by all dialects.
1445
1446        Example:
1447            >>> delete("tbl").returning("*", dialect="postgres").sql()
1448            'DELETE FROM tbl RETURNING *'
1449
1450        Args:
1451            expression: the SQL code strings to parse.
1452                If an `Expression` instance is passed, it will be used as-is.
1453            dialect: the dialect used to parse the input expressions.
1454            copy: if `False`, modify this expression instance in-place.
1455            opts: other options to use to parse the input expressions.
1456
1457        Returns:
1458            Delete: the modified expression.
1459        """
1460        return _apply_builder(
1461            expression=expression,
1462            instance=self,
1463            arg="returning",
1464            prefix="RETURNING",
1465            dialect=dialect,
1466            copy=copy,
1467            into=Returning,
1468            **opts,
1469        )

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):
1472class Drop(Expression):
1473    arg_types = {
1474        "this": False,
1475        "kind": False,
1476        "exists": False,
1477        "temporary": False,
1478        "materialized": False,
1479        "cascade": False,
1480        "constraints": False,
1481        "purge": False,
1482    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1485class Filter(Expression):
1486    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1489class Check(Expression):
1490    pass
key = 'check'
class Directory(Expression):
1493class Directory(Expression):
1494    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1495    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1498class ForeignKey(Expression):
1499    arg_types = {
1500        "expressions": True,
1501        "reference": False,
1502        "delete": False,
1503        "update": False,
1504    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1507class PrimaryKey(Expression):
1508    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1513class Into(Expression):
1514    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1517class From(Expression):
1518    @property
1519    def name(self) -> str:
1520        return self.this.name
1521
1522    @property
1523    def alias_or_name(self) -> str:
1524        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1527class Having(Expression):
1528    pass
key = 'having'
class Hint(Expression):
1531class Hint(Expression):
1532    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1535class JoinHint(Expression):
1536    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1539class Identifier(Expression):
1540    arg_types = {"this": True, "quoted": False, "global": False, "temporary": False}
1541
1542    @property
1543    def quoted(self) -> bool:
1544        return bool(self.args.get("quoted"))
1545
1546    @property
1547    def hashable_args(self) -> t.Any:
1548        return (self.this, self.quoted)
1549
1550    @property
1551    def output_name(self) -> str:
1552        return self.name
arg_types = {'this': True, 'quoted': False, 'global': False, 'temporary': 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):
1555class Index(Expression):
1556    arg_types = {
1557        "this": False,
1558        "table": False,
1559        "using": False,
1560        "where": False,
1561        "columns": False,
1562        "unique": False,
1563        "primary": False,
1564        "amp": False,  # teradata
1565        "partition_by": False,  # teradata
1566    }
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(DDL):
1569class Insert(DDL):
1570    arg_types = {
1571        "with": False,
1572        "this": True,
1573        "expression": False,
1574        "conflict": False,
1575        "returning": False,
1576        "overwrite": False,
1577        "exists": False,
1578        "partition": False,
1579        "alternative": False,
1580        "where": False,
1581        "ignore": False,
1582    }
1583
1584    def with_(
1585        self,
1586        alias: ExpOrStr,
1587        as_: ExpOrStr,
1588        recursive: t.Optional[bool] = None,
1589        append: bool = True,
1590        dialect: DialectType = None,
1591        copy: bool = True,
1592        **opts,
1593    ) -> Insert:
1594        """
1595        Append to or set the common table expressions.
1596
1597        Example:
1598            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1599            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1600
1601        Args:
1602            alias: the SQL code string to parse as the table name.
1603                If an `Expression` instance is passed, this is used as-is.
1604            as_: the SQL code string to parse as the table expression.
1605                If an `Expression` instance is passed, it will be used as-is.
1606            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1607            append: if `True`, add to any existing expressions.
1608                Otherwise, this resets the expressions.
1609            dialect: the dialect used to parse the input expression.
1610            copy: if `False`, modify this expression instance in-place.
1611            opts: other options to use to parse the input expressions.
1612
1613        Returns:
1614            The modified expression.
1615        """
1616        return _apply_cte_builder(
1617            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1618        )
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:
1584    def with_(
1585        self,
1586        alias: ExpOrStr,
1587        as_: ExpOrStr,
1588        recursive: t.Optional[bool] = None,
1589        append: bool = True,
1590        dialect: DialectType = None,
1591        copy: bool = True,
1592        **opts,
1593    ) -> Insert:
1594        """
1595        Append to or set the common table expressions.
1596
1597        Example:
1598            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1599            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1600
1601        Args:
1602            alias: the SQL code string to parse as the table name.
1603                If an `Expression` instance is passed, this is used as-is.
1604            as_: the SQL code string to parse as the table expression.
1605                If an `Expression` instance is passed, it will be used as-is.
1606            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1607            append: if `True`, add to any existing expressions.
1608                Otherwise, this resets the expressions.
1609            dialect: the dialect used to parse the input expression.
1610            copy: if `False`, modify this expression instance in-place.
1611            opts: other options to use to parse the input expressions.
1612
1613        Returns:
1614            The modified expression.
1615        """
1616        return _apply_cte_builder(
1617            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1618        )

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):
1621class OnConflict(Expression):
1622    arg_types = {
1623        "duplicate": False,
1624        "expressions": False,
1625        "nothing": False,
1626        "key": False,
1627        "constraint": False,
1628    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1631class Returning(Expression):
1632    arg_types = {"expressions": True, "into": False}
arg_types = {'expressions': True, 'into': False}
key = 'returning'
class Introducer(Expression):
1636class Introducer(Expression):
1637    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1641class National(Expression):
1642    pass
key = 'national'
class LoadData(Expression):
1645class LoadData(Expression):
1646    arg_types = {
1647        "this": True,
1648        "local": False,
1649        "overwrite": False,
1650        "inpath": True,
1651        "partition": False,
1652        "input_format": False,
1653        "serde": False,
1654    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1657class Partition(Expression):
1658    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1661class Fetch(Expression):
1662    arg_types = {
1663        "direction": False,
1664        "count": False,
1665        "percent": False,
1666        "with_ties": False,
1667    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1670class Group(Expression):
1671    arg_types = {
1672        "expressions": False,
1673        "grouping_sets": False,
1674        "cube": False,
1675        "rollup": False,
1676        "totals": False,
1677        "all": False,
1678    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False, 'all': False}
key = 'group'
class Lambda(Expression):
1681class Lambda(Expression):
1682    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1685class Limit(Expression):
1686    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1689class Literal(Condition):
1690    arg_types = {"this": True, "is_string": True}
1691
1692    @property
1693    def hashable_args(self) -> t.Any:
1694        return (self.this, self.args.get("is_string"))
1695
1696    @classmethod
1697    def number(cls, number) -> Literal:
1698        return cls(this=str(number), is_string=False)
1699
1700    @classmethod
1701    def string(cls, string) -> Literal:
1702        return cls(this=str(string), is_string=True)
1703
1704    @property
1705    def output_name(self) -> str:
1706        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1696    @classmethod
1697    def number(cls, number) -> Literal:
1698        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1700    @classmethod
1701    def string(cls, string) -> Literal:
1702        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):
1709class Join(Expression):
1710    arg_types = {
1711        "this": True,
1712        "on": False,
1713        "side": False,
1714        "kind": False,
1715        "using": False,
1716        "method": False,
1717        "global": False,
1718        "hint": False,
1719    }
1720
1721    @property
1722    def method(self) -> str:
1723        return self.text("method").upper()
1724
1725    @property
1726    def kind(self) -> str:
1727        return self.text("kind").upper()
1728
1729    @property
1730    def side(self) -> str:
1731        return self.text("side").upper()
1732
1733    @property
1734    def hint(self) -> str:
1735        return self.text("hint").upper()
1736
1737    @property
1738    def alias_or_name(self) -> str:
1739        return self.this.alias_or_name
1740
1741    def on(
1742        self,
1743        *expressions: t.Optional[ExpOrStr],
1744        append: bool = True,
1745        dialect: DialectType = None,
1746        copy: bool = True,
1747        **opts,
1748    ) -> Join:
1749        """
1750        Append to or set the ON expressions.
1751
1752        Example:
1753            >>> import sqlglot
1754            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1755            'JOIN x ON y = 1'
1756
1757        Args:
1758            *expressions: the SQL code strings to parse.
1759                If an `Expression` instance is passed, it will be used as-is.
1760                Multiple expressions are combined with an AND operator.
1761            append: if `True`, AND the new expressions to any existing expression.
1762                Otherwise, this resets the expression.
1763            dialect: the dialect used to parse the input expressions.
1764            copy: if `False`, modify this expression instance in-place.
1765            opts: other options to use to parse the input expressions.
1766
1767        Returns:
1768            The modified Join expression.
1769        """
1770        join = _apply_conjunction_builder(
1771            *expressions,
1772            instance=self,
1773            arg="on",
1774            append=append,
1775            dialect=dialect,
1776            copy=copy,
1777            **opts,
1778        )
1779
1780        if join.kind == "CROSS":
1781            join.set("kind", None)
1782
1783        return join
1784
1785    def using(
1786        self,
1787        *expressions: t.Optional[ExpOrStr],
1788        append: bool = True,
1789        dialect: DialectType = None,
1790        copy: bool = True,
1791        **opts,
1792    ) -> Join:
1793        """
1794        Append to or set the USING expressions.
1795
1796        Example:
1797            >>> import sqlglot
1798            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1799            'JOIN x USING (foo, bla)'
1800
1801        Args:
1802            *expressions: the SQL code strings to parse.
1803                If an `Expression` instance is passed, it will be used as-is.
1804            append: if `True`, concatenate the new expressions to the existing "using" list.
1805                Otherwise, this resets the expression.
1806            dialect: the dialect used to parse the input expressions.
1807            copy: if `False`, modify this expression instance in-place.
1808            opts: other options to use to parse the input expressions.
1809
1810        Returns:
1811            The modified Join expression.
1812        """
1813        join = _apply_list_builder(
1814            *expressions,
1815            instance=self,
1816            arg="using",
1817            append=append,
1818            dialect=dialect,
1819            copy=copy,
1820            **opts,
1821        )
1822
1823        if join.kind == "CROSS":
1824            join.set("kind", None)
1825
1826        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:
1741    def on(
1742        self,
1743        *expressions: t.Optional[ExpOrStr],
1744        append: bool = True,
1745        dialect: DialectType = None,
1746        copy: bool = True,
1747        **opts,
1748    ) -> Join:
1749        """
1750        Append to or set the ON expressions.
1751
1752        Example:
1753            >>> import sqlglot
1754            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1755            'JOIN x ON y = 1'
1756
1757        Args:
1758            *expressions: the SQL code strings to parse.
1759                If an `Expression` instance is passed, it will be used as-is.
1760                Multiple expressions are combined with an AND operator.
1761            append: if `True`, AND the new expressions to any existing expression.
1762                Otherwise, this resets the expression.
1763            dialect: the dialect used to parse the input expressions.
1764            copy: if `False`, modify this expression instance in-place.
1765            opts: other options to use to parse the input expressions.
1766
1767        Returns:
1768            The modified Join expression.
1769        """
1770        join = _apply_conjunction_builder(
1771            *expressions,
1772            instance=self,
1773            arg="on",
1774            append=append,
1775            dialect=dialect,
1776            copy=copy,
1777            **opts,
1778        )
1779
1780        if join.kind == "CROSS":
1781            join.set("kind", None)
1782
1783        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:
1785    def using(
1786        self,
1787        *expressions: t.Optional[ExpOrStr],
1788        append: bool = True,
1789        dialect: DialectType = None,
1790        copy: bool = True,
1791        **opts,
1792    ) -> Join:
1793        """
1794        Append to or set the USING expressions.
1795
1796        Example:
1797            >>> import sqlglot
1798            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1799            'JOIN x USING (foo, bla)'
1800
1801        Args:
1802            *expressions: the SQL code strings to parse.
1803                If an `Expression` instance is passed, it will be used as-is.
1804            append: if `True`, concatenate the new expressions to the existing "using" list.
1805                Otherwise, this resets the expression.
1806            dialect: the dialect used to parse the input expressions.
1807            copy: if `False`, modify this expression instance in-place.
1808            opts: other options to use to parse the input expressions.
1809
1810        Returns:
1811            The modified Join expression.
1812        """
1813        join = _apply_list_builder(
1814            *expressions,
1815            instance=self,
1816            arg="using",
1817            append=append,
1818            dialect=dialect,
1819            copy=copy,
1820            **opts,
1821        )
1822
1823        if join.kind == "CROSS":
1824            join.set("kind", None)
1825
1826        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):
1829class Lateral(UDTF):
1830    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):
1833class MatchRecognize(Expression):
1834    arg_types = {
1835        "partition_by": False,
1836        "order": False,
1837        "measures": False,
1838        "rows": False,
1839        "after": False,
1840        "pattern": False,
1841        "define": False,
1842        "alias": False,
1843    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1848class Final(Expression):
1849    pass
key = 'final'
class Offset(Expression):
1852class Offset(Expression):
1853    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1856class Order(Expression):
1857    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1862class Cluster(Order):
1863    pass
key = 'cluster'
class Distribute(Order):
1866class Distribute(Order):
1867    pass
key = 'distribute'
class Sort(Order):
1870class Sort(Order):
1871    pass
key = 'sort'
class Ordered(Expression):
1874class Ordered(Expression):
1875    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1878class Property(Expression):
1879    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1882class AlgorithmProperty(Property):
1883    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1886class AutoIncrementProperty(Property):
1887    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1890class BlockCompressionProperty(Property):
1891    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):
1894class CharacterSetProperty(Property):
1895    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1898class ChecksumProperty(Property):
1899    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1902class CollateProperty(Property):
1903    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1906class CopyGrantsProperty(Property):
1907    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1910class DataBlocksizeProperty(Property):
1911    arg_types = {
1912        "size": False,
1913        "units": False,
1914        "minimum": False,
1915        "maximum": False,
1916        "default": False,
1917    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1920class DefinerProperty(Property):
1921    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1924class DistKeyProperty(Property):
1925    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1928class DistStyleProperty(Property):
1929    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1932class EngineProperty(Property):
1933    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class HeapProperty(Property):
1936class HeapProperty(Property):
1937    arg_types = {}
arg_types = {}
key = 'heapproperty'
class ToTableProperty(Property):
1940class ToTableProperty(Property):
1941    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1944class ExecuteAsProperty(Property):
1945    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1948class ExternalProperty(Property):
1949    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1952class FallbackProperty(Property):
1953    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1956class FileFormatProperty(Property):
1957    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1960class FreespaceProperty(Property):
1961    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1964class InputOutputFormat(Expression):
1965    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1968class IsolatedLoadingProperty(Property):
1969    arg_types = {
1970        "no": True,
1971        "concurrent": True,
1972        "for_all": True,
1973        "for_insert": True,
1974        "for_none": True,
1975    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1978class JournalProperty(Property):
1979    arg_types = {
1980        "no": False,
1981        "dual": False,
1982        "before": False,
1983        "local": False,
1984        "after": False,
1985    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1988class LanguageProperty(Property):
1989    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class ClusteredByProperty(Property):
1993class ClusteredByProperty(Property):
1994    arg_types = {"expressions": True, "sorted_by": False, "buckets": True}
arg_types = {'expressions': True, 'sorted_by': False, 'buckets': True}
key = 'clusteredbyproperty'
class DictProperty(Property):
1997class DictProperty(Property):
1998    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
2001class DictSubProperty(Property):
2002    pass
key = 'dictsubproperty'
class DictRange(Property):
2005class DictRange(Property):
2006    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
2011class OnCluster(Property):
2012    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
2015class LikeProperty(Property):
2016    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
2019class LocationProperty(Property):
2020    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
2023class LockingProperty(Property):
2024    arg_types = {
2025        "this": False,
2026        "kind": True,
2027        "for_or_in": True,
2028        "lock_type": True,
2029        "override": False,
2030    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
2033class LogProperty(Property):
2034    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
2037class MaterializedProperty(Property):
2038    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
2041class MergeBlockRatioProperty(Property):
2042    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):
2045class NoPrimaryIndexProperty(Property):
2046    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
2049class OnCommitProperty(Property):
2050    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
2053class PartitionedByProperty(Property):
2054    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
2057class ReturnsProperty(Property):
2058    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2061class RowFormatProperty(Property):
2062    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2065class RowFormatDelimitedProperty(Property):
2066    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2067    arg_types = {
2068        "fields": False,
2069        "escaped": False,
2070        "collection_items": False,
2071        "map_keys": False,
2072        "lines": False,
2073        "null": False,
2074        "serde": False,
2075    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2078class RowFormatSerdeProperty(Property):
2079    arg_types = {"this": True, "serde_properties": False}
arg_types = {'this': True, 'serde_properties': False}
key = 'rowformatserdeproperty'
class QueryTransform(Expression):
2083class QueryTransform(Expression):
2084    arg_types = {
2085        "expressions": True,
2086        "command_script": True,
2087        "schema": False,
2088        "row_format_before": False,
2089        "record_writer": False,
2090        "row_format_after": False,
2091        "record_reader": False,
2092    }
arg_types = {'expressions': True, 'command_script': True, 'schema': False, 'row_format_before': False, 'record_writer': False, 'row_format_after': False, 'record_reader': False}
key = 'querytransform'
class SchemaCommentProperty(Property):
2095class SchemaCommentProperty(Property):
2096    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2099class SerdeProperties(Property):
2100    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2103class SetProperty(Property):
2104    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2107class SettingsProperty(Property):
2108    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2111class SortKeyProperty(Property):
2112    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2115class SqlSecurityProperty(Property):
2116    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2119class StabilityProperty(Property):
2120    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2123class TemporaryProperty(Property):
2124    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2127class TransientProperty(Property):
2128    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2131class VolatileProperty(Property):
2132    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2135class WithDataProperty(Property):
2136    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2139class WithJournalTableProperty(Property):
2140    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2143class Properties(Expression):
2144    arg_types = {"expressions": True}
2145
2146    NAME_TO_PROPERTY = {
2147        "ALGORITHM": AlgorithmProperty,
2148        "AUTO_INCREMENT": AutoIncrementProperty,
2149        "CHARACTER SET": CharacterSetProperty,
2150        "CLUSTERED_BY": ClusteredByProperty,
2151        "COLLATE": CollateProperty,
2152        "COMMENT": SchemaCommentProperty,
2153        "DEFINER": DefinerProperty,
2154        "DISTKEY": DistKeyProperty,
2155        "DISTSTYLE": DistStyleProperty,
2156        "ENGINE": EngineProperty,
2157        "EXECUTE AS": ExecuteAsProperty,
2158        "FORMAT": FileFormatProperty,
2159        "LANGUAGE": LanguageProperty,
2160        "LOCATION": LocationProperty,
2161        "PARTITIONED_BY": PartitionedByProperty,
2162        "RETURNS": ReturnsProperty,
2163        "ROW_FORMAT": RowFormatProperty,
2164        "SORTKEY": SortKeyProperty,
2165    }
2166
2167    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2168
2169    # CREATE property locations
2170    # Form: schema specified
2171    #   create [POST_CREATE]
2172    #     table a [POST_NAME]
2173    #     (b int) [POST_SCHEMA]
2174    #     with ([POST_WITH])
2175    #     index (b) [POST_INDEX]
2176    #
2177    # Form: alias selection
2178    #   create [POST_CREATE]
2179    #     table a [POST_NAME]
2180    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2181    #     index (c) [POST_INDEX]
2182    class Location(AutoName):
2183        POST_CREATE = auto()
2184        POST_NAME = auto()
2185        POST_SCHEMA = auto()
2186        POST_WITH = auto()
2187        POST_ALIAS = auto()
2188        POST_EXPRESSION = auto()
2189        POST_INDEX = auto()
2190        UNSUPPORTED = auto()
2191
2192    @classmethod
2193    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2194        expressions = []
2195        for key, value in properties_dict.items():
2196            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2197            if property_cls:
2198                expressions.append(property_cls(this=convert(value)))
2199            else:
2200                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2201
2202        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:
2192    @classmethod
2193    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2194        expressions = []
2195        for key, value in properties_dict.items():
2196            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2197            if property_cls:
2198                expressions.append(property_cls(this=convert(value)))
2199            else:
2200                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2201
2202        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2182    class Location(AutoName):
2183        POST_CREATE = auto()
2184        POST_NAME = auto()
2185        POST_SCHEMA = auto()
2186        POST_WITH = auto()
2187        POST_ALIAS = auto()
2188        POST_EXPRESSION = auto()
2189        POST_INDEX = auto()
2190        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):
2205class Qualify(Expression):
2206    pass
key = 'qualify'
class Return(Expression):
2210class Return(Expression):
2211    pass
key = 'return'
class Reference(Expression):
2214class Reference(Expression):
2215    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2218class Tuple(Expression):
2219    arg_types = {"expressions": False}
2220
2221    def isin(
2222        self,
2223        *expressions: t.Any,
2224        query: t.Optional[ExpOrStr] = None,
2225        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2226        copy: bool = True,
2227        **opts,
2228    ) -> In:
2229        return In(
2230            this=maybe_copy(self, copy),
2231            expressions=[convert(e, copy=copy) for e in expressions],
2232            query=maybe_parse(query, copy=copy, **opts) if query else None,
2233            unnest=Unnest(
2234                expressions=[
2235                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2236                ]
2237            )
2238            if unnest
2239            else None,
2240        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, unnest: Union[str, sqlglot.expressions.Expression, NoneType, Collection[Union[str, sqlglot.expressions.Expression]]] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2221    def isin(
2222        self,
2223        *expressions: t.Any,
2224        query: t.Optional[ExpOrStr] = None,
2225        unnest: t.Optional[ExpOrStr] | t.Collection[ExpOrStr] = None,
2226        copy: bool = True,
2227        **opts,
2228    ) -> In:
2229        return In(
2230            this=maybe_copy(self, copy),
2231            expressions=[convert(e, copy=copy) for e in expressions],
2232            query=maybe_parse(query, copy=copy, **opts) if query else None,
2233            unnest=Unnest(
2234                expressions=[
2235                    maybe_parse(t.cast(ExpOrStr, e), copy=copy, **opts) for e in ensure_list(unnest)
2236                ]
2237            )
2238            if unnest
2239            else None,
2240        )
key = 'tuple'
class Subqueryable(Unionable):
2243class Subqueryable(Unionable):
2244    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2245        """
2246        Convert this expression to an aliased expression that can be used as a Subquery.
2247
2248        Example:
2249            >>> subquery = Select().select("x").from_("tbl").subquery()
2250            >>> Select().select("x").from_(subquery).sql()
2251            'SELECT x FROM (SELECT x FROM tbl)'
2252
2253        Args:
2254            alias (str | Identifier): an optional alias for the subquery
2255            copy (bool): if `False`, modify this expression instance in-place.
2256
2257        Returns:
2258            Alias: the subquery
2259        """
2260        instance = maybe_copy(self, copy)
2261        if not isinstance(alias, Expression):
2262            alias = TableAlias(this=to_identifier(alias)) if alias else None
2263
2264        return Subquery(this=instance, alias=alias)
2265
2266    def limit(
2267        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2268    ) -> Select:
2269        raise NotImplementedError
2270
2271    @property
2272    def ctes(self):
2273        with_ = self.args.get("with")
2274        if not with_:
2275            return []
2276        return with_.expressions
2277
2278    @property
2279    def selects(self) -> t.List[Expression]:
2280        raise NotImplementedError("Subqueryable objects must implement `selects`")
2281
2282    @property
2283    def named_selects(self) -> t.List[str]:
2284        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2285
2286    def with_(
2287        self,
2288        alias: ExpOrStr,
2289        as_: ExpOrStr,
2290        recursive: t.Optional[bool] = None,
2291        append: bool = True,
2292        dialect: DialectType = None,
2293        copy: bool = True,
2294        **opts,
2295    ) -> Subqueryable:
2296        """
2297        Append to or set the common table expressions.
2298
2299        Example:
2300            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2301            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2302
2303        Args:
2304            alias: the SQL code string to parse as the table name.
2305                If an `Expression` instance is passed, this is used as-is.
2306            as_: the SQL code string to parse as the table expression.
2307                If an `Expression` instance is passed, it will be used as-is.
2308            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2309            append: if `True`, add to any existing expressions.
2310                Otherwise, this resets the expressions.
2311            dialect: the dialect used to parse the input expression.
2312            copy: if `False`, modify this expression instance in-place.
2313            opts: other options to use to parse the input expressions.
2314
2315        Returns:
2316            The modified expression.
2317        """
2318        return _apply_cte_builder(
2319            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2320        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2244    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2245        """
2246        Convert this expression to an aliased expression that can be used as a Subquery.
2247
2248        Example:
2249            >>> subquery = Select().select("x").from_("tbl").subquery()
2250            >>> Select().select("x").from_(subquery).sql()
2251            'SELECT x FROM (SELECT x FROM tbl)'
2252
2253        Args:
2254            alias (str | Identifier): an optional alias for the subquery
2255            copy (bool): if `False`, modify this expression instance in-place.
2256
2257        Returns:
2258            Alias: the subquery
2259        """
2260        instance = maybe_copy(self, copy)
2261        if not isinstance(alias, Expression):
2262            alias = TableAlias(this=to_identifier(alias)) if alias else None
2263
2264        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:
2266    def limit(
2267        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2268    ) -> Select:
2269        raise NotImplementedError
ctes
named_selects: List[str]
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:
2286    def with_(
2287        self,
2288        alias: ExpOrStr,
2289        as_: ExpOrStr,
2290        recursive: t.Optional[bool] = None,
2291        append: bool = True,
2292        dialect: DialectType = None,
2293        copy: bool = True,
2294        **opts,
2295    ) -> Subqueryable:
2296        """
2297        Append to or set the common table expressions.
2298
2299        Example:
2300            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2301            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2302
2303        Args:
2304            alias: the SQL code string to parse as the table name.
2305                If an `Expression` instance is passed, this is used as-is.
2306            as_: the SQL code string to parse as the table expression.
2307                If an `Expression` instance is passed, it will be used as-is.
2308            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2309            append: if `True`, add to any existing expressions.
2310                Otherwise, this resets the expressions.
2311            dialect: the dialect used to parse the input expression.
2312            copy: if `False`, modify this expression instance in-place.
2313            opts: other options to use to parse the input expressions.
2314
2315        Returns:
2316            The modified expression.
2317        """
2318        return _apply_cte_builder(
2319            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2320        )

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):
2347class WithTableHint(Expression):
2348    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2352class IndexTableHint(Expression):
2353    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2356class Table(Expression):
2357    arg_types = {
2358        "this": True,
2359        "alias": False,
2360        "db": False,
2361        "catalog": False,
2362        "laterals": False,
2363        "joins": False,
2364        "pivots": False,
2365        "hints": False,
2366        "system_time": False,
2367    }
2368
2369    @property
2370    def name(self) -> str:
2371        if isinstance(self.this, Func):
2372            return ""
2373        return self.this.name
2374
2375    @property
2376    def db(self) -> str:
2377        return self.text("db")
2378
2379    @property
2380    def catalog(self) -> str:
2381        return self.text("catalog")
2382
2383    @property
2384    def selects(self) -> t.List[Expression]:
2385        return []
2386
2387    @property
2388    def named_selects(self) -> t.List[str]:
2389        return []
2390
2391    @property
2392    def parts(self) -> t.List[Identifier]:
2393        """Return the parts of a table in order catalog, db, table."""
2394        parts: t.List[Identifier] = []
2395
2396        for arg in ("catalog", "db", "this"):
2397            part = self.args.get(arg)
2398
2399            if isinstance(part, Identifier):
2400                parts.append(part)
2401            elif isinstance(part, Dot):
2402                parts.extend(part.flatten())
2403
2404        return parts
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
named_selects: List[str]

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

key = 'table'
class SystemTime(Expression):
2408class SystemTime(Expression):
2409    arg_types = {
2410        "this": False,
2411        "expression": False,
2412        "kind": True,
2413    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2416class Union(Subqueryable):
2417    arg_types = {
2418        "with": False,
2419        "this": True,
2420        "expression": True,
2421        "distinct": False,
2422        **QUERY_MODIFIERS,
2423    }
2424
2425    def limit(
2426        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2427    ) -> Select:
2428        """
2429        Set the LIMIT expression.
2430
2431        Example:
2432            >>> select("1").union(select("1")).limit(1).sql()
2433            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2434
2435        Args:
2436            expression: the SQL code string to parse.
2437                This can also be an integer.
2438                If a `Limit` instance is passed, this is used as-is.
2439                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2440            dialect: the dialect used to parse the input expression.
2441            copy: if `False`, modify this expression instance in-place.
2442            opts: other options to use to parse the input expressions.
2443
2444        Returns:
2445            The limited subqueryable.
2446        """
2447        return (
2448            select("*")
2449            .from_(self.subquery(alias="_l_0", copy=copy))
2450            .limit(expression, dialect=dialect, copy=False, **opts)
2451        )
2452
2453    def select(
2454        self,
2455        *expressions: t.Optional[ExpOrStr],
2456        append: bool = True,
2457        dialect: DialectType = None,
2458        copy: bool = True,
2459        **opts,
2460    ) -> Union:
2461        """Append to or set the SELECT of the union recursively.
2462
2463        Example:
2464            >>> from sqlglot import parse_one
2465            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2466            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2467
2468        Args:
2469            *expressions: the SQL code strings to parse.
2470                If an `Expression` instance is passed, it will be used as-is.
2471            append: if `True`, add to any existing expressions.
2472                Otherwise, this resets the expressions.
2473            dialect: the dialect used to parse the input expressions.
2474            copy: if `False`, modify this expression instance in-place.
2475            opts: other options to use to parse the input expressions.
2476
2477        Returns:
2478            Union: the modified expression.
2479        """
2480        this = self.copy() if copy else self
2481        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2482        this.expression.unnest().select(
2483            *expressions, append=append, dialect=dialect, copy=False, **opts
2484        )
2485        return this
2486
2487    @property
2488    def named_selects(self) -> t.List[str]:
2489        return self.this.unnest().named_selects
2490
2491    @property
2492    def is_star(self) -> bool:
2493        return self.this.is_star or self.expression.is_star
2494
2495    @property
2496    def selects(self) -> t.List[Expression]:
2497        return self.this.unnest().selects
2498
2499    @property
2500    def left(self):
2501        return self.this
2502
2503    @property
2504    def right(self):
2505        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:
2425    def limit(
2426        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2427    ) -> Select:
2428        """
2429        Set the LIMIT expression.
2430
2431        Example:
2432            >>> select("1").union(select("1")).limit(1).sql()
2433            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2434
2435        Args:
2436            expression: the SQL code string to parse.
2437                This can also be an integer.
2438                If a `Limit` instance is passed, this is used as-is.
2439                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2440            dialect: the dialect used to parse the input expression.
2441            copy: if `False`, modify this expression instance in-place.
2442            opts: other options to use to parse the input expressions.
2443
2444        Returns:
2445            The limited subqueryable.
2446        """
2447        return (
2448            select("*")
2449            .from_(self.subquery(alias="_l_0", copy=copy))
2450            .limit(expression, dialect=dialect, copy=False, **opts)
2451        )

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:
2453    def select(
2454        self,
2455        *expressions: t.Optional[ExpOrStr],
2456        append: bool = True,
2457        dialect: DialectType = None,
2458        copy: bool = True,
2459        **opts,
2460    ) -> Union:
2461        """Append to or set the SELECT of the union recursively.
2462
2463        Example:
2464            >>> from sqlglot import parse_one
2465            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2466            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2467
2468        Args:
2469            *expressions: the SQL code strings to parse.
2470                If an `Expression` instance is passed, it will be used as-is.
2471            append: if `True`, add to any existing expressions.
2472                Otherwise, this resets the expressions.
2473            dialect: the dialect used to parse the input expressions.
2474            copy: if `False`, modify this expression instance in-place.
2475            opts: other options to use to parse the input expressions.
2476
2477        Returns:
2478            Union: the modified expression.
2479        """
2480        this = self.copy() if copy else self
2481        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2482        this.expression.unnest().select(
2483            *expressions, append=append, dialect=dialect, copy=False, **opts
2484        )
2485        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: List[str]
is_star: bool

Checks whether an expression is a star.

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

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:
2603    def group_by(
2604        self,
2605        *expressions: t.Optional[ExpOrStr],
2606        append: bool = True,
2607        dialect: DialectType = None,
2608        copy: bool = True,
2609        **opts,
2610    ) -> Select:
2611        """
2612        Set the GROUP BY expression.
2613
2614        Example:
2615            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2616            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2617
2618        Args:
2619            *expressions: the SQL code strings to parse.
2620                If a `Group` instance is passed, this is used as-is.
2621                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2622                If nothing is passed in then a group by is not applied to the expression
2623            append: if `True`, add to any existing expressions.
2624                Otherwise, this flattens all the `Group` expression into a single expression.
2625            dialect: the dialect used to parse the input expression.
2626            copy: if `False`, modify this expression instance in-place.
2627            opts: other options to use to parse the input expressions.
2628
2629        Returns:
2630            The modified Select expression.
2631        """
2632        if not expressions:
2633            return self if not copy else self.copy()
2634
2635        return _apply_child_list_builder(
2636            *expressions,
2637            instance=self,
2638            arg="group",
2639            append=append,
2640            copy=copy,
2641            prefix="GROUP BY",
2642            into=Group,
2643            dialect=dialect,
2644            **opts,
2645        )

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:
2647    def order_by(
2648        self,
2649        *expressions: t.Optional[ExpOrStr],
2650        append: bool = True,
2651        dialect: DialectType = None,
2652        copy: bool = True,
2653        **opts,
2654    ) -> Select:
2655        """
2656        Set the ORDER BY expression.
2657
2658        Example:
2659            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2660            'SELECT x FROM tbl ORDER BY x DESC'
2661
2662        Args:
2663            *expressions: the SQL code strings to parse.
2664                If a `Group` instance is passed, this is used as-is.
2665                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2666            append: if `True`, add to any existing expressions.
2667                Otherwise, this flattens all the `Order` expression into a single expression.
2668            dialect: the dialect used to parse the input expression.
2669            copy: if `False`, modify this expression instance in-place.
2670            opts: other options to use to parse the input expressions.
2671
2672        Returns:
2673            The modified Select expression.
2674        """
2675        return _apply_child_list_builder(
2676            *expressions,
2677            instance=self,
2678            arg="order",
2679            append=append,
2680            copy=copy,
2681            prefix="ORDER BY",
2682            into=Order,
2683            dialect=dialect,
2684            **opts,
2685        )

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:
2687    def sort_by(
2688        self,
2689        *expressions: t.Optional[ExpOrStr],
2690        append: bool = True,
2691        dialect: DialectType = None,
2692        copy: bool = True,
2693        **opts,
2694    ) -> Select:
2695        """
2696        Set the SORT BY expression.
2697
2698        Example:
2699            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2700            'SELECT x FROM tbl SORT BY x DESC'
2701
2702        Args:
2703            *expressions: the SQL code strings to parse.
2704                If a `Group` instance is passed, this is used as-is.
2705                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2706            append: if `True`, add to any existing expressions.
2707                Otherwise, this flattens all the `Order` expression into a single expression.
2708            dialect: the dialect used to parse the input expression.
2709            copy: if `False`, modify this expression instance in-place.
2710            opts: other options to use to parse the input expressions.
2711
2712        Returns:
2713            The modified Select expression.
2714        """
2715        return _apply_child_list_builder(
2716            *expressions,
2717            instance=self,
2718            arg="sort",
2719            append=append,
2720            copy=copy,
2721            prefix="SORT BY",
2722            into=Sort,
2723            dialect=dialect,
2724            **opts,
2725        )

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:
2727    def cluster_by(
2728        self,
2729        *expressions: t.Optional[ExpOrStr],
2730        append: bool = True,
2731        dialect: DialectType = None,
2732        copy: bool = True,
2733        **opts,
2734    ) -> Select:
2735        """
2736        Set the CLUSTER BY expression.
2737
2738        Example:
2739            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2740            'SELECT x FROM tbl CLUSTER BY x DESC'
2741
2742        Args:
2743            *expressions: the SQL code strings to parse.
2744                If a `Group` instance is passed, this is used as-is.
2745                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2746            append: if `True`, add to any existing expressions.
2747                Otherwise, this flattens all the `Order` expression into a single expression.
2748            dialect: the dialect used to parse the input expression.
2749            copy: if `False`, modify this expression instance in-place.
2750            opts: other options to use to parse the input expressions.
2751
2752        Returns:
2753            The modified Select expression.
2754        """
2755        return _apply_child_list_builder(
2756            *expressions,
2757            instance=self,
2758            arg="cluster",
2759            append=append,
2760            copy=copy,
2761            prefix="CLUSTER BY",
2762            into=Cluster,
2763            dialect=dialect,
2764            **opts,
2765        )

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:
2767    def limit(
2768        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2769    ) -> Select:
2770        """
2771        Set the LIMIT expression.
2772
2773        Example:
2774            >>> Select().from_("tbl").select("x").limit(10).sql()
2775            'SELECT x FROM tbl LIMIT 10'
2776
2777        Args:
2778            expression: the SQL code string to parse.
2779                This can also be an integer.
2780                If a `Limit` instance is passed, this is used as-is.
2781                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2782            dialect: the dialect used to parse the input expression.
2783            copy: if `False`, modify this expression instance in-place.
2784            opts: other options to use to parse the input expressions.
2785
2786        Returns:
2787            Select: the modified expression.
2788        """
2789        return _apply_builder(
2790            expression=expression,
2791            instance=self,
2792            arg="limit",
2793            into=Limit,
2794            prefix="LIMIT",
2795            dialect=dialect,
2796            copy=copy,
2797            **opts,
2798        )

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:
2800    def offset(
2801        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2802    ) -> Select:
2803        """
2804        Set the OFFSET expression.
2805
2806        Example:
2807            >>> Select().from_("tbl").select("x").offset(10).sql()
2808            'SELECT x FROM tbl OFFSET 10'
2809
2810        Args:
2811            expression: the SQL code string to parse.
2812                This can also be an integer.
2813                If a `Offset` instance is passed, this is used as-is.
2814                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2815            dialect: the dialect used to parse the input expression.
2816            copy: if `False`, modify this expression instance in-place.
2817            opts: other options to use to parse the input expressions.
2818
2819        Returns:
2820            The modified Select expression.
2821        """
2822        return _apply_builder(
2823            expression=expression,
2824            instance=self,
2825            arg="offset",
2826            into=Offset,
2827            prefix="OFFSET",
2828            dialect=dialect,
2829            copy=copy,
2830            **opts,
2831        )

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:
2833    def select(
2834        self,
2835        *expressions: t.Optional[ExpOrStr],
2836        append: bool = True,
2837        dialect: DialectType = None,
2838        copy: bool = True,
2839        **opts,
2840    ) -> Select:
2841        """
2842        Append to or set the SELECT expressions.
2843
2844        Example:
2845            >>> Select().select("x", "y").sql()
2846            'SELECT x, y'
2847
2848        Args:
2849            *expressions: the SQL code strings to parse.
2850                If an `Expression` instance is passed, it will be used as-is.
2851            append: if `True`, add to any existing expressions.
2852                Otherwise, this resets the expressions.
2853            dialect: the dialect used to parse the input expressions.
2854            copy: if `False`, modify this expression instance in-place.
2855            opts: other options to use to parse the input expressions.
2856
2857        Returns:
2858            The modified Select expression.
2859        """
2860        return _apply_list_builder(
2861            *expressions,
2862            instance=self,
2863            arg="expressions",
2864            append=append,
2865            dialect=dialect,
2866            copy=copy,
2867            **opts,
2868        )

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:
2870    def lateral(
2871        self,
2872        *expressions: t.Optional[ExpOrStr],
2873        append: bool = True,
2874        dialect: DialectType = None,
2875        copy: bool = True,
2876        **opts,
2877    ) -> Select:
2878        """
2879        Append to or set the LATERAL expressions.
2880
2881        Example:
2882            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2883            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2884
2885        Args:
2886            *expressions: the SQL code strings to parse.
2887                If an `Expression` instance is passed, it will be used as-is.
2888            append: if `True`, add to any existing expressions.
2889                Otherwise, this resets the expressions.
2890            dialect: the dialect used to parse the input expressions.
2891            copy: if `False`, modify this expression instance in-place.
2892            opts: other options to use to parse the input expressions.
2893
2894        Returns:
2895            The modified Select expression.
2896        """
2897        return _apply_list_builder(
2898            *expressions,
2899            instance=self,
2900            arg="laterals",
2901            append=append,
2902            into=Lateral,
2903            prefix="LATERAL VIEW",
2904            dialect=dialect,
2905            copy=copy,
2906            **opts,
2907        )

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, Collection[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:
2909    def join(
2910        self,
2911        expression: ExpOrStr,
2912        on: t.Optional[ExpOrStr] = None,
2913        using: t.Optional[ExpOrStr | t.Collection[ExpOrStr]] = None,
2914        append: bool = True,
2915        join_type: t.Optional[str] = None,
2916        join_alias: t.Optional[Identifier | str] = None,
2917        dialect: DialectType = None,
2918        copy: bool = True,
2919        **opts,
2920    ) -> Select:
2921        """
2922        Append to or set the JOIN expressions.
2923
2924        Example:
2925            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2926            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2927
2928            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2929            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2930
2931            Use `join_type` to change the type of join:
2932
2933            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2934            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2935
2936        Args:
2937            expression: the SQL code string to parse.
2938                If an `Expression` instance is passed, it will be used as-is.
2939            on: optionally specify the join "on" criteria as a SQL string.
2940                If an `Expression` instance is passed, it will be used as-is.
2941            using: optionally specify the join "using" criteria as a SQL string.
2942                If an `Expression` instance is passed, it will be used as-is.
2943            append: if `True`, add to any existing expressions.
2944                Otherwise, this resets the expressions.
2945            join_type: if set, alter the parsed join type.
2946            join_alias: an optional alias for the joined source.
2947            dialect: the dialect used to parse the input expressions.
2948            copy: if `False`, modify this expression instance in-place.
2949            opts: other options to use to parse the input expressions.
2950
2951        Returns:
2952            Select: the modified expression.
2953        """
2954        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2955
2956        try:
2957            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2958        except ParseError:
2959            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2960
2961        join = expression if isinstance(expression, Join) else Join(this=expression)
2962
2963        if isinstance(join.this, Select):
2964            join.this.replace(join.this.subquery())
2965
2966        if join_type:
2967            method: t.Optional[Token]
2968            side: t.Optional[Token]
2969            kind: t.Optional[Token]
2970
2971            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2972
2973            if method:
2974                join.set("method", method.text)
2975            if side:
2976                join.set("side", side.text)
2977            if kind:
2978                join.set("kind", kind.text)
2979
2980        if on:
2981            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2982            join.set("on", on)
2983
2984        if using:
2985            join = _apply_list_builder(
2986                *ensure_list(using),
2987                instance=join,
2988                arg="using",
2989                append=append,
2990                copy=copy,
2991                into=Identifier,
2992                **opts,
2993            )
2994
2995        if join_alias:
2996            join.set("this", alias_(join.this, join_alias, table=True))
2997
2998        return _apply_list_builder(
2999            join,
3000            instance=self,
3001            arg="joins",
3002            append=append,
3003            copy=copy,
3004            **opts,
3005        )

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:
3007    def where(
3008        self,
3009        *expressions: t.Optional[ExpOrStr],
3010        append: bool = True,
3011        dialect: DialectType = None,
3012        copy: bool = True,
3013        **opts,
3014    ) -> Select:
3015        """
3016        Append to or set the WHERE expressions.
3017
3018        Example:
3019            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
3020            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
3021
3022        Args:
3023            *expressions: the SQL code strings to parse.
3024                If an `Expression` instance is passed, it will be used as-is.
3025                Multiple expressions are combined with an AND operator.
3026            append: if `True`, AND the new expressions to any existing expression.
3027                Otherwise, this resets the expression.
3028            dialect: the dialect used to parse the input expressions.
3029            copy: if `False`, modify this expression instance in-place.
3030            opts: other options to use to parse the input expressions.
3031
3032        Returns:
3033            Select: the modified expression.
3034        """
3035        return _apply_conjunction_builder(
3036            *expressions,
3037            instance=self,
3038            arg="where",
3039            append=append,
3040            into=Where,
3041            dialect=dialect,
3042            copy=copy,
3043            **opts,
3044        )

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:
3046    def having(
3047        self,
3048        *expressions: t.Optional[ExpOrStr],
3049        append: bool = True,
3050        dialect: DialectType = None,
3051        copy: bool = True,
3052        **opts,
3053    ) -> Select:
3054        """
3055        Append to or set the HAVING expressions.
3056
3057        Example:
3058            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
3059            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
3060
3061        Args:
3062            *expressions: the SQL code strings to parse.
3063                If an `Expression` instance is passed, it will be used as-is.
3064                Multiple expressions are combined with an AND operator.
3065            append: if `True`, AND the new expressions to any existing expression.
3066                Otherwise, this resets the expression.
3067            dialect: the dialect used to parse the input expressions.
3068            copy: if `False`, modify this expression instance in-place.
3069            opts: other options to use to parse the input expressions.
3070
3071        Returns:
3072            The modified Select expression.
3073        """
3074        return _apply_conjunction_builder(
3075            *expressions,
3076            instance=self,
3077            arg="having",
3078            append=append,
3079            into=Having,
3080            dialect=dialect,
3081            copy=copy,
3082            **opts,
3083        )

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:
3085    def window(
3086        self,
3087        *expressions: t.Optional[ExpOrStr],
3088        append: bool = True,
3089        dialect: DialectType = None,
3090        copy: bool = True,
3091        **opts,
3092    ) -> Select:
3093        return _apply_list_builder(
3094            *expressions,
3095            instance=self,
3096            arg="windows",
3097            append=append,
3098            into=Window,
3099            dialect=dialect,
3100            copy=copy,
3101            **opts,
3102        )
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:
3104    def qualify(
3105        self,
3106        *expressions: t.Optional[ExpOrStr],
3107        append: bool = True,
3108        dialect: DialectType = None,
3109        copy: bool = True,
3110        **opts,
3111    ) -> Select:
3112        return _apply_conjunction_builder(
3113            *expressions,
3114            instance=self,
3115            arg="qualify",
3116            append=append,
3117            into=Qualify,
3118            dialect=dialect,
3119            copy=copy,
3120            **opts,
3121        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3123    def distinct(
3124        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3125    ) -> Select:
3126        """
3127        Set the OFFSET expression.
3128
3129        Example:
3130            >>> Select().from_("tbl").select("x").distinct().sql()
3131            'SELECT DISTINCT x FROM tbl'
3132
3133        Args:
3134            ons: the expressions to distinct on
3135            distinct: whether the Select should be distinct
3136            copy: if `False`, modify this expression instance in-place.
3137
3138        Returns:
3139            Select: the modified expression.
3140        """
3141        instance = maybe_copy(self, copy)
3142        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3143        instance.set("distinct", Distinct(on=on) if distinct else None)
3144        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:
3146    def ctas(
3147        self,
3148        table: ExpOrStr,
3149        properties: t.Optional[t.Dict] = None,
3150        dialect: DialectType = None,
3151        copy: bool = True,
3152        **opts,
3153    ) -> Create:
3154        """
3155        Convert this expression to a CREATE TABLE AS statement.
3156
3157        Example:
3158            >>> Select().select("*").from_("tbl").ctas("x").sql()
3159            'CREATE TABLE x AS SELECT * FROM tbl'
3160
3161        Args:
3162            table: the SQL code string to parse as the table name.
3163                If another `Expression` instance is passed, it will be used as-is.
3164            properties: an optional mapping of table properties
3165            dialect: the dialect used to parse the input table.
3166            copy: if `False`, modify this expression instance in-place.
3167            opts: other options to use to parse the input table.
3168
3169        Returns:
3170            The new Create expression.
3171        """
3172        instance = maybe_copy(self, copy)
3173        table_expression = maybe_parse(
3174            table,
3175            into=Table,
3176            dialect=dialect,
3177            **opts,
3178        )
3179        properties_expression = None
3180        if properties:
3181            properties_expression = Properties.from_dict(properties)
3182
3183        return Create(
3184            this=table_expression,
3185            kind="table",
3186            expression=instance,
3187            properties=properties_expression,
3188        )

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:
3190    def lock(self, update: bool = True, copy: bool = True) -> Select:
3191        """
3192        Set the locking read mode for this expression.
3193
3194        Examples:
3195            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3196            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3197
3198            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3199            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3200
3201        Args:
3202            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3203            copy: if `False`, modify this expression instance in-place.
3204
3205        Returns:
3206            The modified expression.
3207        """
3208        inst = maybe_copy(self, copy)
3209        inst.set("locks", [Lock(update=update)])
3210
3211        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:
3213    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3214        """
3215        Set hints for this expression.
3216
3217        Examples:
3218            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3219            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3220
3221        Args:
3222            hints: The SQL code strings to parse as the hints.
3223                If an `Expression` instance is passed, it will be used as-is.
3224            dialect: The dialect used to parse the hints.
3225            copy: If `False`, modify this expression instance in-place.
3226
3227        Returns:
3228            The modified expression.
3229        """
3230        inst = maybe_copy(self, copy)
3231        inst.set(
3232            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3233        )
3234
3235        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):
3250class Subquery(DerivedTable, Unionable):
3251    arg_types = {
3252        "this": True,
3253        "alias": False,
3254        "with": False,
3255        **QUERY_MODIFIERS,
3256    }
3257
3258    def unnest(self):
3259        """
3260        Returns the first non subquery.
3261        """
3262        expression = self
3263        while isinstance(expression, Subquery):
3264            expression = expression.this
3265        return expression
3266
3267    @property
3268    def is_star(self) -> bool:
3269        return self.this.is_star
3270
3271    @property
3272    def output_name(self) -> str:
3273        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):
3258    def unnest(self):
3259        """
3260        Returns the first non subquery.
3261        """
3262        expression = self
3263        while isinstance(expression, Subquery):
3264            expression = expression.this
3265        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):
3276class TableSample(Expression):
3277    arg_types = {
3278        "this": False,
3279        "method": False,
3280        "bucket_numerator": False,
3281        "bucket_denominator": False,
3282        "bucket_field": False,
3283        "percent": False,
3284        "rows": False,
3285        "size": False,
3286        "seed": False,
3287        "kind": False,
3288    }
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):
3291class Tag(Expression):
3292    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3293
3294    arg_types = {
3295        "this": False,
3296        "prefix": False,
3297        "postfix": False,
3298    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3303class Pivot(Expression):
3304    arg_types = {
3305        "this": False,
3306        "alias": False,
3307        "expressions": True,
3308        "field": False,
3309        "unpivot": False,
3310        "using": False,
3311        "group": False,
3312        "columns": False,
3313        "include_nulls": False,
3314    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False, 'include_nulls': False}
key = 'pivot'
class Window(Expression):
3317class Window(Expression):
3318    arg_types = {
3319        "this": True,
3320        "partition_by": False,
3321        "order": False,
3322        "spec": False,
3323        "alias": False,
3324        "over": False,
3325        "first": False,
3326    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3329class WindowSpec(Expression):
3330    arg_types = {
3331        "kind": False,
3332        "start": False,
3333        "start_side": False,
3334        "end": False,
3335        "end_side": False,
3336    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3339class Where(Expression):
3340    pass
key = 'where'
class Star(Expression):
3343class Star(Expression):
3344    arg_types = {"except": False, "replace": False}
3345
3346    @property
3347    def name(self) -> str:
3348        return "*"
3349
3350    @property
3351    def output_name(self) -> str:
3352        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):
3355class Parameter(Condition):
3356    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3359class SessionParameter(Condition):
3360    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3363class Placeholder(Condition):
3364    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3367class Null(Condition):
3368    arg_types: t.Dict[str, t.Any] = {}
3369
3370    @property
3371    def name(self) -> str:
3372        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3375class Boolean(Condition):
3376    pass
key = 'boolean'
class DataTypeSize(Expression):
3379class DataTypeSize(Expression):
3380    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3383class DataType(Expression):
3384    arg_types = {
3385        "this": True,
3386        "expressions": False,
3387        "nested": False,
3388        "values": False,
3389        "prefix": False,
3390    }
3391
3392    class Type(AutoName):
3393        ARRAY = auto()
3394        BIGDECIMAL = auto()
3395        BIGINT = auto()
3396        BIGSERIAL = auto()
3397        BINARY = auto()
3398        BIT = auto()
3399        BOOLEAN = auto()
3400        CHAR = auto()
3401        DATE = auto()
3402        DATEMULTIRANGE = auto()
3403        DATERANGE = auto()
3404        DATETIME = auto()
3405        DATETIME64 = auto()
3406        DECIMAL = auto()
3407        DOUBLE = auto()
3408        ENUM = auto()
3409        ENUM8 = auto()
3410        ENUM16 = auto()
3411        FIXEDSTRING = auto()
3412        FLOAT = auto()
3413        GEOGRAPHY = auto()
3414        GEOMETRY = auto()
3415        HLLSKETCH = auto()
3416        HSTORE = auto()
3417        IMAGE = auto()
3418        INET = auto()
3419        INT = auto()
3420        INT128 = auto()
3421        INT256 = auto()
3422        INT4MULTIRANGE = auto()
3423        INT4RANGE = auto()
3424        INT8MULTIRANGE = auto()
3425        INT8RANGE = auto()
3426        INTERVAL = auto()
3427        IPADDRESS = auto()
3428        IPPREFIX = auto()
3429        JSON = auto()
3430        JSONB = auto()
3431        LONGBLOB = auto()
3432        LONGTEXT = auto()
3433        LOWCARDINALITY = auto()
3434        MAP = auto()
3435        MEDIUMBLOB = auto()
3436        MEDIUMTEXT = auto()
3437        MONEY = auto()
3438        NCHAR = auto()
3439        NESTED = auto()
3440        NULL = auto()
3441        NULLABLE = auto()
3442        NUMMULTIRANGE = auto()
3443        NUMRANGE = auto()
3444        NVARCHAR = auto()
3445        OBJECT = auto()
3446        ROWVERSION = auto()
3447        SERIAL = auto()
3448        SET = auto()
3449        SMALLINT = auto()
3450        SMALLMONEY = auto()
3451        SMALLSERIAL = auto()
3452        STRUCT = auto()
3453        SUPER = auto()
3454        TEXT = auto()
3455        TIME = auto()
3456        TIMETZ = auto()
3457        TIMESTAMP = auto()
3458        TIMESTAMPLTZ = auto()
3459        TIMESTAMPTZ = auto()
3460        TINYINT = auto()
3461        TSMULTIRANGE = auto()
3462        TSRANGE = auto()
3463        TSTZMULTIRANGE = auto()
3464        TSTZRANGE = auto()
3465        UBIGINT = auto()
3466        UINT = auto()
3467        UINT128 = auto()
3468        UINT256 = auto()
3469        UNIQUEIDENTIFIER = auto()
3470        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3471        USERDEFINED = "USER-DEFINED"
3472        USMALLINT = auto()
3473        UTINYINT = auto()
3474        UUID = auto()
3475        VARBINARY = auto()
3476        VARCHAR = auto()
3477        VARIANT = auto()
3478        XML = auto()
3479
3480    TEXT_TYPES = {
3481        Type.CHAR,
3482        Type.NCHAR,
3483        Type.VARCHAR,
3484        Type.NVARCHAR,
3485        Type.TEXT,
3486    }
3487
3488    INTEGER_TYPES = {
3489        Type.INT,
3490        Type.TINYINT,
3491        Type.SMALLINT,
3492        Type.BIGINT,
3493        Type.INT128,
3494        Type.INT256,
3495    }
3496
3497    FLOAT_TYPES = {
3498        Type.FLOAT,
3499        Type.DOUBLE,
3500    }
3501
3502    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3503
3504    TEMPORAL_TYPES = {
3505        Type.TIME,
3506        Type.TIMETZ,
3507        Type.TIMESTAMP,
3508        Type.TIMESTAMPTZ,
3509        Type.TIMESTAMPLTZ,
3510        Type.DATE,
3511        Type.DATETIME,
3512        Type.DATETIME64,
3513    }
3514
3515    META_TYPES = {"UNKNOWN", "NULL"}
3516
3517    @classmethod
3518    def build(
3519        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3520    ) -> DataType:
3521        from sqlglot import parse_one
3522
3523        if isinstance(dtype, str):
3524            upper = dtype.upper()
3525            if upper in DataType.META_TYPES:
3526                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3527            else:
3528                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3529
3530            if data_type_exp is None:
3531                raise ValueError(f"Unparsable data type value: {dtype}")
3532        elif isinstance(dtype, DataType.Type):
3533            data_type_exp = DataType(this=dtype)
3534        elif isinstance(dtype, DataType):
3535            return dtype
3536        else:
3537            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3538
3539        return DataType(**{**data_type_exp.args, **kwargs})
3540
3541    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3542        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.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.TEXT: 'TEXT'>, <Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>}
INTEGER_TYPES = {<Type.INT128: 'INT128'>, <Type.INT256: 'INT256'>, <Type.BIGINT: 'BIGINT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>, <Type.SMALLINT: 'SMALLINT'>}
FLOAT_TYPES = {<Type.DOUBLE: 'DOUBLE'>, <Type.FLOAT: 'FLOAT'>}
NUMERIC_TYPES = {<Type.BIGINT: 'BIGINT'>, <Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>, <Type.DOUBLE: 'DOUBLE'>, <Type.INT128: 'INT128'>, <Type.SMALLINT: 'SMALLINT'>, <Type.FLOAT: 'FLOAT'>, <Type.INT256: 'INT256'>}
TEMPORAL_TYPES = {<Type.DATETIME64: 'DATETIME64'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATETIME: 'DATETIME'>, <Type.DATE: 'DATE'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.TIME: 'TIME'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.TIMETZ: 'TIMETZ'>}
META_TYPES = {'UNKNOWN', 'NULL'}
@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:
3517    @classmethod
3518    def build(
3519        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3520    ) -> DataType:
3521        from sqlglot import parse_one
3522
3523        if isinstance(dtype, str):
3524            upper = dtype.upper()
3525            if upper in DataType.META_TYPES:
3526                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3527            else:
3528                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3529
3530            if data_type_exp is None:
3531                raise ValueError(f"Unparsable data type value: {dtype}")
3532        elif isinstance(dtype, DataType.Type):
3533            data_type_exp = DataType(this=dtype)
3534        elif isinstance(dtype, DataType):
3535            return dtype
3536        else:
3537            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3538
3539        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3541    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3542        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3392    class Type(AutoName):
3393        ARRAY = auto()
3394        BIGDECIMAL = auto()
3395        BIGINT = auto()
3396        BIGSERIAL = auto()
3397        BINARY = auto()
3398        BIT = auto()
3399        BOOLEAN = auto()
3400        CHAR = auto()
3401        DATE = auto()
3402        DATEMULTIRANGE = auto()
3403        DATERANGE = auto()
3404        DATETIME = auto()
3405        DATETIME64 = auto()
3406        DECIMAL = auto()
3407        DOUBLE = auto()
3408        ENUM = auto()
3409        ENUM8 = auto()
3410        ENUM16 = auto()
3411        FIXEDSTRING = auto()
3412        FLOAT = auto()
3413        GEOGRAPHY = auto()
3414        GEOMETRY = auto()
3415        HLLSKETCH = auto()
3416        HSTORE = auto()
3417        IMAGE = auto()
3418        INET = auto()
3419        INT = auto()
3420        INT128 = auto()
3421        INT256 = auto()
3422        INT4MULTIRANGE = auto()
3423        INT4RANGE = auto()
3424        INT8MULTIRANGE = auto()
3425        INT8RANGE = auto()
3426        INTERVAL = auto()
3427        IPADDRESS = auto()
3428        IPPREFIX = auto()
3429        JSON = auto()
3430        JSONB = auto()
3431        LONGBLOB = auto()
3432        LONGTEXT = auto()
3433        LOWCARDINALITY = auto()
3434        MAP = auto()
3435        MEDIUMBLOB = auto()
3436        MEDIUMTEXT = auto()
3437        MONEY = auto()
3438        NCHAR = auto()
3439        NESTED = auto()
3440        NULL = auto()
3441        NULLABLE = auto()
3442        NUMMULTIRANGE = auto()
3443        NUMRANGE = auto()
3444        NVARCHAR = auto()
3445        OBJECT = auto()
3446        ROWVERSION = auto()
3447        SERIAL = auto()
3448        SET = auto()
3449        SMALLINT = auto()
3450        SMALLMONEY = auto()
3451        SMALLSERIAL = auto()
3452        STRUCT = auto()
3453        SUPER = auto()
3454        TEXT = auto()
3455        TIME = auto()
3456        TIMETZ = auto()
3457        TIMESTAMP = auto()
3458        TIMESTAMPLTZ = auto()
3459        TIMESTAMPTZ = auto()
3460        TINYINT = auto()
3461        TSMULTIRANGE = auto()
3462        TSRANGE = auto()
3463        TSTZMULTIRANGE = auto()
3464        TSTZRANGE = auto()
3465        UBIGINT = auto()
3466        UINT = auto()
3467        UINT128 = auto()
3468        UINT256 = auto()
3469        UNIQUEIDENTIFIER = auto()
3470        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3471        USERDEFINED = "USER-DEFINED"
3472        USMALLINT = auto()
3473        UTINYINT = auto()
3474        UUID = auto()
3475        VARBINARY = auto()
3476        VARCHAR = auto()
3477        VARIANT = auto()
3478        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'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
ENUM = <Type.ENUM: 'ENUM'>
ENUM8 = <Type.ENUM8: 'ENUM8'>
ENUM16 = <Type.ENUM16: 'ENUM16'>
FIXEDSTRING = <Type.FIXEDSTRING: 'FIXEDSTRING'>
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'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
IPADDRESS = <Type.IPADDRESS: 'IPADDRESS'>
IPPREFIX = <Type.IPPREFIX: 'IPPREFIX'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
LOWCARDINALITY = <Type.LOWCARDINALITY: 'LOWCARDINALITY'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NESTED = <Type.NESTED: 'NESTED'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
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'>
TIMETZ = <Type.TIMETZ: 'TIMETZ'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
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):
3546class PseudoType(Expression):
3547    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3551class SubqueryPredicate(Predicate):
3552    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3555class All(SubqueryPredicate):
3556    pass
key = 'all'
class Any(SubqueryPredicate):
3559class Any(SubqueryPredicate):
3560    pass
key = 'any'
class Exists(SubqueryPredicate):
3563class Exists(SubqueryPredicate):
3564    pass
key = 'exists'
class Command(Expression):
3569class Command(Expression):
3570    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3573class Transaction(Expression):
3574    arg_types = {"this": False, "modes": False, "mark": False}
arg_types = {'this': False, 'modes': False, 'mark': False}
key = 'transaction'
class Commit(Expression):
3577class Commit(Expression):
3578    arg_types = {"chain": False, "this": False, "durability": False}
arg_types = {'chain': False, 'this': False, 'durability': False}
key = 'commit'
class Rollback(Expression):
3581class Rollback(Expression):
3582    arg_types = {"savepoint": False, "this": False}
arg_types = {'savepoint': False, 'this': False}
key = 'rollback'
class AlterTable(Expression):
3585class AlterTable(Expression):
3586    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3589class AddConstraint(Expression):
3590    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3593class DropPartition(Expression):
3594    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3598class Binary(Condition):
3599    arg_types = {"this": True, "expression": True}
3600
3601    @property
3602    def left(self):
3603        return self.this
3604
3605    @property
3606    def right(self):
3607        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3610class Add(Binary):
3611    pass
key = 'add'
class Connector(Binary):
3614class Connector(Binary):
3615    pass
key = 'connector'
class And(Connector):
3618class And(Connector):
3619    pass
key = 'and'
class Or(Connector):
3622class Or(Connector):
3623    pass
key = 'or'
class BitwiseAnd(Binary):
3626class BitwiseAnd(Binary):
3627    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3630class BitwiseLeftShift(Binary):
3631    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3634class BitwiseOr(Binary):
3635    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3638class BitwiseRightShift(Binary):
3639    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3642class BitwiseXor(Binary):
3643    pass
key = 'bitwisexor'
class Div(Binary):
3646class Div(Binary):
3647    pass
key = 'div'
class Overlaps(Binary):
3650class Overlaps(Binary):
3651    pass
key = 'overlaps'
class Dot(Binary):
3654class Dot(Binary):
3655    @property
3656    def name(self) -> str:
3657        return self.expression.name
3658
3659    @property
3660    def output_name(self) -> str:
3661        return self.name
3662
3663    @classmethod
3664    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3665        """Build a Dot object with a sequence of expressions."""
3666        if len(expressions) < 2:
3667            raise ValueError(f"Dot requires >= 2 expressions.")
3668
3669        a, b, *expressions = expressions
3670        dot = Dot(this=a, expression=b)
3671
3672        for expression in expressions:
3673            dot = Dot(this=dot, expression=expression)
3674
3675        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:
3663    @classmethod
3664    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3665        """Build a Dot object with a sequence of expressions."""
3666        if len(expressions) < 2:
3667            raise ValueError(f"Dot requires >= 2 expressions.")
3668
3669        a, b, *expressions = expressions
3670        dot = Dot(this=a, expression=b)
3671
3672        for expression in expressions:
3673            dot = Dot(this=dot, expression=expression)
3674
3675        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3678class DPipe(Binary):
3679    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3682class SafeDPipe(DPipe):
3683    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3686class EQ(Binary, Predicate):
3687    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3690class NullSafeEQ(Binary, Predicate):
3691    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3694class NullSafeNEQ(Binary, Predicate):
3695    pass
key = 'nullsafeneq'
class Distance(Binary):
3698class Distance(Binary):
3699    pass
key = 'distance'
class Escape(Binary):
3702class Escape(Binary):
3703    pass
key = 'escape'
class Glob(Binary, Predicate):
3706class Glob(Binary, Predicate):
3707    pass
key = 'glob'
class GT(Binary, Predicate):
3710class GT(Binary, Predicate):
3711    pass
key = 'gt'
class GTE(Binary, Predicate):
3714class GTE(Binary, Predicate):
3715    pass
key = 'gte'
class ILike(Binary, Predicate):
3718class ILike(Binary, Predicate):
3719    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3722class ILikeAny(Binary, Predicate):
3723    pass
key = 'ilikeany'
class IntDiv(Binary):
3726class IntDiv(Binary):
3727    pass
key = 'intdiv'
class Is(Binary, Predicate):
3730class Is(Binary, Predicate):
3731    pass
key = 'is'
class Kwarg(Binary):
3734class Kwarg(Binary):
3735    """Kwarg in special functions like func(kwarg => y)."""

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

key = 'kwarg'
class Like(Binary, Predicate):
3738class Like(Binary, Predicate):
3739    pass
key = 'like'
class LikeAny(Binary, Predicate):
3742class LikeAny(Binary, Predicate):
3743    pass
key = 'likeany'
class LT(Binary, Predicate):
3746class LT(Binary, Predicate):
3747    pass
key = 'lt'
class LTE(Binary, Predicate):
3750class LTE(Binary, Predicate):
3751    pass
key = 'lte'
class Mod(Binary):
3754class Mod(Binary):
3755    pass
key = 'mod'
class Mul(Binary):
3758class Mul(Binary):
3759    pass
key = 'mul'
class NEQ(Binary, Predicate):
3762class NEQ(Binary, Predicate):
3763    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3766class SimilarTo(Binary, Predicate):
3767    pass
key = 'similarto'
class Slice(Binary):
3770class Slice(Binary):
3771    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3774class Sub(Binary):
3775    pass
key = 'sub'
class ArrayOverlaps(Binary):
3778class ArrayOverlaps(Binary):
3779    pass
key = 'arrayoverlaps'
class Unary(Condition):
3784class Unary(Condition):
3785    pass
key = 'unary'
class BitwiseNot(Unary):
3788class BitwiseNot(Unary):
3789    pass
key = 'bitwisenot'
class Not(Unary):
3792class Not(Unary):
3793    pass
key = 'not'
class Paren(Unary):
3796class Paren(Unary):
3797    arg_types = {"this": True, "with": False}
3798
3799    @property
3800    def output_name(self) -> str:
3801        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):
3804class Neg(Unary):
3805    pass
key = 'neg'
class Alias(Expression):
3808class Alias(Expression):
3809    arg_types = {"this": True, "alias": False}
3810
3811    @property
3812    def output_name(self) -> str:
3813        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):
3816class Aliases(Expression):
3817    arg_types = {"this": True, "expressions": True}
3818
3819    @property
3820    def aliases(self):
3821        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3824class AtTimeZone(Expression):
3825    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3828class Between(Predicate):
3829    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3832class Bracket(Condition):
3833    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class SafeBracket(Bracket):
3836class SafeBracket(Bracket):
3837    """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):
3840class Distinct(Expression):
3841    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3844class In(Predicate):
3845    arg_types = {
3846        "this": True,
3847        "expressions": False,
3848        "query": False,
3849        "unnest": False,
3850        "field": False,
3851        "is_global": False,
3852    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3855class TimeUnit(Expression):
3856    """Automatically converts unit arg into a var."""
3857
3858    arg_types = {"unit": False}
3859
3860    def __init__(self, **args):
3861        unit = args.get("unit")
3862        if isinstance(unit, (Column, Literal)):
3863            args["unit"] = Var(this=unit.name)
3864        elif isinstance(unit, Week):
3865            unit.set("this", Var(this=unit.this.name))
3866
3867        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3860    def __init__(self, **args):
3861        unit = args.get("unit")
3862        if isinstance(unit, (Column, Literal)):
3863            args["unit"] = Var(this=unit.name)
3864        elif isinstance(unit, Week):
3865            unit.set("this", Var(this=unit.this.name))
3866
3867        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class IntervalYearToMonthSpan(Expression):
3872class IntervalYearToMonthSpan(Expression):
3873    arg_types = {}
arg_types = {}
key = 'intervalyeartomonthspan'
class IntervalDayToSecondSpan(Expression):
3878class IntervalDayToSecondSpan(Expression):
3879    arg_types = {}
arg_types = {}
key = 'intervaldaytosecondspan'
class Interval(TimeUnit):
3882class Interval(TimeUnit):
3883    arg_types = {"this": False, "unit": False}
3884
3885    @property
3886    def unit(self) -> t.Optional[Var]:
3887        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3890class IgnoreNulls(Expression):
3891    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3894class RespectNulls(Expression):
3895    pass
key = 'respectnulls'
class Func(Condition):
3899class Func(Condition):
3900    """
3901    The base class for all function expressions.
3902
3903    Attributes:
3904        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3905            treated as a variable length argument and the argument's value will be stored as a list.
3906        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3907            for this function expression. These values are used to map this node to a name during parsing
3908            as well as to provide the function's name during SQL string generation. By default the SQL
3909            name is set to the expression's class name transformed to snake case.
3910    """
3911
3912    is_var_len_args = False
3913
3914    @classmethod
3915    def from_arg_list(cls, args):
3916        if cls.is_var_len_args:
3917            all_arg_keys = list(cls.arg_types)
3918            # If this function supports variable length argument treat the last argument as such.
3919            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3920            num_non_var = len(non_var_len_arg_keys)
3921
3922            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3923            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3924        else:
3925            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3926
3927        return cls(**args_dict)
3928
3929    @classmethod
3930    def sql_names(cls):
3931        if cls is Func:
3932            raise NotImplementedError(
3933                "SQL name is only supported by concrete function implementations"
3934            )
3935        if "_sql_names" not in cls.__dict__:
3936            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3937        return cls._sql_names
3938
3939    @classmethod
3940    def sql_name(cls):
3941        return cls.sql_names()[0]
3942
3943    @classmethod
3944    def default_parser_mappings(cls):
3945        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):
3914    @classmethod
3915    def from_arg_list(cls, args):
3916        if cls.is_var_len_args:
3917            all_arg_keys = list(cls.arg_types)
3918            # If this function supports variable length argument treat the last argument as such.
3919            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3920            num_non_var = len(non_var_len_arg_keys)
3921
3922            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3923            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3924        else:
3925            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3926
3927        return cls(**args_dict)
@classmethod
def sql_names(cls):
3929    @classmethod
3930    def sql_names(cls):
3931        if cls is Func:
3932            raise NotImplementedError(
3933                "SQL name is only supported by concrete function implementations"
3934            )
3935        if "_sql_names" not in cls.__dict__:
3936            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3937        return cls._sql_names
@classmethod
def sql_name(cls):
3939    @classmethod
3940    def sql_name(cls):
3941        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3943    @classmethod
3944    def default_parser_mappings(cls):
3945        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3948class AggFunc(Func):
3949    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3952class ParameterizedAgg(AggFunc):
3953    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3956class Abs(Func):
3957    pass
key = 'abs'
class Transform(Func):
3961class Transform(Func):
3962    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'transform'
class Anonymous(Func):
3965class Anonymous(Func):
3966    arg_types = {"this": True, "expressions": False}
3967    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3972class Hll(AggFunc):
3973    arg_types = {"this": True, "expressions": False}
3974    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3977class ApproxDistinct(AggFunc):
3978    arg_types = {"this": True, "accuracy": False}
3979    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3982class Array(Func):
3983    arg_types = {"expressions": False}
3984    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3988class ToChar(Func):
3989    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3992class GenerateSeries(Func):
3993    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3996class ArrayAgg(AggFunc):
3997    pass
key = 'arrayagg'
class ArrayAll(Func):
4000class ArrayAll(Func):
4001    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
4004class ArrayAny(Func):
4005    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
4008class ArrayConcat(Func):
4009    arg_types = {"this": True, "expressions": False}
4010    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
4013class ArrayContains(Binary, Func):
4014    pass
key = 'arraycontains'
class ArrayContained(Binary):
4017class ArrayContained(Binary):
4018    pass
key = 'arraycontained'
class ArrayFilter(Func):
4021class ArrayFilter(Func):
4022    arg_types = {"this": True, "expression": True}
4023    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
4026class ArrayJoin(Func):
4027    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
4030class ArraySize(Func):
4031    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
4034class ArraySort(Func):
4035    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
4038class ArraySum(Func):
4039    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
4042class ArrayUnionAgg(AggFunc):
4043    pass
key = 'arrayunionagg'
class Avg(AggFunc):
4046class Avg(AggFunc):
4047    pass
key = 'avg'
class AnyValue(AggFunc):
4050class AnyValue(AggFunc):
4051    arg_types = {"this": True, "having": False, "max": False}
arg_types = {'this': True, 'having': False, 'max': False}
key = 'anyvalue'
class Case(Func):
4054class Case(Func):
4055    arg_types = {"this": False, "ifs": True, "default": False}
4056
4057    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4058        instance = maybe_copy(self, copy)
4059        instance.append(
4060            "ifs",
4061            If(
4062                this=maybe_parse(condition, copy=copy, **opts),
4063                true=maybe_parse(then, copy=copy, **opts),
4064            ),
4065        )
4066        return instance
4067
4068    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4069        instance = maybe_copy(self, copy)
4070        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4071        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:
4057    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
4058        instance = maybe_copy(self, copy)
4059        instance.append(
4060            "ifs",
4061            If(
4062                this=maybe_parse(condition, copy=copy, **opts),
4063                true=maybe_parse(then, copy=copy, **opts),
4064            ),
4065        )
4066        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
4068    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
4069        instance = maybe_copy(self, copy)
4070        instance.set("default", maybe_parse(condition, copy=copy, **opts))
4071        return instance
key = 'case'
class Cast(Func):
4074class Cast(Func):
4075    arg_types = {"this": True, "to": True, "format": False}
4076
4077    @property
4078    def name(self) -> str:
4079        return self.this.name
4080
4081    @property
4082    def to(self) -> DataType:
4083        return self.args["to"]
4084
4085    @property
4086    def output_name(self) -> str:
4087        return self.name
4088
4089    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4090        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:
4089    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
4090        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
4093class CastToStrType(Func):
4094    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
4097class Collate(Binary):
4098    pass
key = 'collate'
class TryCast(Cast):
4101class TryCast(Cast):
4102    pass
key = 'trycast'
class Ceil(Func):
4105class Ceil(Func):
4106    arg_types = {"this": True, "decimals": False}
4107    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
4110class Coalesce(Func):
4111    arg_types = {"this": True, "expressions": False}
4112    is_var_len_args = True
4113    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
4116class Concat(Func):
4117    arg_types = {"expressions": True}
4118    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
4121class SafeConcat(Concat):
4122    pass
key = 'safeconcat'
class ConcatWs(Concat):
4125class ConcatWs(Concat):
4126    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
4129class Count(AggFunc):
4130    arg_types = {"this": False, "expressions": False}
4131    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
4134class CountIf(AggFunc):
4135    pass
key = 'countif'
class CurrentDate(Func):
4138class CurrentDate(Func):
4139    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4142class CurrentDatetime(Func):
4143    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4146class CurrentTime(Func):
4147    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4150class CurrentTimestamp(Func):
4151    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4154class CurrentUser(Func):
4155    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4158class DateAdd(Func, TimeUnit):
4159    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4162class DateSub(Func, TimeUnit):
4163    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4166class DateDiff(Func, TimeUnit):
4167    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4168    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4171class DateTrunc(Func):
4172    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4175class DatetimeAdd(Func, TimeUnit):
4176    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4179class DatetimeSub(Func, TimeUnit):
4180    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4183class DatetimeDiff(Func, TimeUnit):
4184    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4187class DatetimeTrunc(Func, TimeUnit):
4188    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4191class DayOfWeek(Func):
4192    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4195class DayOfMonth(Func):
4196    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4199class DayOfYear(Func):
4200    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4203class WeekOfYear(Func):
4204    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class MonthsBetween(Func):
4207class MonthsBetween(Func):
4208    arg_types = {"this": True, "expression": True, "roundoff": False}
arg_types = {'this': True, 'expression': True, 'roundoff': False}
key = 'monthsbetween'
class LastDateOfMonth(Func):
4211class LastDateOfMonth(Func):
4212    pass
key = 'lastdateofmonth'
class Extract(Func):
4215class Extract(Func):
4216    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4219class TimestampAdd(Func, TimeUnit):
4220    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4223class TimestampSub(Func, TimeUnit):
4224    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4227class TimestampDiff(Func, TimeUnit):
4228    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4231class TimestampTrunc(Func, TimeUnit):
4232    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4235class TimeAdd(Func, TimeUnit):
4236    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4239class TimeSub(Func, TimeUnit):
4240    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4243class TimeDiff(Func, TimeUnit):
4244    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4247class TimeTrunc(Func, TimeUnit):
4248    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4251class DateFromParts(Func):
4252    _sql_names = ["DATEFROMPARTS"]
4253    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4256class DateStrToDate(Func):
4257    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4260class DateToDateStr(Func):
4261    pass
key = 'datetodatestr'
class DateToDi(Func):
4264class DateToDi(Func):
4265    pass
key = 'datetodi'
class Date(Func):
4269class Date(Func):
4270    arg_types = {"this": True, "zone": False}
arg_types = {'this': True, 'zone': False}
key = 'date'
class Day(Func):
4273class Day(Func):
4274    pass
key = 'day'
class Decode(Func):
4277class Decode(Func):
4278    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4281class DiToDate(Func):
4282    pass
key = 'ditodate'
class Encode(Func):
4285class Encode(Func):
4286    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4289class Exp(Func):
4290    pass
key = 'exp'
class Explode(Func):
4293class Explode(Func):
4294    pass
key = 'explode'
class Floor(Func):
4297class Floor(Func):
4298    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4301class FromBase64(Func):
4302    pass
key = 'frombase64'
class ToBase64(Func):
4305class ToBase64(Func):
4306    pass
key = 'tobase64'
class Greatest(Func):
4309class Greatest(Func):
4310    arg_types = {"this": True, "expressions": False}
4311    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4314class GroupConcat(Func):
4315    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4318class Hex(Func):
4319    pass
key = 'hex'
class Xor(Connector, Func):
4322class Xor(Connector, Func):
4323    arg_types = {"this": False, "expression": False, "expressions": False}
arg_types = {'this': False, 'expression': False, 'expressions': False}
key = 'xor'
class If(Func):
4326class If(Func):
4327    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4330class Initcap(Func):
4331    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class IsNan(Func):
4334class IsNan(Func):
4335    _sql_names = ["IS_NAN", "ISNAN"]
key = 'isnan'
class JSONKeyValue(Expression):
4338class JSONKeyValue(Expression):
4339    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4342class JSONObject(Func):
4343    arg_types = {
4344        "expressions": False,
4345        "null_handling": False,
4346        "unique_keys": False,
4347        "return_type": False,
4348        "format_json": False,
4349        "encoding": False,
4350    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4353class OpenJSONColumnDef(Expression):
4354    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):
4357class OpenJSON(Func):
4358    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4361class JSONBContains(Binary):
4362    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4365class JSONExtract(Binary, Func):
4366    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4369class JSONExtractScalar(JSONExtract):
4370    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4373class JSONBExtract(JSONExtract):
4374    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4377class JSONBExtractScalar(JSONExtract):
4378    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4381class JSONFormat(Func):
4382    arg_types = {"this": False, "options": False}
4383    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class JSONArrayContains(Binary, Predicate, Func):
4387class JSONArrayContains(Binary, Predicate, Func):
4388    _sql_names = ["JSON_ARRAY_CONTAINS"]
key = 'jsonarraycontains'
class Least(Func):
4391class Least(Func):
4392    arg_types = {"this": True, "expressions": False}
4393    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4396class Left(Func):
4397    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4404class Length(Func):
4405    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4408class Levenshtein(Func):
4409    arg_types = {
4410        "this": True,
4411        "expression": False,
4412        "ins_cost": False,
4413        "del_cost": False,
4414        "sub_cost": False,
4415    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4418class Ln(Func):
4419    pass
key = 'ln'
class Log(Func):
4422class Log(Func):
4423    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4426class Log2(Func):
4427    pass
key = 'log2'
class Log10(Func):
4430class Log10(Func):
4431    pass
key = 'log10'
class LogicalOr(AggFunc):
4434class LogicalOr(AggFunc):
4435    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4438class LogicalAnd(AggFunc):
4439    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4442class Lower(Func):
4443    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4446class Map(Func):
4447    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class MapFromEntries(Func):
4450class MapFromEntries(Func):
4451    pass
key = 'mapfromentries'
class StarMap(Func):
4454class StarMap(Func):
4455    pass
key = 'starmap'
class VarMap(Func):
4458class VarMap(Func):
4459    arg_types = {"keys": True, "values": True}
4460    is_var_len_args = True
4461
4462    @property
4463    def keys(self) -> t.List[Expression]:
4464        return self.args["keys"].expressions
4465
4466    @property
4467    def values(self) -> t.List[Expression]:
4468        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4472class MatchAgainst(Func):
4473    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4476class Max(AggFunc):
4477    arg_types = {"this": True, "expressions": False}
4478    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4481class MD5(Func):
4482    _sql_names = ["MD5"]
key = 'md5'
class MD5Digest(Func):
4486class MD5Digest(Func):
4487    _sql_names = ["MD5_DIGEST"]
key = 'md5digest'
class Min(AggFunc):
4490class Min(AggFunc):
4491    arg_types = {"this": True, "expressions": False}
4492    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4495class Month(Func):
4496    pass
key = 'month'
class Nvl2(Func):
4499class Nvl2(Func):
4500    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4503class Posexplode(Func):
4504    pass
key = 'posexplode'
class Pow(Binary, Func):
4507class Pow(Binary, Func):
4508    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4511class PercentileCont(AggFunc):
4512    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4515class PercentileDisc(AggFunc):
4516    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4519class Quantile(AggFunc):
4520    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4523class ApproxQuantile(Quantile):
4524    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):
4527class RangeN(Func):
4528    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4531class ReadCSV(Func):
4532    _sql_names = ["READ_CSV"]
4533    is_var_len_args = True
4534    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4537class Reduce(Func):
4538    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):
4541class RegexpExtract(Func):
4542    arg_types = {
4543        "this": True,
4544        "expression": True,
4545        "position": False,
4546        "occurrence": False,
4547        "parameters": False,
4548        "group": False,
4549    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'parameters': False, 'group': False}
key = 'regexpextract'
class RegexpReplace(Func):
4552class RegexpReplace(Func):
4553    arg_types = {
4554        "this": True,
4555        "expression": True,
4556        "replacement": True,
4557        "position": False,
4558        "occurrence": False,
4559        "parameters": False,
4560    }
arg_types = {'this': True, 'expression': True, 'replacement': True, 'position': False, 'occurrence': False, 'parameters': False}
key = 'regexpreplace'
class RegexpLike(Binary, Func):
4563class RegexpLike(Binary, Func):
4564    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4567class RegexpILike(Func):
4568    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4573class RegexpSplit(Func):
4574    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4577class Repeat(Func):
4578    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4581class Round(Func):
4582    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4585class RowNumber(Func):
4586    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4589class SafeDivide(Func):
4590    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4593class SetAgg(AggFunc):
4594    pass
key = 'setagg'
class SHA(Func):
4597class SHA(Func):
4598    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4601class SHA2(Func):
4602    _sql_names = ["SHA2"]
4603    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4606class SortArray(Func):
4607    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4610class Split(Func):
4611    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4616class Substring(Func):
4617    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4620class StandardHash(Func):
4621    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StartsWith(Func):
4624class StartsWith(Func):
4625    _sql_names = ["STARTS_WITH", "STARTSWITH"]
4626    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'startswith'
class StrPosition(Func):
4629class StrPosition(Func):
4630    arg_types = {
4631        "this": True,
4632        "substr": True,
4633        "position": False,
4634        "instance": False,
4635    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4638class StrToDate(Func):
4639    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4642class StrToTime(Func):
4643    arg_types = {"this": True, "format": True, "zone": False}
arg_types = {'this': True, 'format': True, 'zone': False}
key = 'strtotime'
class StrToUnix(Func):
4648class StrToUnix(Func):
4649    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4652class NumberToStr(Func):
4653    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4656class FromBase(Func):
4657    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4660class Struct(Func):
4661    arg_types = {"expressions": True}
4662    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4665class StructExtract(Func):
4666    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4669class Sum(AggFunc):
4670    pass
key = 'sum'
class Sqrt(Func):
4673class Sqrt(Func):
4674    pass
key = 'sqrt'
class Stddev(AggFunc):
4677class Stddev(AggFunc):
4678    pass
key = 'stddev'
class StddevPop(AggFunc):
4681class StddevPop(AggFunc):
4682    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4685class StddevSamp(AggFunc):
4686    pass
key = 'stddevsamp'
class TimeToStr(Func):
4689class TimeToStr(Func):
4690    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4693class TimeToTimeStr(Func):
4694    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4697class TimeToUnix(Func):
4698    pass
key = 'timetounix'
class TimeStrToDate(Func):
4701class TimeStrToDate(Func):
4702    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4705class TimeStrToTime(Func):
4706    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4709class TimeStrToUnix(Func):
4710    pass
key = 'timestrtounix'
class Trim(Func):
4713class Trim(Func):
4714    arg_types = {
4715        "this": True,
4716        "expression": False,
4717        "position": False,
4718        "collation": False,
4719    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4722class TsOrDsAdd(Func, TimeUnit):
4723    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4726class TsOrDsToDateStr(Func):
4727    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4730class TsOrDsToDate(Func):
4731    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4734class TsOrDiToDi(Func):
4735    pass
key = 'tsorditodi'
class Unhex(Func):
4738class Unhex(Func):
4739    pass
key = 'unhex'
class UnixToStr(Func):
4742class UnixToStr(Func):
4743    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4748class UnixToTime(Func):
4749    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4750
4751    SECONDS = Literal.string("seconds")
4752    MILLIS = Literal.string("millis")
4753    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):
4756class UnixToTimeStr(Func):
4757    pass
key = 'unixtotimestr'
class Upper(Func):
4760class Upper(Func):
4761    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4764class Variance(AggFunc):
4765    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4768class VariancePop(AggFunc):
4769    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4772class Week(Func):
4773    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4776class XMLTable(Func):
4777    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):
4780class Year(Func):
4781    pass
key = 'year'
class Use(Expression):
4784class Use(Expression):
4785    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4788class Merge(Expression):
4789    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):
4792class When(Func):
4793    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):
4798class NextValueFor(Func):
4799    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.IsNan'>, <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.MD5Digest'>, <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.MonthsBetween'>, <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.RegexpReplace'>, <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.StartsWith'>, <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.Transform'>, <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.Xor'>, <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:
4836def maybe_parse(
4837    sql_or_expression: ExpOrStr,
4838    *,
4839    into: t.Optional[IntoType] = None,
4840    dialect: DialectType = None,
4841    prefix: t.Optional[str] = None,
4842    copy: bool = False,
4843    **opts,
4844) -> Expression:
4845    """Gracefully handle a possible string or expression.
4846
4847    Example:
4848        >>> maybe_parse("1")
4849        (LITERAL this: 1, is_string: False)
4850        >>> maybe_parse(to_identifier("x"))
4851        (IDENTIFIER this: x, quoted: False)
4852
4853    Args:
4854        sql_or_expression: the SQL code string or an expression
4855        into: the SQLGlot Expression to parse into
4856        dialect: the dialect used to parse the input expressions (in the case that an
4857            input expression is a SQL string).
4858        prefix: a string to prefix the sql with before it gets parsed
4859            (automatically includes a space)
4860        copy: whether or not to copy the expression.
4861        **opts: other options to use to parse the input expressions (again, in the case
4862            that an input expression is a SQL string).
4863
4864    Returns:
4865        Expression: the parsed or given expression.
4866    """
4867    if isinstance(sql_or_expression, Expression):
4868        if copy:
4869            return sql_or_expression.copy()
4870        return sql_or_expression
4871
4872    if sql_or_expression is None:
4873        raise ParseError(f"SQL cannot be None")
4874
4875    import sqlglot
4876
4877    sql = str(sql_or_expression)
4878    if prefix:
4879        sql = f"{prefix} {sql}"
4880
4881    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 maybe_copy(instance, copy=True):
4894def maybe_copy(instance, copy=True):
4895    return instance.copy() if copy and instance else instance
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:
5075def union(
5076    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5077) -> Union:
5078    """
5079    Initializes a syntax tree from one UNION expression.
5080
5081    Example:
5082        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
5083        'SELECT * FROM foo UNION SELECT * FROM bla'
5084
5085    Args:
5086        left: the SQL code string corresponding to the left-hand side.
5087            If an `Expression` instance is passed, it will be used as-is.
5088        right: the SQL code string corresponding to the right-hand side.
5089            If an `Expression` instance is passed, it will be used as-is.
5090        distinct: set the DISTINCT flag if and only if this is true.
5091        dialect: the dialect used to parse the input expression.
5092        opts: other options to use to parse the input expressions.
5093
5094    Returns:
5095        The new Union instance.
5096    """
5097    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5098    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5099
5100    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:
5103def intersect(
5104    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5105) -> Intersect:
5106    """
5107    Initializes a syntax tree from one INTERSECT expression.
5108
5109    Example:
5110        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
5111        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
5112
5113    Args:
5114        left: the SQL code string corresponding to the left-hand side.
5115            If an `Expression` instance is passed, it will be used as-is.
5116        right: the SQL code string corresponding to the right-hand side.
5117            If an `Expression` instance is passed, it will be used as-is.
5118        distinct: set the DISTINCT flag if and only if this is true.
5119        dialect: the dialect used to parse the input expression.
5120        opts: other options to use to parse the input expressions.
5121
5122    Returns:
5123        The new Intersect instance.
5124    """
5125    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5126    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5127
5128    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:
5131def except_(
5132    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
5133) -> Except:
5134    """
5135    Initializes a syntax tree from one EXCEPT expression.
5136
5137    Example:
5138        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
5139        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
5140
5141    Args:
5142        left: the SQL code string corresponding to the left-hand side.
5143            If an `Expression` instance is passed, it will be used as-is.
5144        right: the SQL code string corresponding to the right-hand side.
5145            If an `Expression` instance is passed, it will be used as-is.
5146        distinct: set the DISTINCT flag if and only if this is true.
5147        dialect: the dialect used to parse the input expression.
5148        opts: other options to use to parse the input expressions.
5149
5150    Returns:
5151        The new Except instance.
5152    """
5153    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
5154    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
5155
5156    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:
5159def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5160    """
5161    Initializes a syntax tree from one or multiple SELECT expressions.
5162
5163    Example:
5164        >>> select("col1", "col2").from_("tbl").sql()
5165        'SELECT col1, col2 FROM tbl'
5166
5167    Args:
5168        *expressions: the SQL code string to parse as the expressions of a
5169            SELECT statement. If an Expression instance is passed, this is used as-is.
5170        dialect: the dialect used to parse the input expressions (in the case that an
5171            input expression is a SQL string).
5172        **opts: other options to use to parse the input expressions (again, in the case
5173            that an input expression is a SQL string).
5174
5175    Returns:
5176        Select: the syntax tree for the SELECT statement.
5177    """
5178    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:
5181def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
5182    """
5183    Initializes a syntax tree from a FROM expression.
5184
5185    Example:
5186        >>> from_("tbl").select("col1", "col2").sql()
5187        'SELECT col1, col2 FROM tbl'
5188
5189    Args:
5190        *expression: the SQL code string to parse as the FROM expressions of a
5191            SELECT statement. If an Expression instance is passed, this is used as-is.
5192        dialect: the dialect used to parse the input expression (in the case that the
5193            input expression is a SQL string).
5194        **opts: other options to use to parse the input expressions (again, in the case
5195            that the input expression is a SQL string).
5196
5197    Returns:
5198        Select: the syntax tree for the SELECT statement.
5199    """
5200    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:
5203def update(
5204    table: str | Table,
5205    properties: dict,
5206    where: t.Optional[ExpOrStr] = None,
5207    from_: t.Optional[ExpOrStr] = None,
5208    dialect: DialectType = None,
5209    **opts,
5210) -> Update:
5211    """
5212    Creates an update statement.
5213
5214    Example:
5215        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5216        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5217
5218    Args:
5219        *properties: dictionary of properties to set which are
5220            auto converted to sql objects eg None -> NULL
5221        where: sql conditional parsed into a WHERE statement
5222        from_: sql statement parsed into a FROM statement
5223        dialect: the dialect used to parse the input expressions.
5224        **opts: other options to use to parse the input expressions.
5225
5226    Returns:
5227        Update: the syntax tree for the UPDATE statement.
5228    """
5229    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5230    update_expr.set(
5231        "expressions",
5232        [
5233            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5234            for k, v in properties.items()
5235        ],
5236    )
5237    if from_:
5238        update_expr.set(
5239            "from",
5240            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5241        )
5242    if isinstance(where, Condition):
5243        where = Where(this=where)
5244    if where:
5245        update_expr.set(
5246            "where",
5247            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5248        )
5249    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:
5252def delete(
5253    table: ExpOrStr,
5254    where: t.Optional[ExpOrStr] = None,
5255    returning: t.Optional[ExpOrStr] = None,
5256    dialect: DialectType = None,
5257    **opts,
5258) -> Delete:
5259    """
5260    Builds a delete statement.
5261
5262    Example:
5263        >>> delete("my_table", where="id > 1").sql()
5264        'DELETE FROM my_table WHERE id > 1'
5265
5266    Args:
5267        where: sql conditional parsed into a WHERE statement
5268        returning: sql conditional parsed into a RETURNING statement
5269        dialect: the dialect used to parse the input expressions.
5270        **opts: other options to use to parse the input expressions.
5271
5272    Returns:
5273        Delete: the syntax tree for the DELETE statement.
5274    """
5275    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5276    if where:
5277        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5278    if returning:
5279        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5280    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:
5283def insert(
5284    expression: ExpOrStr,
5285    into: ExpOrStr,
5286    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5287    overwrite: t.Optional[bool] = None,
5288    dialect: DialectType = None,
5289    copy: bool = True,
5290    **opts,
5291) -> Insert:
5292    """
5293    Builds an INSERT statement.
5294
5295    Example:
5296        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5297        'INSERT INTO tbl VALUES (1, 2, 3)'
5298
5299    Args:
5300        expression: the sql string or expression of the INSERT statement
5301        into: the tbl to insert data to.
5302        columns: optionally the table's column names.
5303        overwrite: whether to INSERT OVERWRITE or not.
5304        dialect: the dialect used to parse the input expressions.
5305        copy: whether or not to copy the expression.
5306        **opts: other options to use to parse the input expressions.
5307
5308    Returns:
5309        Insert: the syntax tree for the INSERT statement.
5310    """
5311    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5312    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5313
5314    if columns:
5315        this = _apply_list_builder(
5316            *columns,
5317            instance=Schema(this=this),
5318            arg="expressions",
5319            into=Identifier,
5320            copy=False,
5321            dialect=dialect,
5322            **opts,
5323        )
5324
5325    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:
5328def condition(
5329    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5330) -> Condition:
5331    """
5332    Initialize a logical condition expression.
5333
5334    Example:
5335        >>> condition("x=1").sql()
5336        'x = 1'
5337
5338        This is helpful for composing larger logical syntax trees:
5339        >>> where = condition("x=1")
5340        >>> where = where.and_("y=1")
5341        >>> Select().from_("tbl").select("*").where(where).sql()
5342        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5343
5344    Args:
5345        *expression: the SQL code string to parse.
5346            If an Expression instance is passed, this is used as-is.
5347        dialect: the dialect used to parse the input expression (in the case that the
5348            input expression is a SQL string).
5349        copy: Whether or not to copy `expression` (only applies to expressions).
5350        **opts: other options to use to parse the input expressions (again, in the case
5351            that the input expression is a SQL string).
5352
5353    Returns:
5354        The new Condition instance
5355    """
5356    return maybe_parse(
5357        expression,
5358        into=Condition,
5359        dialect=dialect,
5360        copy=copy,
5361        **opts,
5362    )

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:
5365def and_(
5366    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5367) -> Condition:
5368    """
5369    Combine multiple conditions with an AND logical operator.
5370
5371    Example:
5372        >>> and_("x=1", and_("y=1", "z=1")).sql()
5373        'x = 1 AND (y = 1 AND z = 1)'
5374
5375    Args:
5376        *expressions: the SQL code strings to parse.
5377            If an Expression instance is passed, this is used as-is.
5378        dialect: the dialect used to parse the input expression.
5379        copy: whether or not to copy `expressions` (only applies to Expressions).
5380        **opts: other options to use to parse the input expressions.
5381
5382    Returns:
5383        And: the new condition
5384    """
5385    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:
5388def or_(
5389    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5390) -> Condition:
5391    """
5392    Combine multiple conditions with an OR logical operator.
5393
5394    Example:
5395        >>> or_("x=1", or_("y=1", "z=1")).sql()
5396        'x = 1 OR (y = 1 OR z = 1)'
5397
5398    Args:
5399        *expressions: the SQL code strings to parse.
5400            If an Expression instance is passed, this is used as-is.
5401        dialect: the dialect used to parse the input expression.
5402        copy: whether or not to copy `expressions` (only applies to Expressions).
5403        **opts: other options to use to parse the input expressions.
5404
5405    Returns:
5406        Or: the new condition
5407    """
5408    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:
5411def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5412    """
5413    Wrap a condition with a NOT operator.
5414
5415    Example:
5416        >>> not_("this_suit='black'").sql()
5417        "NOT this_suit = 'black'"
5418
5419    Args:
5420        expression: the SQL code string to parse.
5421            If an Expression instance is passed, this is used as-is.
5422        dialect: the dialect used to parse the input expression.
5423        copy: whether to copy the expression or not.
5424        **opts: other options to use to parse the input expressions.
5425
5426    Returns:
5427        The new condition.
5428    """
5429    this = condition(
5430        expression,
5431        dialect=dialect,
5432        copy=copy,
5433        **opts,
5434    )
5435    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:
5438def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5439    """
5440    Wrap an expression in parentheses.
5441
5442    Example:
5443        >>> paren("5 + 3").sql()
5444        '(5 + 3)'
5445
5446    Args:
5447        expression: the SQL code string to parse.
5448            If an Expression instance is passed, this is used as-is.
5449        copy: whether to copy the expression or not.
5450
5451    Returns:
5452        The wrapped expression.
5453    """
5454    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):
5472def to_identifier(name, quoted=None, copy=True):
5473    """Builds an identifier.
5474
5475    Args:
5476        name: The name to turn into an identifier.
5477        quoted: Whether or not force quote the identifier.
5478        copy: Whether or not to copy a passed in Identefier node.
5479
5480    Returns:
5481        The identifier ast node.
5482    """
5483
5484    if name is None:
5485        return None
5486
5487    if isinstance(name, Identifier):
5488        identifier = maybe_copy(name, copy)
5489    elif isinstance(name, str):
5490        identifier = Identifier(
5491            this=name,
5492            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5493        )
5494    else:
5495        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5496    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:
5502def to_interval(interval: str | Literal) -> Interval:
5503    """Builds an interval expression from a string like '1 day' or '5 months'."""
5504    if isinstance(interval, Literal):
5505        if not interval.is_string:
5506            raise ValueError("Invalid interval string.")
5507
5508        interval = interval.this
5509
5510    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5511
5512    if not interval_parts:
5513        raise ValueError("Invalid interval string.")
5514
5515    return Interval(
5516        this=Literal.string(interval_parts.group(1)),
5517        unit=Var(this=interval_parts.group(2)),
5518    )

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]:
5531def to_table(
5532    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5533) -> t.Optional[Table]:
5534    """
5535    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5536    If a table is passed in then that table is returned.
5537
5538    Args:
5539        sql_path: a `[catalog].[schema].[table]` string.
5540        dialect: the source dialect according to which the table name will be parsed.
5541        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5542
5543    Returns:
5544        A table expression.
5545    """
5546    if sql_path is None or isinstance(sql_path, Table):
5547        return sql_path
5548    if not isinstance(sql_path, str):
5549        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5550
5551    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5552    if table:
5553        for k, v in kwargs.items():
5554            table.set(k, v)
5555
5556    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:
5559def to_column(sql_path: str | Column, **kwargs) -> Column:
5560    """
5561    Create a column from a `[table].[column]` sql path. Schema is optional.
5562
5563    If a column is passed in then that column is returned.
5564
5565    Args:
5566        sql_path: `[table].[column]` string
5567    Returns:
5568        Table: A column expression
5569    """
5570    if sql_path is None or isinstance(sql_path, Column):
5571        return sql_path
5572    if not isinstance(sql_path, str):
5573        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5574    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):
5577def alias_(
5578    expression: ExpOrStr,
5579    alias: str | Identifier,
5580    table: bool | t.Sequence[str | Identifier] = False,
5581    quoted: t.Optional[bool] = None,
5582    dialect: DialectType = None,
5583    copy: bool = True,
5584    **opts,
5585):
5586    """Create an Alias expression.
5587
5588    Example:
5589        >>> alias_('foo', 'bar').sql()
5590        'foo AS bar'
5591
5592        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5593        '(SELECT 1, 2) AS bar(a, b)'
5594
5595    Args:
5596        expression: the SQL code strings to parse.
5597            If an Expression instance is passed, this is used as-is.
5598        alias: the alias name to use. If the name has
5599            special characters it is quoted.
5600        table: Whether or not to create a table alias, can also be a list of columns.
5601        quoted: whether or not to quote the alias
5602        dialect: the dialect used to parse the input expression.
5603        copy: Whether or not to copy the expression.
5604        **opts: other options to use to parse the input expressions.
5605
5606    Returns:
5607        Alias: the aliased expression
5608    """
5609    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5610    alias = to_identifier(alias, quoted=quoted)
5611
5612    if table:
5613        table_alias = TableAlias(this=alias)
5614        exp.set("alias", table_alias)
5615
5616        if not isinstance(table, bool):
5617            for column in table:
5618                table_alias.append("columns", to_identifier(column, quoted=quoted))
5619
5620        return exp
5621
5622    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5623    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5624    # for the complete Window expression.
5625    #
5626    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5627
5628    if "alias" in exp.arg_types and not isinstance(exp, Window):
5629        exp.set("alias", alias)
5630        return exp
5631    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:
5634def subquery(
5635    expression: ExpOrStr,
5636    alias: t.Optional[Identifier | str] = None,
5637    dialect: DialectType = None,
5638    **opts,
5639) -> Select:
5640    """
5641    Build a subquery expression.
5642
5643    Example:
5644        >>> subquery('select x from tbl', 'bar').select('x').sql()
5645        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5646
5647    Args:
5648        expression: the SQL code strings to parse.
5649            If an Expression instance is passed, this is used as-is.
5650        alias: the alias name to use.
5651        dialect: the dialect used to parse the input expression.
5652        **opts: other options to use to parse the input expressions.
5653
5654    Returns:
5655        A new Select instance with the subquery expression included.
5656    """
5657
5658    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5659    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:
5662def column(
5663    col: str | Identifier,
5664    table: t.Optional[str | Identifier] = None,
5665    db: t.Optional[str | Identifier] = None,
5666    catalog: t.Optional[str | Identifier] = None,
5667    quoted: t.Optional[bool] = None,
5668) -> Column:
5669    """
5670    Build a Column.
5671
5672    Args:
5673        col: Column name.
5674        table: Table name.
5675        db: Database name.
5676        catalog: Catalog name.
5677        quoted: Whether to force quotes on the column's identifiers.
5678
5679    Returns:
5680        The new Column instance.
5681    """
5682    return Column(
5683        this=to_identifier(col, quoted=quoted),
5684        table=to_identifier(table, quoted=quoted),
5685        db=to_identifier(db, quoted=quoted),
5686        catalog=to_identifier(catalog, quoted=quoted),
5687    )

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:
5690def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5691    """Cast an expression to a data type.
5692
5693    Example:
5694        >>> cast('x + 1', 'int').sql()
5695        'CAST(x + 1 AS INT)'
5696
5697    Args:
5698        expression: The expression to cast.
5699        to: The datatype to cast to.
5700
5701    Returns:
5702        The new Cast instance.
5703    """
5704    expression = maybe_parse(expression, **opts)
5705    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:
5708def table_(
5709    table: Identifier | str,
5710    db: t.Optional[Identifier | str] = None,
5711    catalog: t.Optional[Identifier | str] = None,
5712    quoted: t.Optional[bool] = None,
5713    alias: t.Optional[Identifier | str] = None,
5714) -> Table:
5715    """Build a Table.
5716
5717    Args:
5718        table: Table name.
5719        db: Database name.
5720        catalog: Catalog name.
5721        quote: Whether to force quotes on the table's identifiers.
5722        alias: Table's alias.
5723
5724    Returns:
5725        The new Table instance.
5726    """
5727    return Table(
5728        this=to_identifier(table, quoted=quoted),
5729        db=to_identifier(db, quoted=quoted),
5730        catalog=to_identifier(catalog, quoted=quoted),
5731        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5732    )

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:
5735def values(
5736    values: t.Iterable[t.Tuple[t.Any, ...]],
5737    alias: t.Optional[str] = None,
5738    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5739) -> Values:
5740    """Build VALUES statement.
5741
5742    Example:
5743        >>> values([(1, '2')]).sql()
5744        "VALUES (1, '2')"
5745
5746    Args:
5747        values: values statements that will be converted to SQL
5748        alias: optional alias
5749        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5750         If either are provided then an alias is also required.
5751
5752    Returns:
5753        Values: the Values expression object
5754    """
5755    if columns and not alias:
5756        raise ValueError("Alias is required when providing columns")
5757
5758    return Values(
5759        expressions=[convert(tup) for tup in values],
5760        alias=(
5761            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5762            if columns
5763            else (TableAlias(this=to_identifier(alias)) if alias else None)
5764        ),
5765    )

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:
5768def var(name: t.Optional[ExpOrStr]) -> Var:
5769    """Build a SQL variable.
5770
5771    Example:
5772        >>> repr(var('x'))
5773        '(VAR this: x)'
5774
5775        >>> repr(var(column('x', table='y')))
5776        '(VAR this: x)'
5777
5778    Args:
5779        name: The name of the var or an expression who's name will become the var.
5780
5781    Returns:
5782        The new variable node.
5783    """
5784    if not name:
5785        raise ValueError("Cannot convert empty name into var.")
5786
5787    if isinstance(name, Expression):
5788        name = name.name
5789    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:
5792def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5793    """Build ALTER TABLE... RENAME... expression
5794
5795    Args:
5796        old_name: The old name of the table
5797        new_name: The new name of the table
5798
5799    Returns:
5800        Alter table expression
5801    """
5802    old_table = to_table(old_name)
5803    new_table = to_table(new_name)
5804    return AlterTable(
5805        this=old_table,
5806        actions=[
5807            RenameTable(this=new_table),
5808        ],
5809    )

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:
5812def convert(value: t.Any, copy: bool = False) -> Expression:
5813    """Convert a python value into an expression object.
5814
5815    Raises an error if a conversion is not possible.
5816
5817    Args:
5818        value: A python object.
5819        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5820
5821    Returns:
5822        Expression: the equivalent expression object.
5823    """
5824    if isinstance(value, Expression):
5825        return maybe_copy(value, copy)
5826    if isinstance(value, str):
5827        return Literal.string(value)
5828    if isinstance(value, bool):
5829        return Boolean(this=value)
5830    if value is None or (isinstance(value, float) and math.isnan(value)):
5831        return NULL
5832    if isinstance(value, numbers.Number):
5833        return Literal.number(value)
5834    if isinstance(value, datetime.datetime):
5835        datetime_literal = Literal.string(
5836            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5837        )
5838        return TimeStrToTime(this=datetime_literal)
5839    if isinstance(value, datetime.date):
5840        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5841        return DateStrToDate(this=date_literal)
5842    if isinstance(value, tuple):
5843        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5844    if isinstance(value, list):
5845        return Array(expressions=[convert(v, copy=copy) for v in value])
5846    if isinstance(value, dict):
5847        return Map(
5848            keys=[convert(k, copy=copy) for k in value],
5849            values=[convert(v, copy=copy) for v in value.values()],
5850        )
5851    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:
5854def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5855    """
5856    Replace children of an expression with the result of a lambda fun(child) -> exp.
5857    """
5858    for k, v in expression.args.items():
5859        is_list_arg = type(v) is list
5860
5861        child_nodes = v if is_list_arg else [v]
5862        new_child_nodes = []
5863
5864        for cn in child_nodes:
5865            if isinstance(cn, Expression):
5866                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5867                    new_child_nodes.append(child_node)
5868                    child_node.parent = expression
5869                    child_node.arg_key = k
5870            else:
5871                new_child_nodes.append(cn)
5872
5873        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]:
5876def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5877    """
5878    Return all table names referenced through columns in an expression.
5879
5880    Example:
5881        >>> import sqlglot
5882        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5883        ['a', 'c']
5884
5885    Args:
5886        expression: expression to find table names.
5887        exclude: a table name to exclude
5888
5889    Returns:
5890        A list of unique names.
5891    """
5892    return {
5893        table
5894        for table in (column.table for column in expression.find_all(Column))
5895        if table and table != exclude
5896    }

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:
5899def table_name(table: Table | str, dialect: DialectType = None) -> str:
5900    """Get the full name of a table as a string.
5901
5902    Args:
5903        table: Table expression node or string.
5904        dialect: The dialect to generate the table name for.
5905
5906    Examples:
5907        >>> from sqlglot import exp, parse_one
5908        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5909        'a.b.c'
5910
5911    Returns:
5912        The table name.
5913    """
5914
5915    table = maybe_parse(table, into=Table)
5916
5917    if not table:
5918        raise ValueError(f"Cannot parse {table}")
5919
5920    return ".".join(
5921        part.sql(dialect=dialect, identify=True)
5922        if not SAFE_IDENTIFIER_RE.match(part.name)
5923        else part.name
5924        for part in table.parts
5925    )

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:
5928def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5929    """Replace all tables in expression according to the mapping.
5930
5931    Args:
5932        expression: expression node to be transformed and replaced.
5933        mapping: mapping of table names.
5934        copy: whether or not to copy the expression.
5935
5936    Examples:
5937        >>> from sqlglot import exp, parse_one
5938        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5939        'SELECT * FROM c'
5940
5941    Returns:
5942        The mapped expression.
5943    """
5944
5945    def _replace_tables(node: Expression) -> Expression:
5946        if isinstance(node, Table):
5947            new_name = mapping.get(table_name(node))
5948            if new_name:
5949                return to_table(
5950                    new_name,
5951                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5952                )
5953        return node
5954
5955    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:
5958def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5959    """Replace placeholders in an expression.
5960
5961    Args:
5962        expression: expression node to be transformed and replaced.
5963        args: positional names that will substitute unnamed placeholders in the given order.
5964        kwargs: keyword arguments that will substitute named placeholders.
5965
5966    Examples:
5967        >>> from sqlglot import exp, parse_one
5968        >>> replace_placeholders(
5969        ...     parse_one("select * from :tbl where ? = ?"),
5970        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5971        ... ).sql()
5972        "SELECT * FROM foo WHERE str_col = 'b'"
5973
5974    Returns:
5975        The mapped expression.
5976    """
5977
5978    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5979        if isinstance(node, Placeholder):
5980            if node.name:
5981                new_name = kwargs.get(node.name)
5982                if new_name:
5983                    return convert(new_name)
5984            else:
5985                try:
5986                    return convert(next(args))
5987                except StopIteration:
5988                    pass
5989        return node
5990
5991    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:
5994def expand(
5995    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5996) -> Expression:
5997    """Transforms an expression by expanding all referenced sources into subqueries.
5998
5999    Examples:
6000        >>> from sqlglot import parse_one
6001        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
6002        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
6003
6004        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
6005        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
6006
6007    Args:
6008        expression: The expression to expand.
6009        sources: A dictionary of name to Subqueryables.
6010        copy: Whether or not to copy the expression during transformation. Defaults to True.
6011
6012    Returns:
6013        The transformed expression.
6014    """
6015
6016    def _expand(node: Expression):
6017        if isinstance(node, Table):
6018            name = table_name(node)
6019            source = sources.get(name)
6020            if source:
6021                subquery = source.subquery(node.alias or name)
6022                subquery.comments = [f"source: {name}"]
6023                return subquery.transform(_expand, copy=False)
6024        return node
6025
6026    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:
6029def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
6030    """
6031    Returns a Func expression.
6032
6033    Examples:
6034        >>> func("abs", 5).sql()
6035        'ABS(5)'
6036
6037        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
6038        'CAST(5 AS DOUBLE)'
6039
6040    Args:
6041        name: the name of the function to build.
6042        args: the args used to instantiate the function of interest.
6043        dialect: the source dialect.
6044        kwargs: the kwargs used to instantiate the function of interest.
6045
6046    Note:
6047        The arguments `args` and `kwargs` are mutually exclusive.
6048
6049    Returns:
6050        An instance of the function of interest, or an anonymous function, if `name` doesn't
6051        correspond to an existing `sqlglot.expressions.Func` class.
6052    """
6053    if args and kwargs:
6054        raise ValueError("Can't use both args and kwargs to instantiate a function.")
6055
6056    from sqlglot.dialects.dialect import Dialect
6057
6058    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
6059    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
6060
6061    parser = Dialect.get_or_raise(dialect)().parser()
6062    from_args_list = parser.FUNCTIONS.get(name.upper())
6063
6064    if from_args_list:
6065        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
6066    else:
6067        kwargs = kwargs or {"expressions": converted}
6068        function = Anonymous(this=name, **kwargs)
6069
6070    for error_message in function.error_messages(converted):
6071        raise ValueError(error_message)
6072
6073    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:
6076def true() -> Boolean:
6077    """
6078    Returns a true Boolean expression.
6079    """
6080    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
6083def false() -> Boolean:
6084    """
6085    Returns a false Boolean expression.
6086    """
6087    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
6090def null() -> Null:
6091    """
6092    Returns a Null expression.
6093    """
6094    return Null()

Returns a Null expression.

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