Edit on GitHub

Expressions

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

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


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

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

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

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

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

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

output_name

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def copy(self):
245    def copy(self):
246        """
247        Returns a deep copy of the expression.
248        """
249        new = deepcopy(self)
250        new.parent = self.parent
251        for item, parent, _ in new.bfs():
252            if isinstance(item, Expression) and parent:
253                item.parent = parent
254        return new

Returns a deep copy of the expression.

def append(self, arg_key, value):
256    def append(self, arg_key, value):
257        """
258        Appends value to arg_key if it's a list or sets it as a new list.
259
260        Args:
261            arg_key (str): name of the list expression arg
262            value (Any): value to append to the list
263        """
264        if not isinstance(self.args.get(arg_key), list):
265            self.args[arg_key] = []
266        self.args[arg_key].append(value)
267        self._set_parent(arg_key, value)

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

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key, value):
269    def set(self, arg_key, value):
270        """
271        Sets `arg_key` to `value`.
272
273        Args:
274            arg_key (str): name of the expression arg.
275            value: value to set the arg to.
276        """
277        self.args[arg_key] = value
278        self._set_parent(arg_key, value)

Sets arg_key to value.

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

Returns the depth of this tree.

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
299    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
300        """
301        Returns the first node in this tree which matches at least one of
302        the specified types.
303
304        Args:
305            expression_types (type): the expression type(s) to match.
306
307        Returns:
308            The node which matches the criteria or None if no such node was found.
309        """
310        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 (type): the expression type(s) to match.
Returns:

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

def find_all(self, *expression_types: Type[~E], bfs=True) -> Iterator[~E]:
312    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
313        """
314        Returns a generator object which visits all nodes in this tree and only
315        yields those that match at least one of the specified expression types.
316
317        Args:
318            expression_types (type): the expression type(s) to match.
319
320        Returns:
321            The generator object.
322        """
323        for expression, _, _ in self.walk(bfs=bfs):
324            if isinstance(expression, expression_types):
325                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 (type): the expression type(s) to match.
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
327    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
328        """
329        Returns a nearest parent matching expression_types.
330
331        Args:
332            expression_types (type): the expression type(s) to match.
333
334        Returns:
335            The parent node.
336        """
337        ancestor = self.parent
338        while ancestor and not isinstance(ancestor, expression_types):
339            ancestor = ancestor.parent
340        # ignore type because mypy doesn't know that we're checking type in the loop
341        return ancestor  # type: ignore[return-value]

Returns a nearest parent matching expression_types.

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

The parent node.

parent_select

Returns the parent select statement.

def root(self) -> sqlglot.expressions.Expression:
350    def root(self) -> Expression:
351        """
352        Returns the root expression of this tree.
353        """
354        expression = self
355        while expression.parent:
356            expression = expression.parent
357        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
359    def walk(self, bfs=True, prune=None):
360        """
361        Returns a generator object which visits all nodes in this tree.
362
363        Args:
364            bfs (bool): if set to True the BFS traversal order will be applied,
365                otherwise the DFS traversal will be used instead.
366            prune ((node, parent, arg_key) -> bool): callable that returns True if
367                the generator should stop traversing this branch of the tree.
368
369        Returns:
370            the generator object.
371        """
372        if bfs:
373            yield from self.bfs(prune=prune)
374        else:
375            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):
377    def dfs(self, parent=None, key=None, prune=None):
378        """
379        Returns a generator object which visits all nodes in this tree in
380        the DFS (Depth-first) order.
381
382        Returns:
383            The generator object.
384        """
385        parent = parent or self.parent
386        yield self, parent, key
387        if prune and prune(self, parent, key):
388            return
389
390        for k, v in self.args.items():
391            for node in ensure_collection(v):
392                if isinstance(node, Expression):
393                    yield from node.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):
395    def bfs(self, prune=None):
396        """
397        Returns a generator object which visits all nodes in this tree in
398        the BFS (Breadth-first) order.
399
400        Returns:
401            The generator object.
402        """
403        queue = deque([(self, self.parent, None)])
404
405        while queue:
406            item, parent, key = queue.popleft()
407
408            yield item, parent, key
409            if prune and prune(item, parent, key):
410                continue
411
412            if isinstance(item, Expression):
413                for k, v in item.args.items():
414                    for node in ensure_collection(v):
415                        if isinstance(node, Expression):
416                            queue.append((node, 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):
418    def unnest(self):
419        """
420        Returns the first non parenthesis child or self.
421        """
422        expression = self
423        while isinstance(expression, Paren):
424            expression = expression.this
425        return expression

Returns the first non parenthesis child or self.

def unalias(self):
427    def unalias(self):
428        """
429        Returns the inner expression if this is an Alias.
430        """
431        if isinstance(self, Alias):
432            return self.this
433        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
435    def unnest_operands(self):
436        """
437        Returns unnested operands as a tuple.
438        """
439        return tuple(arg.unnest() for arg in self.args.values() if arg)

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
441    def flatten(self, unnest=True):
442        """
443        Returns a generator which yields child nodes who's parents are the same class.
444
445        A AND B AND C -> [A, B, C]
446        """
447        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not isinstance(n, self.__class__)):
448            if not isinstance(node, self.__class__):
449                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:
457    def sql(self, dialect: DialectType = None, **opts) -> str:
458        """
459        Returns SQL string representation of this tree.
460
461        Args:
462            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
463            opts: other `sqlglot.generator.Generator` options.
464
465        Returns:
466            The SQL string.
467        """
468        from sqlglot.dialects import Dialect
469
470        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):
496    def transform(self, fun, *args, copy=True, **kwargs):
497        """
498        Recursively visits all tree nodes (excluding already transformed ones)
499        and applies the given transformation function to each node.
500
501        Args:
502            fun (function): a function which takes a node as an argument and returns a
503                new transformed node or the same node without modifications. If the function
504                returns None, then the corresponding node will be removed from the syntax tree.
505            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
506                modified in place.
507
508        Returns:
509            The transformed tree.
510        """
511        node = self.copy() if copy else self
512        new_node = fun(node, *args, **kwargs)
513
514        if new_node is None or not isinstance(new_node, Expression):
515            return new_node
516        if new_node is not node:
517            new_node.parent = node.parent
518            return new_node
519
520        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
521        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):
523    def replace(self, expression):
524        """
525        Swap out this expression with a new expression.
526
527        For example::
528
529            >>> tree = Select().select("x").from_("tbl")
530            >>> tree.find(Column).replace(Column(this="y"))
531            (COLUMN this: y)
532            >>> tree.sql()
533            'SELECT y FROM tbl'
534
535        Args:
536            expression (Expression|None): new node
537
538        Returns:
539            The new expression or expressions.
540        """
541        if not self.parent:
542            return expression
543
544        parent = self.parent
545        self.parent = None
546
547        replace_children(parent, lambda child: expression if child is self else child)
548        return expression

Swap out this expression with a new expression.

For example::

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

The new expression or expressions.

def pop(self):
550    def pop(self):
551        """
552        Remove this expression from its AST.
553
554        Returns:
555            The popped expression.
556        """
557        self.replace(None)
558        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_):
560    def assert_is(self, type_):
561        """
562        Assert that this `Expression` is an instance of `type_`.
563
564        If it is NOT an instance of `type_`, this raises an assertion error.
565        Otherwise, this returns this expression.
566
567        Examples:
568            This is useful for type security in chained expressions:
569
570            >>> import sqlglot
571            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
572            'SELECT x, z FROM y'
573        """
574        assert isinstance(self, type_)
575        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]:
577    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
578        """
579        Checks if this expression is valid (e.g. all mandatory args are set).
580
581        Args:
582            args: a sequence of values that were used to instantiate a Func expression. This is used
583                to check that the provided arguments don't exceed the function argument limit.
584
585        Returns:
586            A list of error messages for all possible errors that were found.
587        """
588        errors: t.List[str] = []
589
590        for k in self.args:
591            if k not in self.arg_types:
592                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
593        for k, mandatory in self.arg_types.items():
594            v = self.args.get(k)
595            if mandatory and (v is None or (isinstance(v, list) and not v)):
596                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
597
598        if (
599            args
600            and isinstance(self, Func)
601            and len(args) > len(self.arg_types)
602            and not self.is_var_len_args
603        ):
604            errors.append(
605                f"The number of provided arguments ({len(args)}) is greater than "
606                f"the maximum number of supported arguments ({len(self.arg_types)})"
607            )
608
609        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):
611    def dump(self):
612        """
613        Dump this Expression to a JSON-serializable dict.
614        """
615        from sqlglot.serde import dump
616
617        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
619    @classmethod
620    def load(cls, obj):
621        """
622        Load a dict (as returned by `Expression.dump`) into an Expression instance.
623        """
624        from sqlglot.serde import load
625
626        return load(obj)

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

class Condition(Expression):
637class Condition(Expression):
638    def and_(self, *expressions, dialect=None, **opts):
639        """
640        AND this condition with one or multiple expressions.
641
642        Example:
643            >>> condition("x=1").and_("y=1").sql()
644            'x = 1 AND y = 1'
645
646        Args:
647            *expressions (str | Expression): the SQL code strings to parse.
648                If an `Expression` instance is passed, it will be used as-is.
649            dialect (str): the dialect used to parse the input expression.
650            opts (kwargs): other options to use to parse the input expressions.
651
652        Returns:
653            And: the new condition.
654        """
655        return and_(self, *expressions, dialect=dialect, **opts)
656
657    def or_(self, *expressions, dialect=None, **opts):
658        """
659        OR this condition with one or multiple expressions.
660
661        Example:
662            >>> condition("x=1").or_("y=1").sql()
663            'x = 1 OR y = 1'
664
665        Args:
666            *expressions (str | Expression): the SQL code strings to parse.
667                If an `Expression` instance is passed, it will be used as-is.
668            dialect (str): the dialect used to parse the input expression.
669            opts (kwargs): other options to use to parse the input expressions.
670
671        Returns:
672            Or: the new condition.
673        """
674        return or_(self, *expressions, dialect=dialect, **opts)
675
676    def not_(self):
677        """
678        Wrap this condition with NOT.
679
680        Example:
681            >>> condition("x=1").not_().sql()
682            'NOT x = 1'
683
684        Returns:
685            Not: the new condition.
686        """
687        return not_(self)
def and_(self, *expressions, dialect=None, **opts):
638    def and_(self, *expressions, dialect=None, **opts):
639        """
640        AND this condition with one or multiple expressions.
641
642        Example:
643            >>> condition("x=1").and_("y=1").sql()
644            'x = 1 AND y = 1'
645
646        Args:
647            *expressions (str | Expression): the SQL code strings to parse.
648                If an `Expression` instance is passed, it will be used as-is.
649            dialect (str): the dialect used to parse the input expression.
650            opts (kwargs): other options to use to parse the input expressions.
651
652        Returns:
653            And: the new condition.
654        """
655        return and_(self, *expressions, dialect=dialect, **opts)

AND this condition with one or multiple expressions.

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

And: the new condition.

def or_(self, *expressions, dialect=None, **opts):
657    def or_(self, *expressions, dialect=None, **opts):
658        """
659        OR this condition with one or multiple expressions.
660
661        Example:
662            >>> condition("x=1").or_("y=1").sql()
663            'x = 1 OR y = 1'
664
665        Args:
666            *expressions (str | Expression): the SQL code strings to parse.
667                If an `Expression` instance is passed, it will be used as-is.
668            dialect (str): the dialect used to parse the input expression.
669            opts (kwargs): other options to use to parse the input expressions.
670
671        Returns:
672            Or: the new condition.
673        """
674        return or_(self, *expressions, dialect=dialect, **opts)

OR this condition with one or multiple expressions.

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

Or: the new condition.

def not_(self):
676    def not_(self):
677        """
678        Wrap this condition with NOT.
679
680        Example:
681            >>> condition("x=1").not_().sql()
682            'NOT x = 1'
683
684        Returns:
685            Not: the new condition.
686        """
687        return not_(self)

Wrap this condition with NOT.

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

Not: the new condition.

class Predicate(Condition):
690class Predicate(Condition):
691    """Relationships like x = y, x > 1, x >= y."""

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

class DerivedTable(Expression):
694class DerivedTable(Expression):
695    @property
696    def alias_column_names(self):
697        table_alias = self.args.get("alias")
698        if not table_alias:
699            return []
700        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
701        return [c.name for c in column_list]
702
703    @property
704    def selects(self):
705        alias = self.args.get("alias")
706
707        if alias:
708            return alias.columns
709        return []
710
711    @property
712    def named_selects(self):
713        return [select.output_name for select in self.selects]
class Unionable(Expression):
716class Unionable(Expression):
717    def union(self, expression, distinct=True, dialect=None, **opts):
718        """
719        Builds a UNION expression.
720
721        Example:
722            >>> import sqlglot
723            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
724            'SELECT * FROM foo UNION SELECT * FROM bla'
725
726        Args:
727            expression (str | Expression): the SQL code string.
728                If an `Expression` instance is passed, it will be used as-is.
729            distinct (bool): set the DISTINCT flag if and only if this is true.
730            dialect (str): the dialect used to parse the input expression.
731            opts (kwargs): other options to use to parse the input expressions.
732        Returns:
733            Union: the Union expression.
734        """
735        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
736
737    def intersect(self, expression, distinct=True, dialect=None, **opts):
738        """
739        Builds an INTERSECT expression.
740
741        Example:
742            >>> import sqlglot
743            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
744            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
745
746        Args:
747            expression (str | Expression): the SQL code string.
748                If an `Expression` instance is passed, it will be used as-is.
749            distinct (bool): set the DISTINCT flag if and only if this is true.
750            dialect (str): the dialect used to parse the input expression.
751            opts (kwargs): other options to use to parse the input expressions.
752        Returns:
753            Intersect: the Intersect expression
754        """
755        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
756
757    def except_(self, expression, distinct=True, dialect=None, **opts):
758        """
759        Builds an EXCEPT expression.
760
761        Example:
762            >>> import sqlglot
763            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
764            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
765
766        Args:
767            expression (str | Expression): the SQL code string.
768                If an `Expression` instance is passed, it will be used as-is.
769            distinct (bool): set the DISTINCT flag if and only if this is true.
770            dialect (str): the dialect used to parse the input expression.
771            opts (kwargs): other options to use to parse the input expressions.
772        Returns:
773            Except: the Except expression
774        """
775        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
717    def union(self, expression, distinct=True, dialect=None, **opts):
718        """
719        Builds a UNION expression.
720
721        Example:
722            >>> import sqlglot
723            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
724            'SELECT * FROM foo UNION SELECT * FROM bla'
725
726        Args:
727            expression (str | Expression): the SQL code string.
728                If an `Expression` instance is passed, it will be used as-is.
729            distinct (bool): set the DISTINCT flag if and only if this is true.
730            dialect (str): the dialect used to parse the input expression.
731            opts (kwargs): other options to use to parse the input expressions.
732        Returns:
733            Union: the Union expression.
734        """
735        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

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

Union: the Union expression.

def intersect(self, expression, distinct=True, dialect=None, **opts):
737    def intersect(self, expression, distinct=True, dialect=None, **opts):
738        """
739        Builds an INTERSECT expression.
740
741        Example:
742            >>> import sqlglot
743            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
744            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
745
746        Args:
747            expression (str | Expression): the SQL code string.
748                If an `Expression` instance is passed, it will be used as-is.
749            distinct (bool): set the DISTINCT flag if and only if this is true.
750            dialect (str): the dialect used to parse the input expression.
751            opts (kwargs): other options to use to parse the input expressions.
752        Returns:
753            Intersect: the Intersect expression
754        """
755        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

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

Intersect: the Intersect expression

def except_(self, expression, distinct=True, dialect=None, **opts):
757    def except_(self, expression, distinct=True, dialect=None, **opts):
758        """
759        Builds an EXCEPT expression.
760
761        Example:
762            >>> import sqlglot
763            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
764            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
765
766        Args:
767            expression (str | Expression): the SQL code string.
768                If an `Expression` instance is passed, it will be used as-is.
769            distinct (bool): set the DISTINCT flag if and only if this is true.
770            dialect (str): the dialect used to parse the input expression.
771            opts (kwargs): other options to use to parse the input expressions.
772        Returns:
773            Except: the Except expression
774        """
775        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

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

Except: the Except expression

class UDTF(DerivedTable, Unionable):
778class UDTF(DerivedTable, Unionable):
779    pass
class Cache(Expression):
782class Cache(Expression):
783    arg_types = {
784        "with": False,
785        "this": True,
786        "lazy": False,
787        "options": False,
788        "expression": False,
789    }
class Uncache(Expression):
792class Uncache(Expression):
793    arg_types = {"this": True, "exists": False}
class Create(Expression):
796class Create(Expression):
797    arg_types = {
798        "with": False,
799        "this": True,
800        "kind": True,
801        "expression": False,
802        "exists": False,
803        "properties": False,
804        "replace": False,
805        "unique": False,
806        "volatile": False,
807        "indexes": False,
808        "no_schema_binding": False,
809        "begin": False,
810    }
class Describe(Expression):
813class Describe(Expression):
814    arg_types = {"this": True, "kind": False}
class Set(Expression):
817class Set(Expression):
818    arg_types = {"expressions": False}
class SetItem(Expression):
821class SetItem(Expression):
822    arg_types = {
823        "this": False,
824        "expressions": False,
825        "kind": False,
826        "collate": False,  # MySQL SET NAMES statement
827        "global": False,
828    }
class Show(Expression):
831class Show(Expression):
832    arg_types = {
833        "this": True,
834        "target": False,
835        "offset": False,
836        "limit": False,
837        "like": False,
838        "where": False,
839        "db": False,
840        "full": False,
841        "mutex": False,
842        "query": False,
843        "channel": False,
844        "global": False,
845        "log": False,
846        "position": False,
847        "types": False,
848    }
class UserDefinedFunction(Expression):
851class UserDefinedFunction(Expression):
852    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
855class CharacterSet(Expression):
856    arg_types = {"this": True, "default": False}
class With(Expression):
859class With(Expression):
860    arg_types = {"expressions": True, "recursive": False}
861
862    @property
863    def recursive(self) -> bool:
864        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
867class WithinGroup(Expression):
868    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
871class CTE(DerivedTable):
872    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
875class TableAlias(Expression):
876    arg_types = {"this": False, "columns": False}
877
878    @property
879    def columns(self):
880        return self.args.get("columns") or []
class BitString(Condition):
883class BitString(Condition):
884    pass
class HexString(Condition):
887class HexString(Condition):
888    pass
class ByteString(Condition):
891class ByteString(Condition):
892    pass
class Column(Condition):
895class Column(Condition):
896    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
897
898    @property
899    def table(self) -> str:
900        return self.text("table")
901
902    @property
903    def db(self) -> str:
904        return self.text("db")
905
906    @property
907    def catalog(self) -> str:
908        return self.text("catalog")
909
910    @property
911    def output_name(self) -> str:
912        return self.name
output_name: str

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class ColumnDef(Expression):
915class ColumnDef(Expression):
916    arg_types = {
917        "this": True,
918        "kind": False,
919        "constraints": False,
920        "exists": False,
921    }
class AlterColumn(Expression):
924class AlterColumn(Expression):
925    arg_types = {
926        "this": True,
927        "dtype": False,
928        "collate": False,
929        "using": False,
930        "default": False,
931        "drop": False,
932    }
class RenameTable(Expression):
935class RenameTable(Expression):
936    pass
class SetTag(Expression):
939class SetTag(Expression):
940    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
943class Comment(Expression):
944    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class ColumnConstraint(Expression):
947class ColumnConstraint(Expression):
948    arg_types = {"this": False, "kind": True}
class ColumnConstraintKind(Expression):
951class ColumnConstraintKind(Expression):
952    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
955class AutoIncrementColumnConstraint(ColumnConstraintKind):
956    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
959class CaseSpecificColumnConstraint(ColumnConstraintKind):
960    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
963class CharacterSetColumnConstraint(ColumnConstraintKind):
964    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
967class CheckColumnConstraint(ColumnConstraintKind):
968    pass
class CollateColumnConstraint(ColumnConstraintKind):
971class CollateColumnConstraint(ColumnConstraintKind):
972    pass
class CommentColumnConstraint(ColumnConstraintKind):
975class CommentColumnConstraint(ColumnConstraintKind):
976    pass
class CompressColumnConstraint(ColumnConstraintKind):
979class CompressColumnConstraint(ColumnConstraintKind):
980    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
983class DateFormatColumnConstraint(ColumnConstraintKind):
984    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
987class DefaultColumnConstraint(ColumnConstraintKind):
988    pass
class EncodeColumnConstraint(ColumnConstraintKind):
991class EncodeColumnConstraint(ColumnConstraintKind):
992    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
 995class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
 996    # this: True -> ALWAYS, this: False -> BY DEFAULT
 997    arg_types = {
 998        "this": False,
 999        "start": False,
1000        "increment": False,
1001        "minvalue": False,
1002        "maxvalue": False,
1003        "cycle": False,
1004    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1007class InlineLengthColumnConstraint(ColumnConstraintKind):
1008    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1011class NotNullColumnConstraint(ColumnConstraintKind):
1012    arg_types = {"allow_null": False}
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1015class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1016    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1019class TitleColumnConstraint(ColumnConstraintKind):
1020    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1023class UniqueColumnConstraint(ColumnConstraintKind):
1024    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1027class UppercaseColumnConstraint(ColumnConstraintKind):
1028    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1031class PathColumnConstraint(ColumnConstraintKind):
1032    pass
class Constraint(Expression):
1035class Constraint(Expression):
1036    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1039class Delete(Expression):
1040    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1041
1042    def delete(
1043        self,
1044        table: ExpOrStr,
1045        dialect: DialectType = None,
1046        copy: bool = True,
1047        **opts,
1048    ) -> Delete:
1049        """
1050        Create a DELETE expression or replace the table on an existing DELETE expression.
1051
1052        Example:
1053            >>> delete("tbl").sql()
1054            'DELETE FROM tbl'
1055
1056        Args:
1057            table: the table from which to delete.
1058            dialect: the dialect used to parse the input expression.
1059            copy: if `False`, modify this expression instance in-place.
1060            opts: other options to use to parse the input expressions.
1061
1062        Returns:
1063            Delete: the modified expression.
1064        """
1065        return _apply_builder(
1066            expression=table,
1067            instance=self,
1068            arg="this",
1069            dialect=dialect,
1070            into=Table,
1071            copy=copy,
1072            **opts,
1073        )
1074
1075    def where(
1076        self,
1077        *expressions: ExpOrStr,
1078        append: bool = True,
1079        dialect: DialectType = None,
1080        copy: bool = True,
1081        **opts,
1082    ) -> Delete:
1083        """
1084        Append to or set the WHERE expressions.
1085
1086        Example:
1087            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1088            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1089
1090        Args:
1091            *expressions: the SQL code strings to parse.
1092                If an `Expression` instance is passed, it will be used as-is.
1093                Multiple expressions are combined with an AND operator.
1094            append: if `True`, AND the new expressions to any existing expression.
1095                Otherwise, this resets the expression.
1096            dialect: the dialect used to parse the input expressions.
1097            copy: if `False`, modify this expression instance in-place.
1098            opts: other options to use to parse the input expressions.
1099
1100        Returns:
1101            Delete: the modified expression.
1102        """
1103        return _apply_conjunction_builder(
1104            *expressions,
1105            instance=self,
1106            arg="where",
1107            append=append,
1108            into=Where,
1109            dialect=dialect,
1110            copy=copy,
1111            **opts,
1112        )
1113
1114    def returning(
1115        self,
1116        expression: ExpOrStr,
1117        dialect: DialectType = None,
1118        copy: bool = True,
1119        **opts,
1120    ) -> Delete:
1121        """
1122        Set the RETURNING expression. Not supported by all dialects.
1123
1124        Example:
1125            >>> delete("tbl").returning("*", dialect="postgres").sql()
1126            'DELETE FROM tbl RETURNING *'
1127
1128        Args:
1129            expression: the SQL code strings to parse.
1130                If an `Expression` instance is passed, it will be used as-is.
1131            dialect: the dialect used to parse the input expressions.
1132            copy: if `False`, modify this expression instance in-place.
1133            opts: other options to use to parse the input expressions.
1134
1135        Returns:
1136            Delete: the modified expression.
1137        """
1138        return _apply_builder(
1139            expression=expression,
1140            instance=self,
1141            arg="returning",
1142            prefix="RETURNING",
1143            dialect=dialect,
1144            copy=copy,
1145            into=Returning,
1146            **opts,
1147        )
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:
1042    def delete(
1043        self,
1044        table: ExpOrStr,
1045        dialect: DialectType = None,
1046        copy: bool = True,
1047        **opts,
1048    ) -> Delete:
1049        """
1050        Create a DELETE expression or replace the table on an existing DELETE expression.
1051
1052        Example:
1053            >>> delete("tbl").sql()
1054            'DELETE FROM tbl'
1055
1056        Args:
1057            table: the table from which to delete.
1058            dialect: the dialect used to parse the input expression.
1059            copy: if `False`, modify this expression instance in-place.
1060            opts: other options to use to parse the input expressions.
1061
1062        Returns:
1063            Delete: the modified expression.
1064        """
1065        return _apply_builder(
1066            expression=table,
1067            instance=self,
1068            arg="this",
1069            dialect=dialect,
1070            into=Table,
1071            copy=copy,
1072            **opts,
1073        )

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

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

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1075    def where(
1076        self,
1077        *expressions: ExpOrStr,
1078        append: bool = True,
1079        dialect: DialectType = None,
1080        copy: bool = True,
1081        **opts,
1082    ) -> Delete:
1083        """
1084        Append to or set the WHERE expressions.
1085
1086        Example:
1087            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1088            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1089
1090        Args:
1091            *expressions: the SQL code strings to parse.
1092                If an `Expression` instance is passed, it will be used as-is.
1093                Multiple expressions are combined with an AND operator.
1094            append: if `True`, AND the new expressions to any existing expression.
1095                Otherwise, this resets the expression.
1096            dialect: the dialect used to parse the input expressions.
1097            copy: if `False`, modify this expression instance in-place.
1098            opts: other options to use to parse the input expressions.
1099
1100        Returns:
1101            Delete: the modified expression.
1102        """
1103        return _apply_conjunction_builder(
1104            *expressions,
1105            instance=self,
1106            arg="where",
1107            append=append,
1108            into=Where,
1109            dialect=dialect,
1110            copy=copy,
1111            **opts,
1112        )

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:
1114    def returning(
1115        self,
1116        expression: ExpOrStr,
1117        dialect: DialectType = None,
1118        copy: bool = True,
1119        **opts,
1120    ) -> Delete:
1121        """
1122        Set the RETURNING expression. Not supported by all dialects.
1123
1124        Example:
1125            >>> delete("tbl").returning("*", dialect="postgres").sql()
1126            'DELETE FROM tbl RETURNING *'
1127
1128        Args:
1129            expression: the SQL code strings to parse.
1130                If an `Expression` instance is passed, it will be used as-is.
1131            dialect: the dialect used to parse the input expressions.
1132            copy: if `False`, modify this expression instance in-place.
1133            opts: other options to use to parse the input expressions.
1134
1135        Returns:
1136            Delete: the modified expression.
1137        """
1138        return _apply_builder(
1139            expression=expression,
1140            instance=self,
1141            arg="returning",
1142            prefix="RETURNING",
1143            dialect=dialect,
1144            copy=copy,
1145            into=Returning,
1146            **opts,
1147        )

Set the RETURNING expression. Not supported by all dialects.

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

Delete: the modified expression.

class Drop(Expression):
1150class Drop(Expression):
1151    arg_types = {
1152        "this": False,
1153        "kind": False,
1154        "exists": False,
1155        "temporary": False,
1156        "materialized": False,
1157        "cascade": False,
1158    }
class Filter(Expression):
1161class Filter(Expression):
1162    arg_types = {"this": True, "expression": True}
class Check(Expression):
1165class Check(Expression):
1166    pass
class Directory(Expression):
1169class Directory(Expression):
1170    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1171    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1174class ForeignKey(Expression):
1175    arg_types = {
1176        "expressions": True,
1177        "reference": False,
1178        "delete": False,
1179        "update": False,
1180    }
class PrimaryKey(Expression):
1183class PrimaryKey(Expression):
1184    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1187class Unique(Expression):
1188    arg_types = {"expressions": True}
class Into(Expression):
1193class Into(Expression):
1194    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1197class From(Expression):
1198    arg_types = {"expressions": True}
class Having(Expression):
1201class Having(Expression):
1202    pass
class Hint(Expression):
1205class Hint(Expression):
1206    arg_types = {"expressions": True}
class JoinHint(Expression):
1209class JoinHint(Expression):
1210    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1213class Identifier(Expression):
1214    arg_types = {"this": True, "quoted": False}
1215
1216    @property
1217    def quoted(self):
1218        return bool(self.args.get("quoted"))
1219
1220    def __eq__(self, other):
1221        return isinstance(other, self.__class__) and _norm_arg(self.this) == _norm_arg(other.this)
1222
1223    def __hash__(self):
1224        return hash((self.key, self.this.lower()))
1225
1226    @property
1227    def output_name(self):
1228        return self.name
output_name

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Index(Expression):
1231class Index(Expression):
1232    arg_types = {
1233        "this": False,
1234        "table": False,
1235        "where": False,
1236        "columns": False,
1237        "unique": False,
1238        "primary": False,
1239        "amp": False,  # teradata
1240    }
class Insert(Expression):
1243class Insert(Expression):
1244    arg_types = {
1245        "with": False,
1246        "this": True,
1247        "expression": False,
1248        "returning": False,
1249        "overwrite": False,
1250        "exists": False,
1251        "partition": False,
1252        "alternative": False,
1253    }
class Returning(Expression):
1256class Returning(Expression):
1257    arg_types = {"expressions": True}
class Introducer(Expression):
1261class Introducer(Expression):
1262    arg_types = {"this": True, "expression": True}
class National(Expression):
1266class National(Expression):
1267    pass
class LoadData(Expression):
1270class LoadData(Expression):
1271    arg_types = {
1272        "this": True,
1273        "local": False,
1274        "overwrite": False,
1275        "inpath": True,
1276        "partition": False,
1277        "input_format": False,
1278        "serde": False,
1279    }
class Partition(Expression):
1282class Partition(Expression):
1283    arg_types = {"expressions": True}
class Fetch(Expression):
1286class Fetch(Expression):
1287    arg_types = {"direction": False, "count": False}
class Group(Expression):
1290class Group(Expression):
1291    arg_types = {
1292        "expressions": False,
1293        "grouping_sets": False,
1294        "cube": False,
1295        "rollup": False,
1296    }
class Lambda(Expression):
1299class Lambda(Expression):
1300    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1303class Limit(Expression):
1304    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1307class Literal(Condition):
1308    arg_types = {"this": True, "is_string": True}
1309
1310    def __eq__(self, other):
1311        return (
1312            isinstance(other, Literal)
1313            and self.this == other.this
1314            and self.args["is_string"] == other.args["is_string"]
1315        )
1316
1317    def __hash__(self):
1318        return hash((self.key, self.this, self.args["is_string"]))
1319
1320    @classmethod
1321    def number(cls, number) -> Literal:
1322        return cls(this=str(number), is_string=False)
1323
1324    @classmethod
1325    def string(cls, string) -> Literal:
1326        return cls(this=str(string), is_string=True)
1327
1328    @property
1329    def output_name(self):
1330        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1320    @classmethod
1321    def number(cls, number) -> Literal:
1322        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1324    @classmethod
1325    def string(cls, string) -> Literal:
1326        return cls(this=str(string), is_string=True)
output_name

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Join(Expression):
1333class Join(Expression):
1334    arg_types = {
1335        "this": True,
1336        "on": False,
1337        "side": False,
1338        "kind": False,
1339        "using": False,
1340        "natural": False,
1341    }
1342
1343    @property
1344    def kind(self):
1345        return self.text("kind").upper()
1346
1347    @property
1348    def side(self):
1349        return self.text("side").upper()
1350
1351    @property
1352    def alias_or_name(self):
1353        return self.this.alias_or_name
1354
1355    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1356        """
1357        Append to or set the ON expressions.
1358
1359        Example:
1360            >>> import sqlglot
1361            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1362            'JOIN x ON y = 1'
1363
1364        Args:
1365            *expressions (str | Expression): the SQL code strings to parse.
1366                If an `Expression` instance is passed, it will be used as-is.
1367                Multiple expressions are combined with an AND operator.
1368            append (bool): if `True`, AND the new expressions to any existing expression.
1369                Otherwise, this resets the expression.
1370            dialect (str): the dialect used to parse the input expressions.
1371            copy (bool): if `False`, modify this expression instance in-place.
1372            opts (kwargs): other options to use to parse the input expressions.
1373
1374        Returns:
1375            Join: the modified join expression.
1376        """
1377        join = _apply_conjunction_builder(
1378            *expressions,
1379            instance=self,
1380            arg="on",
1381            append=append,
1382            dialect=dialect,
1383            copy=copy,
1384            **opts,
1385        )
1386
1387        if join.kind == "CROSS":
1388            join.set("kind", None)
1389
1390        return join
1391
1392    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1393        """
1394        Append to or set the USING expressions.
1395
1396        Example:
1397            >>> import sqlglot
1398            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1399            'JOIN x USING (foo, bla)'
1400
1401        Args:
1402            *expressions (str | Expression): the SQL code strings to parse.
1403                If an `Expression` instance is passed, it will be used as-is.
1404            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1405                Otherwise, this resets the expression.
1406            dialect (str): the dialect used to parse the input expressions.
1407            copy (bool): if `False`, modify this expression instance in-place.
1408            opts (kwargs): other options to use to parse the input expressions.
1409
1410        Returns:
1411            Join: the modified join expression.
1412        """
1413        join = _apply_list_builder(
1414            *expressions,
1415            instance=self,
1416            arg="using",
1417            append=append,
1418            dialect=dialect,
1419            copy=copy,
1420            **opts,
1421        )
1422
1423        if join.kind == "CROSS":
1424            join.set("kind", None)
1425
1426        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1355    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1356        """
1357        Append to or set the ON expressions.
1358
1359        Example:
1360            >>> import sqlglot
1361            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1362            'JOIN x ON y = 1'
1363
1364        Args:
1365            *expressions (str | Expression): the SQL code strings to parse.
1366                If an `Expression` instance is passed, it will be used as-is.
1367                Multiple expressions are combined with an AND operator.
1368            append (bool): if `True`, AND the new expressions to any existing expression.
1369                Otherwise, this resets the expression.
1370            dialect (str): the dialect used to parse the input expressions.
1371            copy (bool): if `False`, modify this expression instance in-place.
1372            opts (kwargs): other options to use to parse the input expressions.
1373
1374        Returns:
1375            Join: the modified join expression.
1376        """
1377        join = _apply_conjunction_builder(
1378            *expressions,
1379            instance=self,
1380            arg="on",
1381            append=append,
1382            dialect=dialect,
1383            copy=copy,
1384            **opts,
1385        )
1386
1387        if join.kind == "CROSS":
1388            join.set("kind", None)
1389
1390        return join

Append to or set the ON expressions.

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

Join: the modified join expression.

def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1392    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1393        """
1394        Append to or set the USING expressions.
1395
1396        Example:
1397            >>> import sqlglot
1398            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1399            'JOIN x USING (foo, bla)'
1400
1401        Args:
1402            *expressions (str | Expression): the SQL code strings to parse.
1403                If an `Expression` instance is passed, it will be used as-is.
1404            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1405                Otherwise, this resets the expression.
1406            dialect (str): the dialect used to parse the input expressions.
1407            copy (bool): if `False`, modify this expression instance in-place.
1408            opts (kwargs): other options to use to parse the input expressions.
1409
1410        Returns:
1411            Join: the modified join expression.
1412        """
1413        join = _apply_list_builder(
1414            *expressions,
1415            instance=self,
1416            arg="using",
1417            append=append,
1418            dialect=dialect,
1419            copy=copy,
1420            **opts,
1421        )
1422
1423        if join.kind == "CROSS":
1424            join.set("kind", None)
1425
1426        return join

Append to or set the USING expressions.

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

Join: the modified join expression.

class Lateral(UDTF):
1429class Lateral(UDTF):
1430    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1433class MatchRecognize(Expression):
1434    arg_types = {
1435        "partition_by": False,
1436        "order": False,
1437        "measures": False,
1438        "rows": False,
1439        "after": False,
1440        "pattern": False,
1441        "define": False,
1442    }
class Final(Expression):
1447class Final(Expression):
1448    pass
class Offset(Expression):
1451class Offset(Expression):
1452    arg_types = {"this": False, "expression": True}
class Order(Expression):
1455class Order(Expression):
1456    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1461class Cluster(Order):
1462    pass
class Distribute(Order):
1465class Distribute(Order):
1466    pass
class Sort(Order):
1469class Sort(Order):
1470    pass
class Ordered(Expression):
1473class Ordered(Expression):
1474    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1477class Property(Expression):
1478    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1481class AfterJournalProperty(Property):
1482    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1485class AlgorithmProperty(Property):
1486    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1489class AutoIncrementProperty(Property):
1490    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1493class BlockCompressionProperty(Property):
1494    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1497class CharacterSetProperty(Property):
1498    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1501class ChecksumProperty(Property):
1502    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1505class CollateProperty(Property):
1506    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1509class DataBlocksizeProperty(Property):
1510    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1513class DefinerProperty(Property):
1514    arg_types = {"this": True}
class DistKeyProperty(Property):
1517class DistKeyProperty(Property):
1518    arg_types = {"this": True}
class DistStyleProperty(Property):
1521class DistStyleProperty(Property):
1522    arg_types = {"this": True}
class EngineProperty(Property):
1525class EngineProperty(Property):
1526    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1529class ExecuteAsProperty(Property):
1530    arg_types = {"this": True}
class ExternalProperty(Property):
1533class ExternalProperty(Property):
1534    arg_types = {"this": False}
class FallbackProperty(Property):
1537class FallbackProperty(Property):
1538    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1541class FileFormatProperty(Property):
1542    arg_types = {"this": True}
class FreespaceProperty(Property):
1545class FreespaceProperty(Property):
1546    arg_types = {"this": True, "percent": False}
class IsolatedLoadingProperty(Property):
1549class IsolatedLoadingProperty(Property):
1550    arg_types = {
1551        "no": True,
1552        "concurrent": True,
1553        "for_all": True,
1554        "for_insert": True,
1555        "for_none": True,
1556    }
class JournalProperty(Property):
1559class JournalProperty(Property):
1560    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1563class LanguageProperty(Property):
1564    arg_types = {"this": True}
class LikeProperty(Property):
1567class LikeProperty(Property):
1568    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1571class LocationProperty(Property):
1572    arg_types = {"this": True}
class LockingProperty(Property):
1575class LockingProperty(Property):
1576    arg_types = {
1577        "this": False,
1578        "kind": True,
1579        "for_or_in": True,
1580        "lock_type": True,
1581        "override": False,
1582    }
class LogProperty(Property):
1585class LogProperty(Property):
1586    arg_types = {"no": True}
class MaterializedProperty(Property):
1589class MaterializedProperty(Property):
1590    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1593class MergeBlockRatioProperty(Property):
1594    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1597class NoPrimaryIndexProperty(Property):
1598    arg_types = {"this": False}
class OnCommitProperty(Property):
1601class OnCommitProperty(Property):
1602    arg_type = {"this": False}
class PartitionedByProperty(Property):
1605class PartitionedByProperty(Property):
1606    arg_types = {"this": True}
class ReturnsProperty(Property):
1609class ReturnsProperty(Property):
1610    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatDelimitedProperty(Property):
1613class RowFormatDelimitedProperty(Property):
1614    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1615    arg_types = {
1616        "fields": False,
1617        "escaped": False,
1618        "collection_items": False,
1619        "map_keys": False,
1620        "lines": False,
1621        "null": False,
1622        "serde": False,
1623    }
class RowFormatSerdeProperty(Property):
1626class RowFormatSerdeProperty(Property):
1627    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1630class SchemaCommentProperty(Property):
1631    arg_types = {"this": True}
class SerdeProperties(Property):
1634class SerdeProperties(Property):
1635    arg_types = {"expressions": True}
class SetProperty(Property):
1638class SetProperty(Property):
1639    arg_types = {"multi": True}
class SortKeyProperty(Property):
1642class SortKeyProperty(Property):
1643    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1646class SqlSecurityProperty(Property):
1647    arg_types = {"definer": True}
class TableFormatProperty(Property):
1650class TableFormatProperty(Property):
1651    arg_types = {"this": True}
class TemporaryProperty(Property):
1654class TemporaryProperty(Property):
1655    arg_types = {"global_": True}
class TransientProperty(Property):
1658class TransientProperty(Property):
1659    arg_types = {"this": False}
class VolatilityProperty(Property):
1662class VolatilityProperty(Property):
1663    arg_types = {"this": True}
class WithDataProperty(Property):
1666class WithDataProperty(Property):
1667    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1670class WithJournalTableProperty(Property):
1671    arg_types = {"this": True}
class Properties(Expression):
1674class Properties(Expression):
1675    arg_types = {"expressions": True}
1676
1677    NAME_TO_PROPERTY = {
1678        "ALGORITHM": AlgorithmProperty,
1679        "AUTO_INCREMENT": AutoIncrementProperty,
1680        "CHARACTER SET": CharacterSetProperty,
1681        "COLLATE": CollateProperty,
1682        "COMMENT": SchemaCommentProperty,
1683        "DEFINER": DefinerProperty,
1684        "DISTKEY": DistKeyProperty,
1685        "DISTSTYLE": DistStyleProperty,
1686        "ENGINE": EngineProperty,
1687        "EXECUTE AS": ExecuteAsProperty,
1688        "FORMAT": FileFormatProperty,
1689        "LANGUAGE": LanguageProperty,
1690        "LOCATION": LocationProperty,
1691        "PARTITIONED_BY": PartitionedByProperty,
1692        "RETURNS": ReturnsProperty,
1693        "SORTKEY": SortKeyProperty,
1694        "TABLE_FORMAT": TableFormatProperty,
1695    }
1696
1697    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1698
1699    # CREATE property locations
1700    # Form: schema specified
1701    #   create [POST_CREATE]
1702    #     table a [POST_NAME]
1703    #     (b int) [POST_SCHEMA]
1704    #     with ([POST_WITH])
1705    #     index (b) [POST_INDEX]
1706    #
1707    # Form: alias selection
1708    #   create [POST_CREATE]
1709    #     table a [POST_NAME]
1710    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1711    #     index (c) [POST_INDEX]
1712    class Location(AutoName):
1713        POST_CREATE = auto()
1714        POST_NAME = auto()
1715        POST_SCHEMA = auto()
1716        POST_WITH = auto()
1717        POST_ALIAS = auto()
1718        POST_EXPRESSION = auto()
1719        POST_INDEX = auto()
1720        UNSUPPORTED = auto()
1721
1722    @classmethod
1723    def from_dict(cls, properties_dict) -> Properties:
1724        expressions = []
1725        for key, value in properties_dict.items():
1726            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1727            if property_cls:
1728                expressions.append(property_cls(this=convert(value)))
1729            else:
1730                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1731
1732        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
1722    @classmethod
1723    def from_dict(cls, properties_dict) -> Properties:
1724        expressions = []
1725        for key, value in properties_dict.items():
1726            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1727            if property_cls:
1728                expressions.append(property_cls(this=convert(value)))
1729            else:
1730                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1731
1732        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
1712    class Location(AutoName):
1713        POST_CREATE = auto()
1714        POST_NAME = auto()
1715        POST_SCHEMA = auto()
1716        POST_WITH = auto()
1717        POST_ALIAS = auto()
1718        POST_EXPRESSION = auto()
1719        POST_INDEX = auto()
1720        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):
1735class Qualify(Expression):
1736    pass
class Return(Expression):
1740class Return(Expression):
1741    pass
class Reference(Expression):
1744class Reference(Expression):
1745    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
1748class Tuple(Expression):
1749    arg_types = {"expressions": False}
class Subqueryable(Unionable):
1752class Subqueryable(Unionable):
1753    def subquery(self, alias=None, copy=True) -> Subquery:
1754        """
1755        Convert this expression to an aliased expression that can be used as a Subquery.
1756
1757        Example:
1758            >>> subquery = Select().select("x").from_("tbl").subquery()
1759            >>> Select().select("x").from_(subquery).sql()
1760            'SELECT x FROM (SELECT x FROM tbl)'
1761
1762        Args:
1763            alias (str | Identifier): an optional alias for the subquery
1764            copy (bool): if `False`, modify this expression instance in-place.
1765
1766        Returns:
1767            Alias: the subquery
1768        """
1769        instance = _maybe_copy(self, copy)
1770        return Subquery(
1771            this=instance,
1772            alias=TableAlias(this=to_identifier(alias)),
1773        )
1774
1775    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1776        raise NotImplementedError
1777
1778    @property
1779    def ctes(self):
1780        with_ = self.args.get("with")
1781        if not with_:
1782            return []
1783        return with_.expressions
1784
1785    @property
1786    def selects(self):
1787        raise NotImplementedError("Subqueryable objects must implement `selects`")
1788
1789    @property
1790    def named_selects(self):
1791        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1792
1793    def with_(
1794        self,
1795        alias,
1796        as_,
1797        recursive=None,
1798        append=True,
1799        dialect=None,
1800        copy=True,
1801        **opts,
1802    ):
1803        """
1804        Append to or set the common table expressions.
1805
1806        Example:
1807            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1808            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1809
1810        Args:
1811            alias (str | Expression): the SQL code string to parse as the table name.
1812                If an `Expression` instance is passed, this is used as-is.
1813            as_ (str | Expression): the SQL code string to parse as the table expression.
1814                If an `Expression` instance is passed, it will be used as-is.
1815            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1816            append (bool): if `True`, add to any existing expressions.
1817                Otherwise, this resets the expressions.
1818            dialect (str): the dialect used to parse the input expression.
1819            copy (bool): if `False`, modify this expression instance in-place.
1820            opts (kwargs): other options to use to parse the input expressions.
1821
1822        Returns:
1823            Select: the modified expression.
1824        """
1825        alias_expression = maybe_parse(
1826            alias,
1827            dialect=dialect,
1828            into=TableAlias,
1829            **opts,
1830        )
1831        as_expression = maybe_parse(
1832            as_,
1833            dialect=dialect,
1834            **opts,
1835        )
1836        cte = CTE(
1837            this=as_expression,
1838            alias=alias_expression,
1839        )
1840        return _apply_child_list_builder(
1841            cte,
1842            instance=self,
1843            arg="with",
1844            append=append,
1845            copy=copy,
1846            into=With,
1847            properties={"recursive": recursive or False},
1848        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
1753    def subquery(self, alias=None, copy=True) -> Subquery:
1754        """
1755        Convert this expression to an aliased expression that can be used as a Subquery.
1756
1757        Example:
1758            >>> subquery = Select().select("x").from_("tbl").subquery()
1759            >>> Select().select("x").from_(subquery).sql()
1760            'SELECT x FROM (SELECT x FROM tbl)'
1761
1762        Args:
1763            alias (str | Identifier): an optional alias for the subquery
1764            copy (bool): if `False`, modify this expression instance in-place.
1765
1766        Returns:
1767            Alias: the subquery
1768        """
1769        instance = _maybe_copy(self, copy)
1770        return Subquery(
1771            this=instance,
1772            alias=TableAlias(this=to_identifier(alias)),
1773        )

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

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

Alias: the subquery

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1775    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1776        raise NotImplementedError
def with_( self, alias, as_, recursive=None, append=True, dialect=None, copy=True, **opts):
1793    def with_(
1794        self,
1795        alias,
1796        as_,
1797        recursive=None,
1798        append=True,
1799        dialect=None,
1800        copy=True,
1801        **opts,
1802    ):
1803        """
1804        Append to or set the common table expressions.
1805
1806        Example:
1807            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1808            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1809
1810        Args:
1811            alias (str | Expression): the SQL code string to parse as the table name.
1812                If an `Expression` instance is passed, this is used as-is.
1813            as_ (str | Expression): the SQL code string to parse as the table expression.
1814                If an `Expression` instance is passed, it will be used as-is.
1815            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1816            append (bool): if `True`, add to any existing expressions.
1817                Otherwise, this resets the expressions.
1818            dialect (str): the dialect used to parse the input expression.
1819            copy (bool): if `False`, modify this expression instance in-place.
1820            opts (kwargs): other options to use to parse the input expressions.
1821
1822        Returns:
1823            Select: the modified expression.
1824        """
1825        alias_expression = maybe_parse(
1826            alias,
1827            dialect=dialect,
1828            into=TableAlias,
1829            **opts,
1830        )
1831        as_expression = maybe_parse(
1832            as_,
1833            dialect=dialect,
1834            **opts,
1835        )
1836        cte = CTE(
1837            this=as_expression,
1838            alias=alias_expression,
1839        )
1840        return _apply_child_list_builder(
1841            cte,
1842            instance=self,
1843            arg="with",
1844            append=append,
1845            copy=copy,
1846            into=With,
1847            properties={"recursive": recursive or False},
1848        )

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 (str | Expression): the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_ (str | Expression): the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive (bool): set the RECURSIVE part of the expression. Defaults to False.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

class Table(Expression):
1872class Table(Expression):
1873    arg_types = {
1874        "this": True,
1875        "alias": False,
1876        "db": False,
1877        "catalog": False,
1878        "laterals": False,
1879        "joins": False,
1880        "pivots": False,
1881        "hints": False,
1882        "system_time": False,
1883    }
1884
1885    @property
1886    def db(self) -> str:
1887        return self.text("db")
1888
1889    @property
1890    def catalog(self) -> str:
1891        return self.text("catalog")
class SystemTime(Expression):
1895class SystemTime(Expression):
1896    arg_types = {
1897        "this": False,
1898        "expression": False,
1899        "kind": True,
1900    }
class Union(Subqueryable):
1903class Union(Subqueryable):
1904    arg_types = {
1905        "with": False,
1906        "this": True,
1907        "expression": True,
1908        "distinct": False,
1909        **QUERY_MODIFIERS,
1910    }
1911
1912    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1913        """
1914        Set the LIMIT expression.
1915
1916        Example:
1917            >>> select("1").union(select("1")).limit(1).sql()
1918            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1919
1920        Args:
1921            expression (str | int | Expression): the SQL code string to parse.
1922                This can also be an integer.
1923                If a `Limit` instance is passed, this is used as-is.
1924                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1925            dialect (str): the dialect used to parse the input expression.
1926            copy (bool): if `False`, modify this expression instance in-place.
1927            opts (kwargs): other options to use to parse the input expressions.
1928
1929        Returns:
1930            Select: The limited subqueryable.
1931        """
1932        return (
1933            select("*")
1934            .from_(self.subquery(alias="_l_0", copy=copy))
1935            .limit(expression, dialect=dialect, copy=False, **opts)
1936        )
1937
1938    def select(
1939        self,
1940        *expressions: ExpOrStr,
1941        append: bool = True,
1942        dialect: DialectType = None,
1943        copy: bool = True,
1944        **opts,
1945    ) -> Union:
1946        """Append to or set the SELECT of the union recursively.
1947
1948        Example:
1949            >>> from sqlglot import parse_one
1950            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1951            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1952
1953        Args:
1954            *expressions: the SQL code strings to parse.
1955                If an `Expression` instance is passed, it will be used as-is.
1956            append: if `True`, add to any existing expressions.
1957                Otherwise, this resets the expressions.
1958            dialect: the dialect used to parse the input expressions.
1959            copy: if `False`, modify this expression instance in-place.
1960            opts: other options to use to parse the input expressions.
1961
1962        Returns:
1963            Union: the modified expression.
1964        """
1965        this = self.copy() if copy else self
1966        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1967        this.expression.unnest().select(
1968            *expressions, append=append, dialect=dialect, copy=False, **opts
1969        )
1970        return this
1971
1972    @property
1973    def named_selects(self):
1974        return self.this.unnest().named_selects
1975
1976    @property
1977    def is_star(self) -> bool:
1978        return self.this.is_star or self.expression.is_star
1979
1980    @property
1981    def selects(self):
1982        return self.this.unnest().selects
1983
1984    @property
1985    def left(self):
1986        return self.this
1987
1988    @property
1989    def right(self):
1990        return self.expression
def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1912    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1913        """
1914        Set the LIMIT expression.
1915
1916        Example:
1917            >>> select("1").union(select("1")).limit(1).sql()
1918            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1919
1920        Args:
1921            expression (str | int | Expression): the SQL code string to parse.
1922                This can also be an integer.
1923                If a `Limit` instance is passed, this is used as-is.
1924                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1925            dialect (str): the dialect used to parse the input expression.
1926            copy (bool): if `False`, modify this expression instance in-place.
1927            opts (kwargs): other options to use to parse the input expressions.
1928
1929        Returns:
1930            Select: The limited subqueryable.
1931        """
1932        return (
1933            select("*")
1934            .from_(self.subquery(alias="_l_0", copy=copy))
1935            .limit(expression, dialect=dialect, copy=False, **opts)
1936        )

Set the LIMIT expression.

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

Select: The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
1938    def select(
1939        self,
1940        *expressions: ExpOrStr,
1941        append: bool = True,
1942        dialect: DialectType = None,
1943        copy: bool = True,
1944        **opts,
1945    ) -> Union:
1946        """Append to or set the SELECT of the union recursively.
1947
1948        Example:
1949            >>> from sqlglot import parse_one
1950            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1951            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1952
1953        Args:
1954            *expressions: the SQL code strings to parse.
1955                If an `Expression` instance is passed, it will be used as-is.
1956            append: if `True`, add to any existing expressions.
1957                Otherwise, this resets the expressions.
1958            dialect: the dialect used to parse the input expressions.
1959            copy: if `False`, modify this expression instance in-place.
1960            opts: other options to use to parse the input expressions.
1961
1962        Returns:
1963            Union: the modified expression.
1964        """
1965        this = self.copy() if copy else self
1966        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
1967        this.expression.unnest().select(
1968            *expressions, append=append, dialect=dialect, copy=False, **opts
1969        )
1970        return this

Append to or set the SELECT of the union recursively.

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

Union: the modified expression.

is_star: bool

Checks whether an expression is a star.

class Except(Union):
1993class Except(Union):
1994    pass
class Intersect(Union):
1997class Intersect(Union):
1998    pass
class Unnest(UDTF):
2001class Unnest(UDTF):
2002    arg_types = {
2003        "expressions": True,
2004        "ordinality": False,
2005        "alias": False,
2006        "offset": False,
2007    }
class Update(Expression):
2010class Update(Expression):
2011    arg_types = {
2012        "with": False,
2013        "this": False,
2014        "expressions": True,
2015        "from": False,
2016        "where": False,
2017        "returning": False,
2018    }
class Values(UDTF):
2021class Values(UDTF):
2022    arg_types = {
2023        "expressions": True,
2024        "ordinality": False,
2025        "alias": False,
2026    }
class Var(Expression):
2029class Var(Expression):
2030    pass
class Schema(Expression):
2033class Schema(Expression):
2034    arg_types = {"this": False, "expressions": False}
class Lock(Expression):
2039class Lock(Expression):
2040    arg_types = {"update": True}
class Select(Subqueryable):
2043class Select(Subqueryable):
2044    arg_types = {
2045        "with": False,
2046        "expressions": False,
2047        "hint": False,
2048        "distinct": False,
2049        "into": False,
2050        "from": False,
2051        **QUERY_MODIFIERS,
2052    }
2053
2054    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2055        """
2056        Set the FROM expression.
2057
2058        Example:
2059            >>> Select().from_("tbl").select("x").sql()
2060            'SELECT x FROM tbl'
2061
2062        Args:
2063            *expressions (str | Expression): the SQL code strings to parse.
2064                If a `From` instance is passed, this is used as-is.
2065                If another `Expression` instance is passed, it will be wrapped in a `From`.
2066            append (bool): if `True`, add to any existing expressions.
2067                Otherwise, this flattens all the `From` expression into a single expression.
2068            dialect (str): the dialect used to parse the input expression.
2069            copy (bool): if `False`, modify this expression instance in-place.
2070            opts (kwargs): other options to use to parse the input expressions.
2071
2072        Returns:
2073            Select: the modified expression.
2074        """
2075        return _apply_child_list_builder(
2076            *expressions,
2077            instance=self,
2078            arg="from",
2079            append=append,
2080            copy=copy,
2081            prefix="FROM",
2082            into=From,
2083            dialect=dialect,
2084            **opts,
2085        )
2086
2087    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2088        """
2089        Set the GROUP BY expression.
2090
2091        Example:
2092            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2093            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2094
2095        Args:
2096            *expressions (str | Expression): the SQL code strings to parse.
2097                If a `Group` instance is passed, this is used as-is.
2098                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2099                If nothing is passed in then a group by is not applied to the expression
2100            append (bool): if `True`, add to any existing expressions.
2101                Otherwise, this flattens all the `Group` expression into a single expression.
2102            dialect (str): the dialect used to parse the input expression.
2103            copy (bool): if `False`, modify this expression instance in-place.
2104            opts (kwargs): other options to use to parse the input expressions.
2105
2106        Returns:
2107            Select: the modified expression.
2108        """
2109        if not expressions:
2110            return self if not copy else self.copy()
2111        return _apply_child_list_builder(
2112            *expressions,
2113            instance=self,
2114            arg="group",
2115            append=append,
2116            copy=copy,
2117            prefix="GROUP BY",
2118            into=Group,
2119            dialect=dialect,
2120            **opts,
2121        )
2122
2123    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2124        """
2125        Set the ORDER BY expression.
2126
2127        Example:
2128            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2129            'SELECT x FROM tbl ORDER BY x DESC'
2130
2131        Args:
2132            *expressions (str | Expression): the SQL code strings to parse.
2133                If a `Group` instance is passed, this is used as-is.
2134                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2135            append (bool): if `True`, add to any existing expressions.
2136                Otherwise, this flattens all the `Order` expression into a single expression.
2137            dialect (str): the dialect used to parse the input expression.
2138            copy (bool): if `False`, modify this expression instance in-place.
2139            opts (kwargs): other options to use to parse the input expressions.
2140
2141        Returns:
2142            Select: the modified expression.
2143        """
2144        return _apply_child_list_builder(
2145            *expressions,
2146            instance=self,
2147            arg="order",
2148            append=append,
2149            copy=copy,
2150            prefix="ORDER BY",
2151            into=Order,
2152            dialect=dialect,
2153            **opts,
2154        )
2155
2156    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2157        """
2158        Set the SORT BY expression.
2159
2160        Example:
2161            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2162            'SELECT x FROM tbl SORT BY x DESC'
2163
2164        Args:
2165            *expressions (str | Expression): the SQL code strings to parse.
2166                If a `Group` instance is passed, this is used as-is.
2167                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2168            append (bool): if `True`, add to any existing expressions.
2169                Otherwise, this flattens all the `Order` expression into a single expression.
2170            dialect (str): the dialect used to parse the input expression.
2171            copy (bool): if `False`, modify this expression instance in-place.
2172            opts (kwargs): other options to use to parse the input expressions.
2173
2174        Returns:
2175            Select: the modified expression.
2176        """
2177        return _apply_child_list_builder(
2178            *expressions,
2179            instance=self,
2180            arg="sort",
2181            append=append,
2182            copy=copy,
2183            prefix="SORT BY",
2184            into=Sort,
2185            dialect=dialect,
2186            **opts,
2187        )
2188
2189    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2190        """
2191        Set the CLUSTER BY expression.
2192
2193        Example:
2194            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2195            'SELECT x FROM tbl CLUSTER BY x DESC'
2196
2197        Args:
2198            *expressions (str | Expression): the SQL code strings to parse.
2199                If a `Group` instance is passed, this is used as-is.
2200                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2201            append (bool): if `True`, add to any existing expressions.
2202                Otherwise, this flattens all the `Order` expression into a single expression.
2203            dialect (str): the dialect used to parse the input expression.
2204            copy (bool): if `False`, modify this expression instance in-place.
2205            opts (kwargs): other options to use to parse the input expressions.
2206
2207        Returns:
2208            Select: the modified expression.
2209        """
2210        return _apply_child_list_builder(
2211            *expressions,
2212            instance=self,
2213            arg="cluster",
2214            append=append,
2215            copy=copy,
2216            prefix="CLUSTER BY",
2217            into=Cluster,
2218            dialect=dialect,
2219            **opts,
2220        )
2221
2222    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2223        """
2224        Set the LIMIT expression.
2225
2226        Example:
2227            >>> Select().from_("tbl").select("x").limit(10).sql()
2228            'SELECT x FROM tbl LIMIT 10'
2229
2230        Args:
2231            expression (str | int | Expression): the SQL code string to parse.
2232                This can also be an integer.
2233                If a `Limit` instance is passed, this is used as-is.
2234                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2235            dialect (str): the dialect used to parse the input expression.
2236            copy (bool): if `False`, modify this expression instance in-place.
2237            opts (kwargs): other options to use to parse the input expressions.
2238
2239        Returns:
2240            Select: the modified expression.
2241        """
2242        return _apply_builder(
2243            expression=expression,
2244            instance=self,
2245            arg="limit",
2246            into=Limit,
2247            prefix="LIMIT",
2248            dialect=dialect,
2249            copy=copy,
2250            **opts,
2251        )
2252
2253    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2254        """
2255        Set the OFFSET expression.
2256
2257        Example:
2258            >>> Select().from_("tbl").select("x").offset(10).sql()
2259            'SELECT x FROM tbl OFFSET 10'
2260
2261        Args:
2262            expression (str | int | Expression): the SQL code string to parse.
2263                This can also be an integer.
2264                If a `Offset` instance is passed, this is used as-is.
2265                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2266            dialect (str): the dialect used to parse the input expression.
2267            copy (bool): if `False`, modify this expression instance in-place.
2268            opts (kwargs): other options to use to parse the input expressions.
2269
2270        Returns:
2271            Select: the modified expression.
2272        """
2273        return _apply_builder(
2274            expression=expression,
2275            instance=self,
2276            arg="offset",
2277            into=Offset,
2278            prefix="OFFSET",
2279            dialect=dialect,
2280            copy=copy,
2281            **opts,
2282        )
2283
2284    def select(
2285        self,
2286        *expressions: ExpOrStr,
2287        append: bool = True,
2288        dialect: DialectType = None,
2289        copy: bool = True,
2290        **opts,
2291    ) -> Select:
2292        """
2293        Append to or set the SELECT expressions.
2294
2295        Example:
2296            >>> Select().select("x", "y").sql()
2297            'SELECT x, y'
2298
2299        Args:
2300            *expressions: the SQL code strings to parse.
2301                If an `Expression` instance is passed, it will be used as-is.
2302            append: if `True`, add to any existing expressions.
2303                Otherwise, this resets the expressions.
2304            dialect: the dialect used to parse the input expressions.
2305            copy: if `False`, modify this expression instance in-place.
2306            opts: other options to use to parse the input expressions.
2307
2308        Returns:
2309            Select: the modified expression.
2310        """
2311        return _apply_list_builder(
2312            *expressions,
2313            instance=self,
2314            arg="expressions",
2315            append=append,
2316            dialect=dialect,
2317            copy=copy,
2318            **opts,
2319        )
2320
2321    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2322        """
2323        Append to or set the LATERAL expressions.
2324
2325        Example:
2326            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2327            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2328
2329        Args:
2330            *expressions (str | Expression): the SQL code strings to parse.
2331                If an `Expression` instance is passed, it will be used as-is.
2332            append (bool): if `True`, add to any existing expressions.
2333                Otherwise, this resets the expressions.
2334            dialect (str): the dialect used to parse the input expressions.
2335            copy (bool): if `False`, modify this expression instance in-place.
2336            opts (kwargs): other options to use to parse the input expressions.
2337
2338        Returns:
2339            Select: the modified expression.
2340        """
2341        return _apply_list_builder(
2342            *expressions,
2343            instance=self,
2344            arg="laterals",
2345            append=append,
2346            into=Lateral,
2347            prefix="LATERAL VIEW",
2348            dialect=dialect,
2349            copy=copy,
2350            **opts,
2351        )
2352
2353    def join(
2354        self,
2355        expression,
2356        on=None,
2357        using=None,
2358        append=True,
2359        join_type=None,
2360        join_alias=None,
2361        dialect=None,
2362        copy=True,
2363        **opts,
2364    ) -> Select:
2365        """
2366        Append to or set the JOIN expressions.
2367
2368        Example:
2369            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2370            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2371
2372            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2373            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2374
2375            Use `join_type` to change the type of join:
2376
2377            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2378            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2379
2380        Args:
2381            expression (str | Expression): the SQL code string to parse.
2382                If an `Expression` instance is passed, it will be used as-is.
2383            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2384                If an `Expression` instance is passed, it will be used as-is.
2385            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2386                If an `Expression` instance is passed, it will be used as-is.
2387            append (bool): if `True`, add to any existing expressions.
2388                Otherwise, this resets the expressions.
2389            join_type (str): If set, alter the parsed join type
2390            dialect (str): the dialect used to parse the input expressions.
2391            copy (bool): if `False`, modify this expression instance in-place.
2392            opts (kwargs): other options to use to parse the input expressions.
2393
2394        Returns:
2395            Select: the modified expression.
2396        """
2397        parse_args = {"dialect": dialect, **opts}
2398
2399        try:
2400            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2401        except ParseError:
2402            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2403
2404        join = expression if isinstance(expression, Join) else Join(this=expression)
2405
2406        if isinstance(join.this, Select):
2407            join.this.replace(join.this.subquery())
2408
2409        if join_type:
2410            natural: t.Optional[Token]
2411            side: t.Optional[Token]
2412            kind: t.Optional[Token]
2413
2414            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2415
2416            if natural:
2417                join.set("natural", True)
2418            if side:
2419                join.set("side", side.text)
2420            if kind:
2421                join.set("kind", kind.text)
2422
2423        if on:
2424            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2425            join.set("on", on)
2426
2427        if using:
2428            join = _apply_list_builder(
2429                *ensure_collection(using),
2430                instance=join,
2431                arg="using",
2432                append=append,
2433                copy=copy,
2434                **opts,
2435            )
2436
2437        if join_alias:
2438            join.set("this", alias_(join.this, join_alias, table=True))
2439        return _apply_list_builder(
2440            join,
2441            instance=self,
2442            arg="joins",
2443            append=append,
2444            copy=copy,
2445            **opts,
2446        )
2447
2448    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2449        """
2450        Append to or set the WHERE expressions.
2451
2452        Example:
2453            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2454            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2455
2456        Args:
2457            *expressions (str | Expression): the SQL code strings to parse.
2458                If an `Expression` instance is passed, it will be used as-is.
2459                Multiple expressions are combined with an AND operator.
2460            append (bool): if `True`, AND the new expressions to any existing expression.
2461                Otherwise, this resets the expression.
2462            dialect (str): the dialect used to parse the input expressions.
2463            copy (bool): if `False`, modify this expression instance in-place.
2464            opts (kwargs): other options to use to parse the input expressions.
2465
2466        Returns:
2467            Select: the modified expression.
2468        """
2469        return _apply_conjunction_builder(
2470            *expressions,
2471            instance=self,
2472            arg="where",
2473            append=append,
2474            into=Where,
2475            dialect=dialect,
2476            copy=copy,
2477            **opts,
2478        )
2479
2480    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2481        """
2482        Append to or set the HAVING expressions.
2483
2484        Example:
2485            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2486            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2487
2488        Args:
2489            *expressions (str | Expression): the SQL code strings to parse.
2490                If an `Expression` instance is passed, it will be used as-is.
2491                Multiple expressions are combined with an AND operator.
2492            append (bool): if `True`, AND the new expressions to any existing expression.
2493                Otherwise, this resets the expression.
2494            dialect (str): the dialect used to parse the input expressions.
2495            copy (bool): if `False`, modify this expression instance in-place.
2496            opts (kwargs): other options to use to parse the input expressions.
2497
2498        Returns:
2499            Select: the modified expression.
2500        """
2501        return _apply_conjunction_builder(
2502            *expressions,
2503            instance=self,
2504            arg="having",
2505            append=append,
2506            into=Having,
2507            dialect=dialect,
2508            copy=copy,
2509            **opts,
2510        )
2511
2512    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2513        return _apply_list_builder(
2514            *expressions,
2515            instance=self,
2516            arg="windows",
2517            append=append,
2518            into=Window,
2519            dialect=dialect,
2520            copy=copy,
2521            **opts,
2522        )
2523
2524    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2525        return _apply_conjunction_builder(
2526            *expressions,
2527            instance=self,
2528            arg="qualify",
2529            append=append,
2530            into=Qualify,
2531            dialect=dialect,
2532            copy=copy,
2533            **opts,
2534        )
2535
2536    def distinct(self, distinct=True, copy=True) -> Select:
2537        """
2538        Set the OFFSET expression.
2539
2540        Example:
2541            >>> Select().from_("tbl").select("x").distinct().sql()
2542            'SELECT DISTINCT x FROM tbl'
2543
2544        Args:
2545            distinct (bool): whether the Select should be distinct
2546            copy (bool): if `False`, modify this expression instance in-place.
2547
2548        Returns:
2549            Select: the modified expression.
2550        """
2551        instance = _maybe_copy(self, copy)
2552        instance.set("distinct", Distinct() if distinct else None)
2553        return instance
2554
2555    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2556        """
2557        Convert this expression to a CREATE TABLE AS statement.
2558
2559        Example:
2560            >>> Select().select("*").from_("tbl").ctas("x").sql()
2561            'CREATE TABLE x AS SELECT * FROM tbl'
2562
2563        Args:
2564            table (str | Expression): the SQL code string to parse as the table name.
2565                If another `Expression` instance is passed, it will be used as-is.
2566            properties (dict): an optional mapping of table properties
2567            dialect (str): the dialect used to parse the input table.
2568            copy (bool): if `False`, modify this expression instance in-place.
2569            opts (kwargs): other options to use to parse the input table.
2570
2571        Returns:
2572            Create: the CREATE TABLE AS expression
2573        """
2574        instance = _maybe_copy(self, copy)
2575        table_expression = maybe_parse(
2576            table,
2577            into=Table,
2578            dialect=dialect,
2579            **opts,
2580        )
2581        properties_expression = None
2582        if properties:
2583            properties_expression = Properties.from_dict(properties)
2584
2585        return Create(
2586            this=table_expression,
2587            kind="table",
2588            expression=instance,
2589            properties=properties_expression,
2590        )
2591
2592    def lock(self, update: bool = True, copy: bool = True) -> Select:
2593        """
2594        Set the locking read mode for this expression.
2595
2596        Examples:
2597            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2598            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2599
2600            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2601            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2602
2603        Args:
2604            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2605            copy: if `False`, modify this expression instance in-place.
2606
2607        Returns:
2608            The modified expression.
2609        """
2610
2611        inst = _maybe_copy(self, copy)
2612        inst.set("lock", Lock(update=update))
2613
2614        return inst
2615
2616    @property
2617    def named_selects(self) -> t.List[str]:
2618        return [e.output_name for e in self.expressions if e.alias_or_name]
2619
2620    @property
2621    def is_star(self) -> bool:
2622        return any(expression.is_star for expression in self.expressions)
2623
2624    @property
2625    def selects(self) -> t.List[Expression]:
2626        return self.expressions
def from_( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2054    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2055        """
2056        Set the FROM expression.
2057
2058        Example:
2059            >>> Select().from_("tbl").select("x").sql()
2060            'SELECT x FROM tbl'
2061
2062        Args:
2063            *expressions (str | Expression): the SQL code strings to parse.
2064                If a `From` instance is passed, this is used as-is.
2065                If another `Expression` instance is passed, it will be wrapped in a `From`.
2066            append (bool): if `True`, add to any existing expressions.
2067                Otherwise, this flattens all the `From` expression into a single expression.
2068            dialect (str): the dialect used to parse the input expression.
2069            copy (bool): if `False`, modify this expression instance in-place.
2070            opts (kwargs): other options to use to parse the input expressions.
2071
2072        Returns:
2073            Select: the modified expression.
2074        """
2075        return _apply_child_list_builder(
2076            *expressions,
2077            instance=self,
2078            arg="from",
2079            append=append,
2080            copy=copy,
2081            prefix="FROM",
2082            into=From,
2083            dialect=dialect,
2084            **opts,
2085        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • *expressions (str | 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.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the From expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def group_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2087    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2088        """
2089        Set the GROUP BY expression.
2090
2091        Example:
2092            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2093            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2094
2095        Args:
2096            *expressions (str | Expression): the SQL code strings to parse.
2097                If a `Group` instance is passed, this is used as-is.
2098                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2099                If nothing is passed in then a group by is not applied to the expression
2100            append (bool): if `True`, add to any existing expressions.
2101                Otherwise, this flattens all the `Group` expression into a single expression.
2102            dialect (str): the dialect used to parse the input expression.
2103            copy (bool): if `False`, modify this expression instance in-place.
2104            opts (kwargs): other options to use to parse the input expressions.
2105
2106        Returns:
2107            Select: the modified expression.
2108        """
2109        if not expressions:
2110            return self if not copy else self.copy()
2111        return _apply_child_list_builder(
2112            *expressions,
2113            instance=self,
2114            arg="group",
2115            append=append,
2116            copy=copy,
2117            prefix="GROUP BY",
2118            into=Group,
2119            dialect=dialect,
2120            **opts,
2121        )

Set the GROUP BY expression.

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

Select: the modified expression.

def order_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2123    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2124        """
2125        Set the ORDER BY expression.
2126
2127        Example:
2128            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2129            'SELECT x FROM tbl ORDER BY x DESC'
2130
2131        Args:
2132            *expressions (str | Expression): the SQL code strings to parse.
2133                If a `Group` instance is passed, this is used as-is.
2134                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2135            append (bool): if `True`, add to any existing expressions.
2136                Otherwise, this flattens all the `Order` expression into a single expression.
2137            dialect (str): the dialect used to parse the input expression.
2138            copy (bool): if `False`, modify this expression instance in-place.
2139            opts (kwargs): other options to use to parse the input expressions.
2140
2141        Returns:
2142            Select: the modified expression.
2143        """
2144        return _apply_child_list_builder(
2145            *expressions,
2146            instance=self,
2147            arg="order",
2148            append=append,
2149            copy=copy,
2150            prefix="ORDER BY",
2151            into=Order,
2152            dialect=dialect,
2153            **opts,
2154        )

Set the ORDER BY expression.

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

Select: the modified expression.

def sort_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2156    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2157        """
2158        Set the SORT BY expression.
2159
2160        Example:
2161            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2162            'SELECT x FROM tbl SORT BY x DESC'
2163
2164        Args:
2165            *expressions (str | Expression): the SQL code strings to parse.
2166                If a `Group` instance is passed, this is used as-is.
2167                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2168            append (bool): if `True`, add to any existing expressions.
2169                Otherwise, this flattens all the `Order` expression into a single expression.
2170            dialect (str): the dialect used to parse the input expression.
2171            copy (bool): if `False`, modify this expression instance in-place.
2172            opts (kwargs): other options to use to parse the input expressions.
2173
2174        Returns:
2175            Select: the modified expression.
2176        """
2177        return _apply_child_list_builder(
2178            *expressions,
2179            instance=self,
2180            arg="sort",
2181            append=append,
2182            copy=copy,
2183            prefix="SORT BY",
2184            into=Sort,
2185            dialect=dialect,
2186            **opts,
2187        )

Set the SORT BY expression.

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

Select: the modified expression.

def cluster_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2189    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2190        """
2191        Set the CLUSTER BY expression.
2192
2193        Example:
2194            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2195            'SELECT x FROM tbl CLUSTER BY x DESC'
2196
2197        Args:
2198            *expressions (str | Expression): the SQL code strings to parse.
2199                If a `Group` instance is passed, this is used as-is.
2200                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2201            append (bool): if `True`, add to any existing expressions.
2202                Otherwise, this flattens all the `Order` expression into a single expression.
2203            dialect (str): the dialect used to parse the input expression.
2204            copy (bool): if `False`, modify this expression instance in-place.
2205            opts (kwargs): other options to use to parse the input expressions.
2206
2207        Returns:
2208            Select: the modified expression.
2209        """
2210        return _apply_child_list_builder(
2211            *expressions,
2212            instance=self,
2213            arg="cluster",
2214            append=append,
2215            copy=copy,
2216            prefix="CLUSTER BY",
2217            into=Cluster,
2218            dialect=dialect,
2219            **opts,
2220        )

Set the CLUSTER BY expression.

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

Select: the modified expression.

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2222    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2223        """
2224        Set the LIMIT expression.
2225
2226        Example:
2227            >>> Select().from_("tbl").select("x").limit(10).sql()
2228            'SELECT x FROM tbl LIMIT 10'
2229
2230        Args:
2231            expression (str | int | Expression): the SQL code string to parse.
2232                This can also be an integer.
2233                If a `Limit` instance is passed, this is used as-is.
2234                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2235            dialect (str): the dialect used to parse the input expression.
2236            copy (bool): if `False`, modify this expression instance in-place.
2237            opts (kwargs): other options to use to parse the input expressions.
2238
2239        Returns:
2240            Select: the modified expression.
2241        """
2242        return _apply_builder(
2243            expression=expression,
2244            instance=self,
2245            arg="limit",
2246            into=Limit,
2247            prefix="LIMIT",
2248            dialect=dialect,
2249            copy=copy,
2250            **opts,
2251        )

Set the LIMIT expression.

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

Select: the modified expression.

def offset( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2253    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2254        """
2255        Set the OFFSET expression.
2256
2257        Example:
2258            >>> Select().from_("tbl").select("x").offset(10).sql()
2259            'SELECT x FROM tbl OFFSET 10'
2260
2261        Args:
2262            expression (str | int | Expression): the SQL code string to parse.
2263                This can also be an integer.
2264                If a `Offset` instance is passed, this is used as-is.
2265                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2266            dialect (str): the dialect used to parse the input expression.
2267            copy (bool): if `False`, modify this expression instance in-place.
2268            opts (kwargs): other options to use to parse the input expressions.
2269
2270        Returns:
2271            Select: the modified expression.
2272        """
2273        return _apply_builder(
2274            expression=expression,
2275            instance=self,
2276            arg="offset",
2277            into=Offset,
2278            prefix="OFFSET",
2279            dialect=dialect,
2280            copy=copy,
2281            **opts,
2282        )

Set the OFFSET expression.

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

Select: the modified expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2284    def select(
2285        self,
2286        *expressions: ExpOrStr,
2287        append: bool = True,
2288        dialect: DialectType = None,
2289        copy: bool = True,
2290        **opts,
2291    ) -> Select:
2292        """
2293        Append to or set the SELECT expressions.
2294
2295        Example:
2296            >>> Select().select("x", "y").sql()
2297            'SELECT x, y'
2298
2299        Args:
2300            *expressions: the SQL code strings to parse.
2301                If an `Expression` instance is passed, it will be used as-is.
2302            append: if `True`, add to any existing expressions.
2303                Otherwise, this resets the expressions.
2304            dialect: the dialect used to parse the input expressions.
2305            copy: if `False`, modify this expression instance in-place.
2306            opts: other options to use to parse the input expressions.
2307
2308        Returns:
2309            Select: the modified expression.
2310        """
2311        return _apply_list_builder(
2312            *expressions,
2313            instance=self,
2314            arg="expressions",
2315            append=append,
2316            dialect=dialect,
2317            copy=copy,
2318            **opts,
2319        )

Append to or set the SELECT expressions.

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

Select: the modified expression.

def lateral( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2321    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2322        """
2323        Append to or set the LATERAL expressions.
2324
2325        Example:
2326            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2327            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2328
2329        Args:
2330            *expressions (str | Expression): the SQL code strings to parse.
2331                If an `Expression` instance is passed, it will be used as-is.
2332            append (bool): if `True`, add to any existing expressions.
2333                Otherwise, this resets the expressions.
2334            dialect (str): the dialect used to parse the input expressions.
2335            copy (bool): if `False`, modify this expression instance in-place.
2336            opts (kwargs): other options to use to parse the input expressions.
2337
2338        Returns:
2339            Select: the modified expression.
2340        """
2341        return _apply_list_builder(
2342            *expressions,
2343            instance=self,
2344            arg="laterals",
2345            append=append,
2346            into=Lateral,
2347            prefix="LATERAL VIEW",
2348            dialect=dialect,
2349            copy=copy,
2350            **opts,
2351        )

Append to or set the LATERAL expressions.

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

Select: the modified expression.

def join( self, expression, on=None, using=None, append=True, join_type=None, join_alias=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2353    def join(
2354        self,
2355        expression,
2356        on=None,
2357        using=None,
2358        append=True,
2359        join_type=None,
2360        join_alias=None,
2361        dialect=None,
2362        copy=True,
2363        **opts,
2364    ) -> Select:
2365        """
2366        Append to or set the JOIN expressions.
2367
2368        Example:
2369            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2370            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2371
2372            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2373            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2374
2375            Use `join_type` to change the type of join:
2376
2377            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2378            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2379
2380        Args:
2381            expression (str | Expression): the SQL code string to parse.
2382                If an `Expression` instance is passed, it will be used as-is.
2383            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2384                If an `Expression` instance is passed, it will be used as-is.
2385            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2386                If an `Expression` instance is passed, it will be used as-is.
2387            append (bool): if `True`, add to any existing expressions.
2388                Otherwise, this resets the expressions.
2389            join_type (str): If set, alter the parsed join type
2390            dialect (str): the dialect used to parse the input expressions.
2391            copy (bool): if `False`, modify this expression instance in-place.
2392            opts (kwargs): other options to use to parse the input expressions.
2393
2394        Returns:
2395            Select: the modified expression.
2396        """
2397        parse_args = {"dialect": dialect, **opts}
2398
2399        try:
2400            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2401        except ParseError:
2402            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2403
2404        join = expression if isinstance(expression, Join) else Join(this=expression)
2405
2406        if isinstance(join.this, Select):
2407            join.this.replace(join.this.subquery())
2408
2409        if join_type:
2410            natural: t.Optional[Token]
2411            side: t.Optional[Token]
2412            kind: t.Optional[Token]
2413
2414            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2415
2416            if natural:
2417                join.set("natural", True)
2418            if side:
2419                join.set("side", side.text)
2420            if kind:
2421                join.set("kind", kind.text)
2422
2423        if on:
2424            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2425            join.set("on", on)
2426
2427        if using:
2428            join = _apply_list_builder(
2429                *ensure_collection(using),
2430                instance=join,
2431                arg="using",
2432                append=append,
2433                copy=copy,
2434                **opts,
2435            )
2436
2437        if join_alias:
2438            join.set("this", alias_(join.this, join_alias, table=True))
2439        return _apply_list_builder(
2440            join,
2441            instance=self,
2442            arg="joins",
2443            append=append,
2444            copy=copy,
2445            **opts,
2446        )

Append to or set the JOIN expressions.

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

Use join_type to change the type of join:

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

Select: the modified expression.

def where( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2448    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2449        """
2450        Append to or set the WHERE expressions.
2451
2452        Example:
2453            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2454            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2455
2456        Args:
2457            *expressions (str | Expression): the SQL code strings to parse.
2458                If an `Expression` instance is passed, it will be used as-is.
2459                Multiple expressions are combined with an AND operator.
2460            append (bool): if `True`, AND the new expressions to any existing expression.
2461                Otherwise, this resets the expression.
2462            dialect (str): the dialect used to parse the input expressions.
2463            copy (bool): if `False`, modify this expression instance in-place.
2464            opts (kwargs): other options to use to parse the input expressions.
2465
2466        Returns:
2467            Select: the modified expression.
2468        """
2469        return _apply_conjunction_builder(
2470            *expressions,
2471            instance=self,
2472            arg="where",
2473            append=append,
2474            into=Where,
2475            dialect=dialect,
2476            copy=copy,
2477            **opts,
2478        )

Append to or set the WHERE expressions.

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

Select: the modified expression.

def having( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2480    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2481        """
2482        Append to or set the HAVING expressions.
2483
2484        Example:
2485            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2486            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2487
2488        Args:
2489            *expressions (str | Expression): the SQL code strings to parse.
2490                If an `Expression` instance is passed, it will be used as-is.
2491                Multiple expressions are combined with an AND operator.
2492            append (bool): if `True`, AND the new expressions to any existing expression.
2493                Otherwise, this resets the expression.
2494            dialect (str): the dialect used to parse the input expressions.
2495            copy (bool): if `False`, modify this expression instance in-place.
2496            opts (kwargs): other options to use to parse the input expressions.
2497
2498        Returns:
2499            Select: the modified expression.
2500        """
2501        return _apply_conjunction_builder(
2502            *expressions,
2503            instance=self,
2504            arg="having",
2505            append=append,
2506            into=Having,
2507            dialect=dialect,
2508            copy=copy,
2509            **opts,
2510        )

Append to or set the HAVING expressions.

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

Select: the modified expression.

def window( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2512    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2513        return _apply_list_builder(
2514            *expressions,
2515            instance=self,
2516            arg="windows",
2517            append=append,
2518            into=Window,
2519            dialect=dialect,
2520            copy=copy,
2521            **opts,
2522        )
def qualify( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2524    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2525        return _apply_conjunction_builder(
2526            *expressions,
2527            instance=self,
2528            arg="qualify",
2529            append=append,
2530            into=Qualify,
2531            dialect=dialect,
2532            copy=copy,
2533            **opts,
2534        )
def distinct(self, distinct=True, copy=True) -> sqlglot.expressions.Select:
2536    def distinct(self, distinct=True, copy=True) -> Select:
2537        """
2538        Set the OFFSET expression.
2539
2540        Example:
2541            >>> Select().from_("tbl").select("x").distinct().sql()
2542            'SELECT DISTINCT x FROM tbl'
2543
2544        Args:
2545            distinct (bool): whether the Select should be distinct
2546            copy (bool): if `False`, modify this expression instance in-place.
2547
2548        Returns:
2549            Select: the modified expression.
2550        """
2551        instance = _maybe_copy(self, copy)
2552        instance.set("distinct", Distinct() if distinct else None)
2553        return instance

Set the OFFSET expression.

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

Select: the modified expression.

def ctas( self, table, properties=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Create:
2555    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2556        """
2557        Convert this expression to a CREATE TABLE AS statement.
2558
2559        Example:
2560            >>> Select().select("*").from_("tbl").ctas("x").sql()
2561            'CREATE TABLE x AS SELECT * FROM tbl'
2562
2563        Args:
2564            table (str | Expression): the SQL code string to parse as the table name.
2565                If another `Expression` instance is passed, it will be used as-is.
2566            properties (dict): an optional mapping of table properties
2567            dialect (str): the dialect used to parse the input table.
2568            copy (bool): if `False`, modify this expression instance in-place.
2569            opts (kwargs): other options to use to parse the input table.
2570
2571        Returns:
2572            Create: the CREATE TABLE AS expression
2573        """
2574        instance = _maybe_copy(self, copy)
2575        table_expression = maybe_parse(
2576            table,
2577            into=Table,
2578            dialect=dialect,
2579            **opts,
2580        )
2581        properties_expression = None
2582        if properties:
2583            properties_expression = Properties.from_dict(properties)
2584
2585        return Create(
2586            this=table_expression,
2587            kind="table",
2588            expression=instance,
2589            properties=properties_expression,
2590        )

Convert this expression to a CREATE TABLE AS statement.

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

Create: the CREATE TABLE AS expression

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2592    def lock(self, update: bool = True, copy: bool = True) -> Select:
2593        """
2594        Set the locking read mode for this expression.
2595
2596        Examples:
2597            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2598            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2599
2600            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2601            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2602
2603        Args:
2604            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2605            copy: if `False`, modify this expression instance in-place.
2606
2607        Returns:
2608            The modified expression.
2609        """
2610
2611        inst = _maybe_copy(self, copy)
2612        inst.set("lock", Lock(update=update))
2613
2614        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

is_star: bool

Checks whether an expression is a star.

class Subquery(DerivedTable, Unionable):
2629class Subquery(DerivedTable, Unionable):
2630    arg_types = {
2631        "this": True,
2632        "alias": False,
2633        "with": False,
2634        **QUERY_MODIFIERS,
2635    }
2636
2637    def unnest(self):
2638        """
2639        Returns the first non subquery.
2640        """
2641        expression = self
2642        while isinstance(expression, Subquery):
2643            expression = expression.this
2644        return expression
2645
2646    @property
2647    def is_star(self) -> bool:
2648        return self.this.is_star
2649
2650    @property
2651    def output_name(self):
2652        return self.alias
def unnest(self):
2637    def unnest(self):
2638        """
2639        Returns the first non subquery.
2640        """
2641        expression = self
2642        while isinstance(expression, Subquery):
2643            expression = expression.this
2644        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class TableSample(Expression):
2655class TableSample(Expression):
2656    arg_types = {
2657        "this": False,
2658        "method": False,
2659        "bucket_numerator": False,
2660        "bucket_denominator": False,
2661        "bucket_field": False,
2662        "percent": False,
2663        "rows": False,
2664        "size": False,
2665        "seed": False,
2666        "kind": False,
2667    }
class Tag(Expression):
2670class Tag(Expression):
2671    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2672
2673    arg_types = {
2674        "this": False,
2675        "prefix": False,
2676        "postfix": False,
2677    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2680class Pivot(Expression):
2681    arg_types = {
2682        "this": False,
2683        "alias": False,
2684        "expressions": True,
2685        "field": True,
2686        "unpivot": True,
2687    }
class Window(Expression):
2690class Window(Expression):
2691    arg_types = {
2692        "this": True,
2693        "partition_by": False,
2694        "order": False,
2695        "spec": False,
2696        "alias": False,
2697    }
class WindowSpec(Expression):
2700class WindowSpec(Expression):
2701    arg_types = {
2702        "kind": False,
2703        "start": False,
2704        "start_side": False,
2705        "end": False,
2706        "end_side": False,
2707    }
class Where(Expression):
2710class Where(Expression):
2711    pass
class Star(Expression):
2714class Star(Expression):
2715    arg_types = {"except": False, "replace": False}
2716
2717    @property
2718    def name(self) -> str:
2719        return "*"
2720
2721    @property
2722    def output_name(self):
2723        return self.name
output_name

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Parameter(Expression):
2726class Parameter(Expression):
2727    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
2730class SessionParameter(Expression):
2731    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
2734class Placeholder(Expression):
2735    arg_types = {"this": False}
class Null(Condition):
2738class Null(Condition):
2739    arg_types: t.Dict[str, t.Any] = {}
2740
2741    @property
2742    def name(self) -> str:
2743        return "NULL"
class Boolean(Condition):
2746class Boolean(Condition):
2747    pass
class DataType(Expression):
2750class DataType(Expression):
2751    arg_types = {
2752        "this": True,
2753        "expressions": False,
2754        "nested": False,
2755        "values": False,
2756        "prefix": False,
2757    }
2758
2759    class Type(AutoName):
2760        CHAR = auto()
2761        NCHAR = auto()
2762        VARCHAR = auto()
2763        NVARCHAR = auto()
2764        TEXT = auto()
2765        MEDIUMTEXT = auto()
2766        LONGTEXT = auto()
2767        MEDIUMBLOB = auto()
2768        LONGBLOB = auto()
2769        BINARY = auto()
2770        VARBINARY = auto()
2771        INT = auto()
2772        UINT = auto()
2773        TINYINT = auto()
2774        UTINYINT = auto()
2775        SMALLINT = auto()
2776        USMALLINT = auto()
2777        BIGINT = auto()
2778        UBIGINT = auto()
2779        FLOAT = auto()
2780        DOUBLE = auto()
2781        DECIMAL = auto()
2782        BIT = auto()
2783        BOOLEAN = auto()
2784        JSON = auto()
2785        JSONB = auto()
2786        INTERVAL = auto()
2787        TIME = auto()
2788        TIMESTAMP = auto()
2789        TIMESTAMPTZ = auto()
2790        TIMESTAMPLTZ = auto()
2791        DATE = auto()
2792        DATETIME = auto()
2793        ARRAY = auto()
2794        MAP = auto()
2795        UUID = auto()
2796        GEOGRAPHY = auto()
2797        GEOMETRY = auto()
2798        STRUCT = auto()
2799        NULLABLE = auto()
2800        HLLSKETCH = auto()
2801        HSTORE = auto()
2802        SUPER = auto()
2803        SERIAL = auto()
2804        SMALLSERIAL = auto()
2805        BIGSERIAL = auto()
2806        XML = auto()
2807        UNIQUEIDENTIFIER = auto()
2808        MONEY = auto()
2809        SMALLMONEY = auto()
2810        ROWVERSION = auto()
2811        IMAGE = auto()
2812        VARIANT = auto()
2813        OBJECT = auto()
2814        INET = auto()
2815        NULL = auto()
2816        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2817
2818    TEXT_TYPES = {
2819        Type.CHAR,
2820        Type.NCHAR,
2821        Type.VARCHAR,
2822        Type.NVARCHAR,
2823        Type.TEXT,
2824    }
2825
2826    INTEGER_TYPES = {
2827        Type.INT,
2828        Type.TINYINT,
2829        Type.SMALLINT,
2830        Type.BIGINT,
2831    }
2832
2833    FLOAT_TYPES = {
2834        Type.FLOAT,
2835        Type.DOUBLE,
2836    }
2837
2838    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2839
2840    TEMPORAL_TYPES = {
2841        Type.TIMESTAMP,
2842        Type.TIMESTAMPTZ,
2843        Type.TIMESTAMPLTZ,
2844        Type.DATE,
2845        Type.DATETIME,
2846    }
2847
2848    @classmethod
2849    def build(
2850        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2851    ) -> DataType:
2852        from sqlglot import parse_one
2853
2854        if isinstance(dtype, str):
2855            if dtype.upper() in cls.Type.__members__:
2856                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2857            else:
2858                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2859            if data_type_exp is None:
2860                raise ValueError(f"Unparsable data type value: {dtype}")
2861        elif isinstance(dtype, DataType.Type):
2862            data_type_exp = DataType(this=dtype)
2863        elif isinstance(dtype, DataType):
2864            return dtype
2865        else:
2866            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2867        return DataType(**{**data_type_exp.args, **kwargs})
2868
2869    def is_type(self, dtype: DataType.Type) -> bool:
2870        return self.this == dtype
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
2848    @classmethod
2849    def build(
2850        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2851    ) -> DataType:
2852        from sqlglot import parse_one
2853
2854        if isinstance(dtype, str):
2855            if dtype.upper() in cls.Type.__members__:
2856                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2857            else:
2858                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2859            if data_type_exp is None:
2860                raise ValueError(f"Unparsable data type value: {dtype}")
2861        elif isinstance(dtype, DataType.Type):
2862            data_type_exp = DataType(this=dtype)
2863        elif isinstance(dtype, DataType):
2864            return dtype
2865        else:
2866            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2867        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
2869    def is_type(self, dtype: DataType.Type) -> bool:
2870        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
2759    class Type(AutoName):
2760        CHAR = auto()
2761        NCHAR = auto()
2762        VARCHAR = auto()
2763        NVARCHAR = auto()
2764        TEXT = auto()
2765        MEDIUMTEXT = auto()
2766        LONGTEXT = auto()
2767        MEDIUMBLOB = auto()
2768        LONGBLOB = auto()
2769        BINARY = auto()
2770        VARBINARY = auto()
2771        INT = auto()
2772        UINT = auto()
2773        TINYINT = auto()
2774        UTINYINT = auto()
2775        SMALLINT = auto()
2776        USMALLINT = auto()
2777        BIGINT = auto()
2778        UBIGINT = auto()
2779        FLOAT = auto()
2780        DOUBLE = auto()
2781        DECIMAL = auto()
2782        BIT = auto()
2783        BOOLEAN = auto()
2784        JSON = auto()
2785        JSONB = auto()
2786        INTERVAL = auto()
2787        TIME = auto()
2788        TIMESTAMP = auto()
2789        TIMESTAMPTZ = auto()
2790        TIMESTAMPLTZ = auto()
2791        DATE = auto()
2792        DATETIME = auto()
2793        ARRAY = auto()
2794        MAP = auto()
2795        UUID = auto()
2796        GEOGRAPHY = auto()
2797        GEOMETRY = auto()
2798        STRUCT = auto()
2799        NULLABLE = auto()
2800        HLLSKETCH = auto()
2801        HSTORE = auto()
2802        SUPER = auto()
2803        SERIAL = auto()
2804        SMALLSERIAL = auto()
2805        BIGSERIAL = auto()
2806        XML = auto()
2807        UNIQUEIDENTIFIER = auto()
2808        MONEY = auto()
2809        SMALLMONEY = auto()
2810        ROWVERSION = auto()
2811        IMAGE = auto()
2812        VARIANT = auto()
2813        OBJECT = auto()
2814        INET = auto()
2815        NULL = auto()
2816        UNKNOWN = auto()  # Sentinel value, useful for type annotation

An enumeration.

CHAR = <Type.CHAR: 'CHAR'>
NCHAR = <Type.NCHAR: 'NCHAR'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
TEXT = <Type.TEXT: 'TEXT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
BINARY = <Type.BINARY: 'BINARY'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
INT = <Type.INT: 'INT'>
UINT = <Type.UINT: 'UINT'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
BIGINT = <Type.BIGINT: 'BIGINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
FLOAT = <Type.FLOAT: 'FLOAT'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
ARRAY = <Type.ARRAY: 'ARRAY'>
MAP = <Type.MAP: 'MAP'>
UUID = <Type.UUID: 'UUID'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
STRUCT = <Type.STRUCT: 'STRUCT'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
SUPER = <Type.SUPER: 'SUPER'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
XML = <Type.XML: 'XML'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
MONEY = <Type.MONEY: 'MONEY'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
IMAGE = <Type.IMAGE: 'IMAGE'>
VARIANT = <Type.VARIANT: 'VARIANT'>
OBJECT = <Type.OBJECT: 'OBJECT'>
INET = <Type.INET: 'INET'>
NULL = <Type.NULL: 'NULL'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
2874class PseudoType(Expression):
2875    pass
class StructKwarg(Expression):
2878class StructKwarg(Expression):
2879    arg_types = {"this": True, "expression": True}
class SubqueryPredicate(Predicate):
2883class SubqueryPredicate(Predicate):
2884    pass
class All(SubqueryPredicate):
2887class All(SubqueryPredicate):
2888    pass
class Any(SubqueryPredicate):
2891class Any(SubqueryPredicate):
2892    pass
class Exists(SubqueryPredicate):
2895class Exists(SubqueryPredicate):
2896    pass
class Command(Expression):
2901class Command(Expression):
2902    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
2905class Transaction(Expression):
2906    arg_types = {"this": False, "modes": False}
class Commit(Expression):
2909class Commit(Expression):
2910    arg_types = {"chain": False}
class Rollback(Expression):
2913class Rollback(Expression):
2914    arg_types = {"savepoint": False}
class AlterTable(Expression):
2917class AlterTable(Expression):
2918    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
2921class AddConstraint(Expression):
2922    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
2925class DropPartition(Expression):
2926    arg_types = {"expressions": True, "exists": False}
class Binary(Expression):
2930class Binary(Expression):
2931    arg_types = {"this": True, "expression": True}
2932
2933    @property
2934    def left(self):
2935        return self.this
2936
2937    @property
2938    def right(self):
2939        return self.expression
class Add(Binary):
2942class Add(Binary):
2943    pass
class Connector(Binary, Condition):
2946class Connector(Binary, Condition):
2947    pass
class And(Connector):
2950class And(Connector):
2951    pass
class Or(Connector):
2954class Or(Connector):
2955    pass
class BitwiseAnd(Binary):
2958class BitwiseAnd(Binary):
2959    pass
class BitwiseLeftShift(Binary):
2962class BitwiseLeftShift(Binary):
2963    pass
class BitwiseOr(Binary):
2966class BitwiseOr(Binary):
2967    pass
class BitwiseRightShift(Binary):
2970class BitwiseRightShift(Binary):
2971    pass
class BitwiseXor(Binary):
2974class BitwiseXor(Binary):
2975    pass
class Div(Binary):
2978class Div(Binary):
2979    pass
class Overlaps(Binary):
2982class Overlaps(Binary):
2983    pass
class Dot(Binary):
2986class Dot(Binary):
2987    @property
2988    def name(self) -> str:
2989        return self.expression.name
class DPipe(Binary):
2992class DPipe(Binary):
2993    pass
class EQ(Binary, Predicate):
2996class EQ(Binary, Predicate):
2997    pass
class NullSafeEQ(Binary, Predicate):
3000class NullSafeEQ(Binary, Predicate):
3001    pass
class NullSafeNEQ(Binary, Predicate):
3004class NullSafeNEQ(Binary, Predicate):
3005    pass
class Distance(Binary):
3008class Distance(Binary):
3009    pass
class Escape(Binary):
3012class Escape(Binary):
3013    pass
class Glob(Binary, Predicate):
3016class Glob(Binary, Predicate):
3017    pass
class GT(Binary, Predicate):
3020class GT(Binary, Predicate):
3021    pass
class GTE(Binary, Predicate):
3024class GTE(Binary, Predicate):
3025    pass
class ILike(Binary, Predicate):
3028class ILike(Binary, Predicate):
3029    pass
class ILikeAny(Binary, Predicate):
3032class ILikeAny(Binary, Predicate):
3033    pass
class IntDiv(Binary):
3036class IntDiv(Binary):
3037    pass
class Is(Binary, Predicate):
3040class Is(Binary, Predicate):
3041    pass
class Kwarg(Binary):
3044class Kwarg(Binary):
3045    """Kwarg in special functions like func(kwarg => y)."""

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

class Like(Binary, Predicate):
3048class Like(Binary, Predicate):
3049    pass
class LikeAny(Binary, Predicate):
3052class LikeAny(Binary, Predicate):
3053    pass
class LT(Binary, Predicate):
3056class LT(Binary, Predicate):
3057    pass
class LTE(Binary, Predicate):
3060class LTE(Binary, Predicate):
3061    pass
class Mod(Binary):
3064class Mod(Binary):
3065    pass
class Mul(Binary):
3068class Mul(Binary):
3069    pass
class NEQ(Binary, Predicate):
3072class NEQ(Binary, Predicate):
3073    pass
class SimilarTo(Binary, Predicate):
3076class SimilarTo(Binary, Predicate):
3077    pass
class Slice(Binary):
3080class Slice(Binary):
3081    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3084class Sub(Binary):
3085    pass
class ArrayOverlaps(Binary):
3088class ArrayOverlaps(Binary):
3089    pass
class Unary(Expression):
3094class Unary(Expression):
3095    pass
class BitwiseNot(Unary):
3098class BitwiseNot(Unary):
3099    pass
class Not(Unary, Condition):
3102class Not(Unary, Condition):
3103    pass
class Paren(Unary, Condition):
3106class Paren(Unary, Condition):
3107    arg_types = {"this": True, "with": False}
class Neg(Unary):
3110class Neg(Unary):
3111    pass
class Alias(Expression):
3115class Alias(Expression):
3116    arg_types = {"this": True, "alias": False}
3117
3118    @property
3119    def output_name(self):
3120        return self.alias
output_name

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Aliases(Expression):
3123class Aliases(Expression):
3124    arg_types = {"this": True, "expressions": True}
3125
3126    @property
3127    def aliases(self):
3128        return self.expressions
class AtTimeZone(Expression):
3131class AtTimeZone(Expression):
3132    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3135class Between(Predicate):
3136    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3139class Bracket(Condition):
3140    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3143class Distinct(Expression):
3144    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3147class In(Predicate):
3148    arg_types = {
3149        "this": True,
3150        "expressions": False,
3151        "query": False,
3152        "unnest": False,
3153        "field": False,
3154        "is_global": False,
3155    }
class TimeUnit(Expression):
3158class TimeUnit(Expression):
3159    """Automatically converts unit arg into a var."""
3160
3161    arg_types = {"unit": False}
3162
3163    def __init__(self, **args):
3164        unit = args.get("unit")
3165        if isinstance(unit, (Column, Literal)):
3166            args["unit"] = Var(this=unit.name)
3167        elif isinstance(unit, Week):
3168            unit.set("this", Var(this=unit.this.name))
3169        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3163    def __init__(self, **args):
3164        unit = args.get("unit")
3165        if isinstance(unit, (Column, Literal)):
3166            args["unit"] = Var(this=unit.name)
3167        elif isinstance(unit, Week):
3168            unit.set("this", Var(this=unit.this.name))
3169        super().__init__(**args)
class Interval(TimeUnit):
3172class Interval(TimeUnit):
3173    arg_types = {"this": False, "unit": False}
class IgnoreNulls(Expression):
3176class IgnoreNulls(Expression):
3177    pass
class RespectNulls(Expression):
3180class RespectNulls(Expression):
3181    pass
class Func(Condition):
3185class Func(Condition):
3186    """
3187    The base class for all function expressions.
3188
3189    Attributes:
3190        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3191            treated as a variable length argument and the argument's value will be stored as a list.
3192        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3193            for this function expression. These values are used to map this node to a name during parsing
3194            as well as to provide the function's name during SQL string generation. By default the SQL
3195            name is set to the expression's class name transformed to snake case.
3196    """
3197
3198    is_var_len_args = False
3199
3200    @classmethod
3201    def from_arg_list(cls, args):
3202        if cls.is_var_len_args:
3203            all_arg_keys = list(cls.arg_types)
3204            # If this function supports variable length argument treat the last argument as such.
3205            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3206            num_non_var = len(non_var_len_arg_keys)
3207
3208            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3209            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3210        else:
3211            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3212
3213        return cls(**args_dict)
3214
3215    @classmethod
3216    def sql_names(cls):
3217        if cls is Func:
3218            raise NotImplementedError(
3219                "SQL name is only supported by concrete function implementations"
3220            )
3221        if "_sql_names" not in cls.__dict__:
3222            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3223        return cls._sql_names
3224
3225    @classmethod
3226    def sql_name(cls):
3227        return cls.sql_names()[0]
3228
3229    @classmethod
3230    def default_parser_mappings(cls):
3231        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
@classmethod
def from_arg_list(cls, args):
3200    @classmethod
3201    def from_arg_list(cls, args):
3202        if cls.is_var_len_args:
3203            all_arg_keys = list(cls.arg_types)
3204            # If this function supports variable length argument treat the last argument as such.
3205            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3206            num_non_var = len(non_var_len_arg_keys)
3207
3208            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3209            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3210        else:
3211            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3212
3213        return cls(**args_dict)
@classmethod
def sql_names(cls):
3215    @classmethod
3216    def sql_names(cls):
3217        if cls is Func:
3218            raise NotImplementedError(
3219                "SQL name is only supported by concrete function implementations"
3220            )
3221        if "_sql_names" not in cls.__dict__:
3222            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3223        return cls._sql_names
@classmethod
def sql_name(cls):
3225    @classmethod
3226    def sql_name(cls):
3227        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3229    @classmethod
3230    def default_parser_mappings(cls):
3231        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3234class AggFunc(Func):
3235    pass
class Abs(Func):
3238class Abs(Func):
3239    pass
class Anonymous(Func):
3242class Anonymous(Func):
3243    arg_types = {"this": True, "expressions": False}
3244    is_var_len_args = True
class ApproxDistinct(AggFunc):
3247class ApproxDistinct(AggFunc):
3248    arg_types = {"this": True, "accuracy": False}
class Array(Func):
3251class Array(Func):
3252    arg_types = {"expressions": False}
3253    is_var_len_args = True
class ToChar(Func):
3257class ToChar(Func):
3258    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3261class GenerateSeries(Func):
3262    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3265class ArrayAgg(AggFunc):
3266    pass
class ArrayAll(Func):
3269class ArrayAll(Func):
3270    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3273class ArrayAny(Func):
3274    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3277class ArrayConcat(Func):
3278    arg_types = {"this": True, "expressions": False}
3279    is_var_len_args = True
class ArrayContains(Binary, Func):
3282class ArrayContains(Binary, Func):
3283    pass
class ArrayContained(Binary):
3286class ArrayContained(Binary):
3287    pass
class ArrayFilter(Func):
3290class ArrayFilter(Func):
3291    arg_types = {"this": True, "expression": True}
3292    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3295class ArrayJoin(Func):
3296    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3299class ArraySize(Func):
3300    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3303class ArraySort(Func):
3304    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3307class ArraySum(Func):
3308    pass
class ArrayUnionAgg(AggFunc):
3311class ArrayUnionAgg(AggFunc):
3312    pass
class Avg(AggFunc):
3315class Avg(AggFunc):
3316    pass
class AnyValue(AggFunc):
3319class AnyValue(AggFunc):
3320    pass
class Case(Func):
3323class Case(Func):
3324    arg_types = {"this": False, "ifs": True, "default": False}
class Cast(Func):
3327class Cast(Func):
3328    arg_types = {"this": True, "to": True}
3329
3330    @property
3331    def name(self) -> str:
3332        return self.this.name
3333
3334    @property
3335    def to(self):
3336        return self.args["to"]
3337
3338    @property
3339    def output_name(self):
3340        return self.name
3341
3342    def is_type(self, dtype: DataType.Type) -> bool:
3343        return self.to.is_type(dtype)
output_name

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

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

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3342    def is_type(self, dtype: DataType.Type) -> bool:
3343        return self.to.is_type(dtype)
class Collate(Binary):
3346class Collate(Binary):
3347    pass
class TryCast(Cast):
3350class TryCast(Cast):
3351    pass
class Ceil(Func):
3354class Ceil(Func):
3355    arg_types = {"this": True, "decimals": False}
3356    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3359class Coalesce(Func):
3360    arg_types = {"this": True, "expressions": False}
3361    is_var_len_args = True
class Concat(Func):
3364class Concat(Func):
3365    arg_types = {"expressions": True}
3366    is_var_len_args = True
class ConcatWs(Concat):
3369class ConcatWs(Concat):
3370    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3373class Count(AggFunc):
3374    arg_types = {"this": False}
class CountIf(AggFunc):
3377class CountIf(AggFunc):
3378    pass
class CurrentDate(Func):
3381class CurrentDate(Func):
3382    arg_types = {"this": False}
class CurrentDatetime(Func):
3385class CurrentDatetime(Func):
3386    arg_types = {"this": False}
class CurrentTime(Func):
3389class CurrentTime(Func):
3390    arg_types = {"this": False}
class CurrentTimestamp(Func):
3393class CurrentTimestamp(Func):
3394    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3397class DateAdd(Func, TimeUnit):
3398    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3401class DateSub(Func, TimeUnit):
3402    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3405class DateDiff(Func, TimeUnit):
3406    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3407    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3410class DateTrunc(Func):
3411    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3414class DatetimeAdd(Func, TimeUnit):
3415    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3418class DatetimeSub(Func, TimeUnit):
3419    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3422class DatetimeDiff(Func, TimeUnit):
3423    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3426class DatetimeTrunc(Func, TimeUnit):
3427    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3430class DayOfWeek(Func):
3431    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3434class DayOfMonth(Func):
3435    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3438class DayOfYear(Func):
3439    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3442class WeekOfYear(Func):
3443    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3446class LastDateOfMonth(Func):
3447    pass
class Extract(Func):
3450class Extract(Func):
3451    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3454class TimestampAdd(Func, TimeUnit):
3455    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3458class TimestampSub(Func, TimeUnit):
3459    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3462class TimestampDiff(Func, TimeUnit):
3463    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3466class TimestampTrunc(Func, TimeUnit):
3467    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3470class TimeAdd(Func, TimeUnit):
3471    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3474class TimeSub(Func, TimeUnit):
3475    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3478class TimeDiff(Func, TimeUnit):
3479    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3482class TimeTrunc(Func, TimeUnit):
3483    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3486class DateFromParts(Func):
3487    _sql_names = ["DATEFROMPARTS"]
3488    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3491class DateStrToDate(Func):
3492    pass
class DateToDateStr(Func):
3495class DateToDateStr(Func):
3496    pass
class DateToDi(Func):
3499class DateToDi(Func):
3500    pass
class Day(Func):
3503class Day(Func):
3504    pass
class Decode(Func):
3507class Decode(Func):
3508    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3511class DiToDate(Func):
3512    pass
class Encode(Func):
3515class Encode(Func):
3516    arg_types = {"this": True, "charset": True}
class Exp(Func):
3519class Exp(Func):
3520    pass
class Explode(Func):
3523class Explode(Func):
3524    pass
class Floor(Func):
3527class Floor(Func):
3528    arg_types = {"this": True, "decimals": False}
class Greatest(Func):
3531class Greatest(Func):
3532    arg_types = {"this": True, "expressions": False}
3533    is_var_len_args = True
class GroupConcat(Func):
3536class GroupConcat(Func):
3537    arg_types = {"this": True, "separator": False}
class Hex(Func):
3540class Hex(Func):
3541    pass
class If(Func):
3544class If(Func):
3545    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3548class IfNull(Func):
3549    arg_types = {"this": True, "expression": False}
3550    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3553class Initcap(Func):
3554    pass
class JSONBContains(Binary):
3557class JSONBContains(Binary):
3558    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3561class JSONExtract(Binary, Func):
3562    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3565class JSONExtractScalar(JSONExtract):
3566    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3569class JSONBExtract(JSONExtract):
3570    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3573class JSONBExtractScalar(JSONExtract):
3574    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class Least(Func):
3577class Least(Func):
3578    arg_types = {"expressions": False}
3579    is_var_len_args = True
class Length(Func):
3582class Length(Func):
3583    pass
class Levenshtein(Func):
3586class Levenshtein(Func):
3587    arg_types = {
3588        "this": True,
3589        "expression": False,
3590        "ins_cost": False,
3591        "del_cost": False,
3592        "sub_cost": False,
3593    }
class Ln(Func):
3596class Ln(Func):
3597    pass
class Log(Func):
3600class Log(Func):
3601    arg_types = {"this": True, "expression": False}
class Log2(Func):
3604class Log2(Func):
3605    pass
class Log10(Func):
3608class Log10(Func):
3609    pass
class LogicalOr(AggFunc):
3612class LogicalOr(AggFunc):
3613    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
3616class LogicalAnd(AggFunc):
3617    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
3620class Lower(Func):
3621    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
3624class Map(Func):
3625    arg_types = {"keys": False, "values": False}
class VarMap(Func):
3628class VarMap(Func):
3629    arg_types = {"keys": True, "values": True}
3630    is_var_len_args = True
class Matches(Func):
3633class Matches(Func):
3634    """Oracle/Snowflake decode.
3635    https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm
3636    Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else)
3637    """
3638
3639    arg_types = {"this": True, "expressions": True}
3640    is_var_len_args = True

Oracle/Snowflake decode. https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions040.htm Pattern matching MATCHES(value, search1, result1, ...searchN, resultN, else)

class Max(AggFunc):
3643class Max(AggFunc):
3644    arg_types = {"this": True, "expressions": False}
3645    is_var_len_args = True
class Min(AggFunc):
3648class Min(AggFunc):
3649    arg_types = {"this": True, "expressions": False}
3650    is_var_len_args = True
class Month(Func):
3653class Month(Func):
3654    pass
class Nvl2(Func):
3657class Nvl2(Func):
3658    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
3661class Posexplode(Func):
3662    pass
class Pow(Binary, Func):
3665class Pow(Binary, Func):
3666    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
3669class PercentileCont(AggFunc):
3670    pass
class PercentileDisc(AggFunc):
3673class PercentileDisc(AggFunc):
3674    pass
class Quantile(AggFunc):
3677class Quantile(AggFunc):
3678    arg_types = {"this": True, "quantile": True}
class Quantiles(AggFunc):
3683class Quantiles(AggFunc):
3684    arg_types = {"parameters": True, "expressions": True}
3685    is_var_len_args = True
class QuantileIf(AggFunc):
3688class QuantileIf(AggFunc):
3689    arg_types = {"parameters": True, "expressions": True}
class ApproxQuantile(Quantile):
3692class ApproxQuantile(Quantile):
3693    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
3696class RangeN(Func):
3697    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
3700class ReadCSV(Func):
3701    _sql_names = ["READ_CSV"]
3702    is_var_len_args = True
3703    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
3706class Reduce(Func):
3707    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
3710class RegexpExtract(Func):
3711    arg_types = {
3712        "this": True,
3713        "expression": True,
3714        "position": False,
3715        "occurrence": False,
3716        "group": False,
3717    }
class RegexpLike(Func):
3720class RegexpLike(Func):
3721    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
3724class RegexpILike(Func):
3725    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
3728class RegexpSplit(Func):
3729    arg_types = {"this": True, "expression": True}
class Repeat(Func):
3732class Repeat(Func):
3733    arg_types = {"this": True, "times": True}
class Round(Func):
3736class Round(Func):
3737    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
3740class RowNumber(Func):
3741    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
3744class SafeDivide(Func):
3745    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
3748class SetAgg(AggFunc):
3749    pass
class SortArray(Func):
3752class SortArray(Func):
3753    arg_types = {"this": True, "asc": False}
class Split(Func):
3756class Split(Func):
3757    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
3762class Substring(Func):
3763    arg_types = {"this": True, "start": False, "length": False}
class StrPosition(Func):
3766class StrPosition(Func):
3767    arg_types = {
3768        "this": True,
3769        "substr": True,
3770        "position": False,
3771        "instance": False,
3772    }
class StrToDate(Func):
3775class StrToDate(Func):
3776    arg_types = {"this": True, "format": True}
class StrToTime(Func):
3779class StrToTime(Func):
3780    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
3785class StrToUnix(Func):
3786    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
3789class NumberToStr(Func):
3790    arg_types = {"this": True, "format": True}
class Struct(Func):
3793class Struct(Func):
3794    arg_types = {"expressions": True}
3795    is_var_len_args = True
class StructExtract(Func):
3798class StructExtract(Func):
3799    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
3802class Sum(AggFunc):
3803    pass
class Sqrt(Func):
3806class Sqrt(Func):
3807    pass
class Stddev(AggFunc):
3810class Stddev(AggFunc):
3811    pass
class StddevPop(AggFunc):
3814class StddevPop(AggFunc):
3815    pass
class StddevSamp(AggFunc):
3818class StddevSamp(AggFunc):
3819    pass
class TimeToStr(Func):
3822class TimeToStr(Func):
3823    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
3826class TimeToTimeStr(Func):
3827    pass
class TimeToUnix(Func):
3830class TimeToUnix(Func):
3831    pass
class TimeStrToDate(Func):
3834class TimeStrToDate(Func):
3835    pass
class TimeStrToTime(Func):
3838class TimeStrToTime(Func):
3839    pass
class TimeStrToUnix(Func):
3842class TimeStrToUnix(Func):
3843    pass
class Trim(Func):
3846class Trim(Func):
3847    arg_types = {
3848        "this": True,
3849        "expression": False,
3850        "position": False,
3851        "collation": False,
3852    }
class TsOrDsAdd(Func, TimeUnit):
3855class TsOrDsAdd(Func, TimeUnit):
3856    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
3859class TsOrDsToDateStr(Func):
3860    pass
class TsOrDsToDate(Func):
3863class TsOrDsToDate(Func):
3864    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
3867class TsOrDiToDi(Func):
3868    pass
class Unhex(Func):
3871class Unhex(Func):
3872    pass
class UnixToStr(Func):
3875class UnixToStr(Func):
3876    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
3881class UnixToTime(Func):
3882    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
3883
3884    SECONDS = Literal.string("seconds")
3885    MILLIS = Literal.string("millis")
3886    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
3889class UnixToTimeStr(Func):
3890    pass
class Upper(Func):
3893class Upper(Func):
3894    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
3897class Variance(AggFunc):
3898    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
3901class VariancePop(AggFunc):
3902    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
3905class Week(Func):
3906    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
3909class XMLTable(Func):
3910    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
3913class Year(Func):
3914    pass
class Use(Expression):
3917class Use(Expression):
3918    arg_types = {"this": True, "kind": False}
class Merge(Expression):
3921class Merge(Expression):
3922    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
3925class When(Func):
3926    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
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:
3954def maybe_parse(
3955    sql_or_expression: ExpOrStr,
3956    *,
3957    into: t.Optional[IntoType] = None,
3958    dialect: DialectType = None,
3959    prefix: t.Optional[str] = None,
3960    copy: bool = False,
3961    **opts,
3962) -> Expression:
3963    """Gracefully handle a possible string or expression.
3964
3965    Example:
3966        >>> maybe_parse("1")
3967        (LITERAL this: 1, is_string: False)
3968        >>> maybe_parse(to_identifier("x"))
3969        (IDENTIFIER this: x, quoted: False)
3970
3971    Args:
3972        sql_or_expression: the SQL code string or an expression
3973        into: the SQLGlot Expression to parse into
3974        dialect: the dialect used to parse the input expressions (in the case that an
3975            input expression is a SQL string).
3976        prefix: a string to prefix the sql with before it gets parsed
3977            (automatically includes a space)
3978        copy: whether or not to copy the expression.
3979        **opts: other options to use to parse the input expressions (again, in the case
3980            that an input expression is a SQL string).
3981
3982    Returns:
3983        Expression: the parsed or given expression.
3984    """
3985    if isinstance(sql_or_expression, Expression):
3986        if copy:
3987            return sql_or_expression.copy()
3988        return sql_or_expression
3989
3990    import sqlglot
3991
3992    sql = str(sql_or_expression)
3993    if prefix:
3994        sql = f"{prefix} {sql}"
3995    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

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

Expression: the parsed or given expression.

def union(left, right, distinct=True, dialect=None, **opts):
4141def union(left, right, distinct=True, dialect=None, **opts):
4142    """
4143    Initializes a syntax tree from one UNION expression.
4144
4145    Example:
4146        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4147        'SELECT * FROM foo UNION SELECT * FROM bla'
4148
4149    Args:
4150        left (str | Expression): the SQL code string corresponding to the left-hand side.
4151            If an `Expression` instance is passed, it will be used as-is.
4152        right (str | Expression): the SQL code string corresponding to the right-hand side.
4153            If an `Expression` instance is passed, it will be used as-is.
4154        distinct (bool): set the DISTINCT flag if and only if this is true.
4155        dialect (str): the dialect used to parse the input expression.
4156        opts (kwargs): other options to use to parse the input expressions.
4157    Returns:
4158        Union: the syntax tree for the UNION expression.
4159    """
4160    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4161    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4162
4163    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

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

Union: the syntax tree for the UNION expression.

def intersect(left, right, distinct=True, dialect=None, **opts):
4166def intersect(left, right, distinct=True, dialect=None, **opts):
4167    """
4168    Initializes a syntax tree from one INTERSECT expression.
4169
4170    Example:
4171        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4172        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4173
4174    Args:
4175        left (str | Expression): the SQL code string corresponding to the left-hand side.
4176            If an `Expression` instance is passed, it will be used as-is.
4177        right (str | Expression): the SQL code string corresponding to the right-hand side.
4178            If an `Expression` instance is passed, it will be used as-is.
4179        distinct (bool): set the DISTINCT flag if and only if this is true.
4180        dialect (str): the dialect used to parse the input expression.
4181        opts (kwargs): other options to use to parse the input expressions.
4182    Returns:
4183        Intersect: the syntax tree for the INTERSECT expression.
4184    """
4185    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4186    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4187
4188    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

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

Intersect: the syntax tree for the INTERSECT expression.

def except_(left, right, distinct=True, dialect=None, **opts):
4191def except_(left, right, distinct=True, dialect=None, **opts):
4192    """
4193    Initializes a syntax tree from one EXCEPT expression.
4194
4195    Example:
4196        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4197        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4198
4199    Args:
4200        left (str | Expression): the SQL code string corresponding to the left-hand side.
4201            If an `Expression` instance is passed, it will be used as-is.
4202        right (str | Expression): the SQL code string corresponding to the right-hand side.
4203            If an `Expression` instance is passed, it will be used as-is.
4204        distinct (bool): set the DISTINCT flag if and only if this is true.
4205        dialect (str): the dialect used to parse the input expression.
4206        opts (kwargs): other options to use to parse the input expressions.
4207    Returns:
4208        Except: the syntax tree for the EXCEPT statement.
4209    """
4210    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4211    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4212
4213    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

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

Except: the syntax tree for the EXCEPT statement.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4216def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4217    """
4218    Initializes a syntax tree from one or multiple SELECT expressions.
4219
4220    Example:
4221        >>> select("col1", "col2").from_("tbl").sql()
4222        'SELECT col1, col2 FROM tbl'
4223
4224    Args:
4225        *expressions: the SQL code string to parse as the expressions of a
4226            SELECT statement. If an Expression instance is passed, this is used as-is.
4227        dialect: the dialect used to parse the input expressions (in the case that an
4228            input expression is a SQL string).
4229        **opts: other options to use to parse the input expressions (again, in the case
4230            that an input expression is a SQL string).
4231
4232    Returns:
4233        Select: the syntax tree for the SELECT statement.
4234    """
4235    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_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Select:
4238def from_(*expressions, dialect=None, **opts) -> Select:
4239    """
4240    Initializes a syntax tree from a FROM expression.
4241
4242    Example:
4243        >>> from_("tbl").select("col1", "col2").sql()
4244        'SELECT col1, col2 FROM tbl'
4245
4246    Args:
4247        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4248            SELECT statement. If an Expression instance is passed, this is used as-is.
4249        dialect (str): the dialect used to parse the input expression (in the case that the
4250            input expression is a SQL string).
4251        **opts: other options to use to parse the input expressions (again, in the case
4252            that the input expression is a SQL string).
4253
4254    Returns:
4255        Select: the syntax tree for the SELECT statement.
4256    """
4257    return Select().from_(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions (str | 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 (str): 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:
4260def update(
4261    table: str | Table,
4262    properties: dict,
4263    where: t.Optional[ExpOrStr] = None,
4264    from_: t.Optional[ExpOrStr] = None,
4265    dialect: DialectType = None,
4266    **opts,
4267) -> Update:
4268    """
4269    Creates an update statement.
4270
4271    Example:
4272        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4273        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4274
4275    Args:
4276        *properties: dictionary of properties to set which are
4277            auto converted to sql objects eg None -> NULL
4278        where: sql conditional parsed into a WHERE statement
4279        from_: sql statement parsed into a FROM statement
4280        dialect: the dialect used to parse the input expressions.
4281        **opts: other options to use to parse the input expressions.
4282
4283    Returns:
4284        Update: the syntax tree for the UPDATE statement.
4285    """
4286    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4287    update_expr.set(
4288        "expressions",
4289        [
4290            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4291            for k, v in properties.items()
4292        ],
4293    )
4294    if from_:
4295        update_expr.set(
4296            "from",
4297            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4298        )
4299    if isinstance(where, Condition):
4300        where = Where(this=where)
4301    if where:
4302        update_expr.set(
4303            "where",
4304            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4305        )
4306    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:
4309def delete(
4310    table: ExpOrStr,
4311    where: t.Optional[ExpOrStr] = None,
4312    returning: t.Optional[ExpOrStr] = None,
4313    dialect: DialectType = None,
4314    **opts,
4315) -> Delete:
4316    """
4317    Builds a delete statement.
4318
4319    Example:
4320        >>> delete("my_table", where="id > 1").sql()
4321        'DELETE FROM my_table WHERE id > 1'
4322
4323    Args:
4324        where: sql conditional parsed into a WHERE statement
4325        returning: sql conditional parsed into a RETURNING statement
4326        dialect: the dialect used to parse the input expressions.
4327        **opts: other options to use to parse the input expressions.
4328
4329    Returns:
4330        Delete: the syntax tree for the DELETE statement.
4331    """
4332    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4333    if where:
4334        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4335    if returning:
4336        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4337    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 condition(expression, dialect=None, **opts) -> sqlglot.expressions.Condition:
4340def condition(expression, dialect=None, **opts) -> Condition:
4341    """
4342    Initialize a logical condition expression.
4343
4344    Example:
4345        >>> condition("x=1").sql()
4346        'x = 1'
4347
4348        This is helpful for composing larger logical syntax trees:
4349        >>> where = condition("x=1")
4350        >>> where = where.and_("y=1")
4351        >>> Select().from_("tbl").select("*").where(where).sql()
4352        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4353
4354    Args:
4355        *expression (str | Expression): the SQL code string to parse.
4356            If an Expression instance is passed, this is used as-is.
4357        dialect (str): the dialect used to parse the input expression (in the case that the
4358            input expression is a SQL string).
4359        **opts: other options to use to parse the input expressions (again, in the case
4360            that the input expression is a SQL string).
4361
4362    Returns:
4363        Condition: the expression
4364    """
4365    return maybe_parse(  # type: ignore
4366        expression,
4367        into=Condition,
4368        dialect=dialect,
4369        **opts,
4370    )

Initialize a logical condition expression.

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

This is helpful for composing larger logical syntax trees:

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

Condition: the expression

def and_(*expressions, dialect=None, **opts) -> sqlglot.expressions.And:
4373def and_(*expressions, dialect=None, **opts) -> And:
4374    """
4375    Combine multiple conditions with an AND logical operator.
4376
4377    Example:
4378        >>> and_("x=1", and_("y=1", "z=1")).sql()
4379        'x = 1 AND (y = 1 AND z = 1)'
4380
4381    Args:
4382        *expressions (str | Expression): the SQL code strings to parse.
4383            If an Expression instance is passed, this is used as-is.
4384        dialect (str): the dialect used to parse the input expression.
4385        **opts: other options to use to parse the input expressions.
4386
4387    Returns:
4388        And: the new condition
4389    """
4390    return _combine(expressions, And, dialect, **opts)

Combine multiple conditions with an AND logical operator.

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

And: the new condition

def or_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Or:
4393def or_(*expressions, dialect=None, **opts) -> Or:
4394    """
4395    Combine multiple conditions with an OR logical operator.
4396
4397    Example:
4398        >>> or_("x=1", or_("y=1", "z=1")).sql()
4399        'x = 1 OR (y = 1 OR z = 1)'
4400
4401    Args:
4402        *expressions (str | Expression): the SQL code strings to parse.
4403            If an Expression instance is passed, this is used as-is.
4404        dialect (str): the dialect used to parse the input expression.
4405        **opts: other options to use to parse the input expressions.
4406
4407    Returns:
4408        Or: the new condition
4409    """
4410    return _combine(expressions, Or, dialect, **opts)

Combine multiple conditions with an OR logical operator.

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

Or: the new condition

def not_(expression, dialect=None, **opts) -> sqlglot.expressions.Not:
4413def not_(expression, dialect=None, **opts) -> Not:
4414    """
4415    Wrap a condition with a NOT operator.
4416
4417    Example:
4418        >>> not_("this_suit='black'").sql()
4419        "NOT this_suit = 'black'"
4420
4421    Args:
4422        expression (str | Expression): the SQL code strings to parse.
4423            If an Expression instance is passed, this is used as-is.
4424        dialect (str): the dialect used to parse the input expression.
4425        **opts: other options to use to parse the input expressions.
4426
4427    Returns:
4428        Not: the new condition
4429    """
4430    this = condition(
4431        expression,
4432        dialect=dialect,
4433        **opts,
4434    )
4435    return Not(this=_wrap_operator(this))

Wrap a condition with a NOT operator.

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

Not: the new condition

def paren(expression) -> sqlglot.expressions.Paren:
4438def paren(expression) -> Paren:
4439    return Paren(this=expression)
def to_identifier(name, quoted=None):
4455def to_identifier(name, quoted=None):
4456    """Builds an identifier.
4457
4458    Args:
4459        name: The name to turn into an identifier.
4460        quoted: Whether or not force quote the identifier.
4461
4462    Returns:
4463        The identifier ast node.
4464    """
4465
4466    if name is None:
4467        return None
4468
4469    if isinstance(name, Identifier):
4470        identifier = name
4471    elif isinstance(name, str):
4472        identifier = Identifier(
4473            this=name,
4474            quoted=not re.match(SAFE_IDENTIFIER_RE, name) if quoted is None else quoted,
4475        )
4476    else:
4477        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4478    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
Returns:

The identifier ast node.

def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
4484def to_interval(interval: str | Literal) -> Interval:
4485    """Builds an interval expression from a string like '1 day' or '5 months'."""
4486    if isinstance(interval, Literal):
4487        if not interval.is_string:
4488            raise ValueError("Invalid interval string.")
4489
4490        interval = interval.this
4491
4492    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4493
4494    if not interval_parts:
4495        raise ValueError("Invalid interval string.")
4496
4497    return Interval(
4498        this=Literal.string(interval_parts.group(1)),
4499        unit=Var(this=interval_parts.group(2)),
4500    )

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

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], **kwargs) -> Optional[sqlglot.expressions.Table]:
4513def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4514    """
4515    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4516    If a table is passed in then that table is returned.
4517
4518    Args:
4519        sql_path: a `[catalog].[schema].[table]` string.
4520
4521    Returns:
4522        A table expression.
4523    """
4524    if sql_path is None or isinstance(sql_path, Table):
4525        return sql_path
4526    if not isinstance(sql_path, str):
4527        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4528
4529    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4530    return Table(this=table_name, db=db, catalog=catalog, **kwargs)

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

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
4533def to_column(sql_path: str | Column, **kwargs) -> Column:
4534    """
4535    Create a column from a `[table].[column]` sql path. Schema is optional.
4536
4537    If a column is passed in then that column is returned.
4538
4539    Args:
4540        sql_path: `[table].[column]` string
4541    Returns:
4542        Table: A column expression
4543    """
4544    if sql_path is None or isinstance(sql_path, Column):
4545        return sql_path
4546    if not isinstance(sql_path, str):
4547        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4548    table_name, column_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 2))
4549    return Column(this=column_name, table=table_name, **kwargs)

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, **opts):
4552def alias_(
4553    expression: ExpOrStr,
4554    alias: str | Identifier,
4555    table: bool | t.Sequence[str | Identifier] = False,
4556    quoted: t.Optional[bool] = None,
4557    dialect: DialectType = None,
4558    **opts,
4559):
4560    """Create an Alias expression.
4561
4562    Example:
4563        >>> alias_('foo', 'bar').sql()
4564        'foo AS bar'
4565
4566        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4567        '(SELECT 1, 2) AS bar(a, b)'
4568
4569    Args:
4570        expression: the SQL code strings to parse.
4571            If an Expression instance is passed, this is used as-is.
4572        alias: the alias name to use. If the name has
4573            special characters it is quoted.
4574        table: Whether or not to create a table alias, can also be a list of columns.
4575        quoted: whether or not to quote the alias
4576        dialect: the dialect used to parse the input expression.
4577        **opts: other options to use to parse the input expressions.
4578
4579    Returns:
4580        Alias: the aliased expression
4581    """
4582    exp = maybe_parse(expression, dialect=dialect, **opts)
4583    alias = to_identifier(alias, quoted=quoted)
4584
4585    if table:
4586        table_alias = TableAlias(this=alias)
4587        exp.set("alias", table_alias)
4588
4589        if not isinstance(table, bool):
4590            for column in table:
4591                table_alias.append("columns", to_identifier(column, quoted=quoted))
4592
4593        return exp
4594
4595    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4596    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4597    # for the complete Window expression.
4598    #
4599    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4600
4601    if "alias" in exp.arg_types and not isinstance(exp, Window):
4602        exp = exp.copy()
4603        exp.set("alias", alias)
4604        return exp
4605    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.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery(expression, alias=None, dialect=None, **opts):
4608def subquery(expression, alias=None, dialect=None, **opts):
4609    """
4610    Build a subquery expression.
4611
4612    Example:
4613        >>> subquery('select x from tbl', 'bar').select('x').sql()
4614        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4615
4616    Args:
4617        expression (str | Expression): the SQL code strings to parse.
4618            If an Expression instance is passed, this is used as-is.
4619        alias (str | Expression): the alias name to use.
4620        dialect (str): the dialect used to parse the input expression.
4621        **opts: other options to use to parse the input expressions.
4622
4623    Returns:
4624        Select: a new select with the subquery expression included
4625    """
4626
4627    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4628    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

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

Select: a new select with the subquery expression included

def column( col: str | sqlglot.expressions.Identifier, table: Union[str, sqlglot.expressions.Identifier, NoneType] = None, schema: Union[str, sqlglot.expressions.Identifier, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
4631def column(
4632    col: str | Identifier,
4633    table: t.Optional[str | Identifier] = None,
4634    schema: t.Optional[str | Identifier] = None,
4635    quoted: t.Optional[bool] = None,
4636) -> Column:
4637    """
4638    Build a Column.
4639
4640    Args:
4641        col: column name
4642        table: table name
4643        schema: schema name
4644        quoted: whether or not to force quote each part
4645    Returns:
4646        Column: column instance
4647    """
4648    return Column(
4649        this=to_identifier(col, quoted=quoted),
4650        table=to_identifier(table, quoted=quoted),
4651        schema=to_identifier(schema, quoted=quoted),
4652    )

Build a Column.

Arguments:
  • col: column name
  • table: table name
  • schema: schema name
  • quoted: whether or not to force quote each part
Returns:

Column: column instance

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
4655def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4656    """Cast an expression to a data type.
4657
4658    Example:
4659        >>> cast('x + 1', 'int').sql()
4660        'CAST(x + 1 AS INT)'
4661
4662    Args:
4663        expression: The expression to cast.
4664        to: The datatype to cast to.
4665
4666    Returns:
4667        A cast node.
4668    """
4669    expression = maybe_parse(expression, **opts)
4670    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

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

A cast node.

def table_( table, db=None, catalog=None, quoted=None, alias=None) -> sqlglot.expressions.Table:
4673def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4674    """Build a Table.
4675
4676    Args:
4677        table (str | Expression): column name
4678        db (str | Expression): db name
4679        catalog (str | Expression): catalog name
4680
4681    Returns:
4682        Table: table instance
4683    """
4684    return Table(
4685        this=to_identifier(table, quoted=quoted),
4686        db=to_identifier(db, quoted=quoted),
4687        catalog=to_identifier(catalog, quoted=quoted),
4688        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4689    )

Build a Table.

Arguments:
  • table (str | Expression): column name
  • db (str | Expression): db name
  • catalog (str | Expression): catalog name
Returns:

Table: table instance

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
4692def values(
4693    values: t.Iterable[t.Tuple[t.Any, ...]],
4694    alias: t.Optional[str] = None,
4695    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4696) -> Values:
4697    """Build VALUES statement.
4698
4699    Example:
4700        >>> values([(1, '2')]).sql()
4701        "VALUES (1, '2')"
4702
4703    Args:
4704        values: values statements that will be converted to SQL
4705        alias: optional alias
4706        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4707         If either are provided then an alias is also required.
4708         If a dictionary is provided then the first column of the values will be casted to the expected type
4709         in order to help with type inference.
4710
4711    Returns:
4712        Values: the Values expression object
4713    """
4714    if columns and not alias:
4715        raise ValueError("Alias is required when providing columns")
4716    table_alias = (
4717        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4718        if columns
4719        else TableAlias(this=to_identifier(alias) if alias else None)
4720    )
4721    expressions = [convert(tup) for tup in values]
4722    if columns and isinstance(columns, dict):
4723        types = list(columns.values())
4724        expressions[0].set(
4725            "expressions",
4726            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4727        )
4728    return Values(
4729        expressions=expressions,
4730        alias=table_alias,
4731    )

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. If a dictionary is provided then the first column of the values will be casted to the expected type in order to help with type inference.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
4734def var(name: t.Optional[ExpOrStr]) -> Var:
4735    """Build a SQL variable.
4736
4737    Example:
4738        >>> repr(var('x'))
4739        '(VAR this: x)'
4740
4741        >>> repr(var(column('x', table='y')))
4742        '(VAR this: x)'
4743
4744    Args:
4745        name: The name of the var or an expression who's name will become the var.
4746
4747    Returns:
4748        The new variable node.
4749    """
4750    if not name:
4751        raise ValueError("Cannot convert empty name into var.")
4752
4753    if isinstance(name, Expression):
4754        name = name.name
4755    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:
4758def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4759    """Build ALTER TABLE... RENAME... expression
4760
4761    Args:
4762        old_name: The old name of the table
4763        new_name: The new name of the table
4764
4765    Returns:
4766        Alter table expression
4767    """
4768    old_table = to_table(old_name)
4769    new_table = to_table(new_name)
4770    return AlterTable(
4771        this=old_table,
4772        actions=[
4773            RenameTable(this=new_table),
4774        ],
4775    )

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) -> sqlglot.expressions.Expression:
4778def convert(value) -> Expression:
4779    """Convert a python value into an expression object.
4780
4781    Raises an error if a conversion is not possible.
4782
4783    Args:
4784        value (Any): a python object
4785
4786    Returns:
4787        Expression: the equivalent expression object
4788    """
4789    if isinstance(value, Expression):
4790        return value
4791    if value is None:
4792        return NULL
4793    if isinstance(value, bool):
4794        return Boolean(this=value)
4795    if isinstance(value, str):
4796        return Literal.string(value)
4797    if isinstance(value, float) and math.isnan(value):
4798        return NULL
4799    if isinstance(value, numbers.Number):
4800        return Literal.number(value)
4801    if isinstance(value, tuple):
4802        return Tuple(expressions=[convert(v) for v in value])
4803    if isinstance(value, list):
4804        return Array(expressions=[convert(v) for v in value])
4805    if isinstance(value, dict):
4806        return Map(
4807            keys=[convert(k) for k in value],
4808            values=[convert(v) for v in value.values()],
4809        )
4810    if isinstance(value, datetime.datetime):
4811        datetime_literal = Literal.string(
4812            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4813        )
4814        return TimeStrToTime(this=datetime_literal)
4815    if isinstance(value, datetime.date):
4816        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4817        return DateStrToDate(this=date_literal)
4818    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 (Any): a python object
Returns:

Expression: the equivalent expression object

def replace_children(expression, fun, *args, **kwargs):
4821def replace_children(expression, fun, *args, **kwargs):
4822    """
4823    Replace children of an expression with the result of a lambda fun(child) -> exp.
4824    """
4825    for k, v in expression.args.items():
4826        is_list_arg = isinstance(v, list)
4827
4828        child_nodes = v if is_list_arg else [v]
4829        new_child_nodes = []
4830
4831        for cn in child_nodes:
4832            if isinstance(cn, Expression):
4833                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4834                    new_child_nodes.append(child_node)
4835                    child_node.parent = expression
4836                    child_node.arg_key = k
4837            else:
4838                new_child_nodes.append(cn)
4839
4840        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):
4843def column_table_names(expression):
4844    """
4845    Return all table names referenced through columns in an expression.
4846
4847    Example:
4848        >>> import sqlglot
4849        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4850        ['c', 'a']
4851
4852    Args:
4853        expression (sqlglot.Expression): expression to find table names
4854
4855    Returns:
4856        list: A list of unique names
4857    """
4858    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))

Return all table names referenced through columns in an expression.

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

list: A list of unique names

def table_name(table) -> str:
4861def table_name(table) -> str:
4862    """Get the full name of a table as a string.
4863
4864    Args:
4865        table (exp.Table | str): table expression node or string.
4866
4867    Examples:
4868        >>> from sqlglot import exp, parse_one
4869        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
4870        'a.b.c'
4871
4872    Returns:
4873        The table name.
4874    """
4875
4876    table = maybe_parse(table, into=Table)
4877
4878    if not table:
4879        raise ValueError(f"Cannot parse {table}")
4880
4881    return ".".join(
4882        part
4883        for part in (
4884            table.text("catalog"),
4885            table.text("db"),
4886            table.name,
4887        )
4888        if part
4889    )

Get the full name of a table as a string.

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

The table name.

def replace_tables(expression, mapping):
4892def replace_tables(expression, mapping):
4893    """Replace all tables in expression according to the mapping.
4894
4895    Args:
4896        expression (sqlglot.Expression): expression node to be transformed and replaced.
4897        mapping (Dict[str, str]): mapping of table names.
4898
4899    Examples:
4900        >>> from sqlglot import exp, parse_one
4901        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
4902        'SELECT * FROM c'
4903
4904    Returns:
4905        The mapped expression.
4906    """
4907
4908    def _replace_tables(node):
4909        if isinstance(node, Table):
4910            new_name = mapping.get(table_name(node))
4911            if new_name:
4912                return to_table(
4913                    new_name,
4914                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
4915                )
4916        return node
4917
4918    return expression.transform(_replace_tables)

Replace all tables in expression according to the mapping.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders(expression, *args, **kwargs):
4921def replace_placeholders(expression, *args, **kwargs):
4922    """Replace placeholders in an expression.
4923
4924    Args:
4925        expression (sqlglot.Expression): expression node to be transformed and replaced.
4926        args: positional names that will substitute unnamed placeholders in the given order.
4927        kwargs: keyword arguments that will substitute named placeholders.
4928
4929    Examples:
4930        >>> from sqlglot import exp, parse_one
4931        >>> replace_placeholders(
4932        ...     parse_one("select * from :tbl where ? = ?"), "a", "b", tbl="foo"
4933        ... ).sql()
4934        'SELECT * FROM foo WHERE a = b'
4935
4936    Returns:
4937        The mapped expression.
4938    """
4939
4940    def _replace_placeholders(node, args, **kwargs):
4941        if isinstance(node, Placeholder):
4942            if node.name:
4943                new_name = kwargs.get(node.name)
4944                if new_name:
4945                    return to_identifier(new_name)
4946            else:
4947                try:
4948                    return to_identifier(next(args))
4949                except StopIteration:
4950                    pass
4951        return node
4952
4953    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

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

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy=True) -> sqlglot.expressions.Expression:
4956def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression:
4957    """Transforms an expression by expanding all referenced sources into subqueries.
4958
4959    Examples:
4960        >>> from sqlglot import parse_one
4961        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
4962        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
4963
4964    Args:
4965        expression: The expression to expand.
4966        sources: A dictionary of name to Subqueryables.
4967        copy: Whether or not to copy the expression during transformation. Defaults to True.
4968
4969    Returns:
4970        The transformed expression.
4971    """
4972
4973    def _expand(node: Expression):
4974        if isinstance(node, Table):
4975            name = table_name(node)
4976            source = sources.get(name)
4977            if source:
4978                subquery = source.subquery(node.alias or name)
4979                subquery.comments = [f"source: {name}"]
4980                return subquery
4981        return node
4982
4983    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 */'
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:
4986def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
4987    """
4988    Returns a Func expression.
4989
4990    Examples:
4991        >>> func("abs", 5).sql()
4992        'ABS(5)'
4993
4994        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
4995        'CAST(5 AS DOUBLE)'
4996
4997    Args:
4998        name: the name of the function to build.
4999        args: the args used to instantiate the function of interest.
5000        dialect: the source dialect.
5001        kwargs: the kwargs used to instantiate the function of interest.
5002
5003    Note:
5004        The arguments `args` and `kwargs` are mutually exclusive.
5005
5006    Returns:
5007        An instance of the function of interest, or an anonymous function, if `name` doesn't
5008        correspond to an existing `sqlglot.expressions.Func` class.
5009    """
5010    if args and kwargs:
5011        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5012
5013    from sqlglot.dialects.dialect import Dialect
5014
5015    converted = [convert(arg) for arg in args]
5016    kwargs = {key: convert(value) for key, value in kwargs.items()}
5017
5018    parser = Dialect.get_or_raise(dialect)().parser()
5019    from_args_list = parser.FUNCTIONS.get(name.upper())
5020
5021    if from_args_list:
5022        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5023    else:
5024        kwargs = kwargs or {"expressions": converted}
5025        function = Anonymous(this=name, **kwargs)
5026
5027    for error_message in function.error_messages(converted):
5028        raise ValueError(error_message)
5029
5030    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():
5033def true():
5034    """
5035    Returns a true Boolean expression.
5036    """
5037    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5040def false():
5041    """
5042    Returns a false Boolean expression.
5043    """
5044    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5047def null():
5048    """
5049    Returns a Null expression.
5050    """
5051    return Null()

Returns a Null expression.