Edit on GitHub

Expressions

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

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


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

Returns a deep copy of the expression.

def append(self, arg_key, value):
262    def append(self, arg_key, value):
263        """
264        Appends value to arg_key if it's a list or sets it as a new list.
265
266        Args:
267            arg_key (str): name of the list expression arg
268            value (Any): value to append to the list
269        """
270        if not isinstance(self.args.get(arg_key), list):
271            self.args[arg_key] = []
272        self.args[arg_key].append(value)
273        self._set_parent(arg_key, value)

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):
275    def set(self, arg_key, value):
276        """
277        Sets `arg_key` to `value`.
278
279        Args:
280            arg_key (str): name of the expression arg.
281            value: value to set the arg to.
282        """
283        self.args[arg_key] = value
284        self._set_parent(arg_key, value)

Sets arg_key to value.

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

Returns the depth of this tree.

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

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

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
316    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
317        """
318        Returns the first node in this tree which matches at least one of
319        the specified types.
320
321        Args:
322            expression_types: the expression type(s) to match.
323
324        Returns:
325            The node which matches the criteria or None if no such node was found.
326        """
327        return next(self.find_all(*expression_types, bfs=bfs), None)

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

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

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

def find_all(self, *expression_types: Type[~E], bfs=True) -> Iterator[~E]:
329    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
330        """
331        Returns a generator object which visits all nodes in this tree and only
332        yields those that match at least one of the specified expression types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336
337        Returns:
338            The generator object.
339        """
340        for expression, *_ in self.walk(bfs=bfs):
341            if isinstance(expression, expression_types):
342                yield expression

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

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

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
344    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
345        """
346        Returns a nearest parent matching expression_types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350
351        Returns:
352            The parent node.
353        """
354        ancestor = self.parent
355        while ancestor and not isinstance(ancestor, expression_types):
356            ancestor = ancestor.parent
357        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

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

The parent node.

parent_select

Returns the parent select statement.

same_parent

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
371    def root(self) -> Expression:
372        """
373        Returns the root expression of this tree.
374        """
375        expression = self
376        while expression.parent:
377            expression = expression.parent
378        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
380    def walk(self, bfs=True, prune=None):
381        """
382        Returns a generator object which visits all nodes in this tree.
383
384        Args:
385            bfs (bool): if set to True the BFS traversal order will be applied,
386                otherwise the DFS traversal will be used instead.
387            prune ((node, parent, arg_key) -> bool): callable that returns True if
388                the generator should stop traversing this branch of the tree.
389
390        Returns:
391            the generator object.
392        """
393        if bfs:
394            yield from self.bfs(prune=prune)
395        else:
396            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):
398    def dfs(self, parent=None, key=None, prune=None):
399        """
400        Returns a generator object which visits all nodes in this tree in
401        the DFS (Depth-first) order.
402
403        Returns:
404            The generator object.
405        """
406        parent = parent or self.parent
407        yield self, parent, key
408        if prune and prune(self, parent, key):
409            return
410
411        for k, v in self.iter_expressions():
412            yield from v.dfs(self, k, prune)

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

Returns:

The generator object.

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

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

Returns:

The generator object.

def unnest(self):
434    def unnest(self):
435        """
436        Returns the first non parenthesis child or self.
437        """
438        expression = self
439        while type(expression) is Paren:
440            expression = expression.this
441        return expression

Returns the first non parenthesis child or self.

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

Returns the inner expression if this is an Alias.

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

Returns unnested operands as a tuple.

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

Remove this expression from its AST.

Returns:

The popped expression.

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

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
635    @classmethod
636    def load(cls, obj):
637        """
638        Load a dict (as returned by `Expression.dump`) into an Expression instance.
639        """
640        from sqlglot.serde import load
641
642        return load(obj)

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

class Condition(Expression):
653class Condition(Expression):
654    def and_(self, *expressions, dialect=None, **opts):
655        """
656        AND this condition with one or multiple expressions.
657
658        Example:
659            >>> condition("x=1").and_("y=1").sql()
660            'x = 1 AND y = 1'
661
662        Args:
663            *expressions (str | Expression): the SQL code strings to parse.
664                If an `Expression` instance is passed, it will be used as-is.
665            dialect (str): the dialect used to parse the input expression.
666            opts (kwargs): other options to use to parse the input expressions.
667
668        Returns:
669            And: the new condition.
670        """
671        return and_(self, *expressions, dialect=dialect, **opts)
672
673    def or_(self, *expressions, dialect=None, **opts):
674        """
675        OR this condition with one or multiple expressions.
676
677        Example:
678            >>> condition("x=1").or_("y=1").sql()
679            'x = 1 OR y = 1'
680
681        Args:
682            *expressions (str | Expression): the SQL code strings to parse.
683                If an `Expression` instance is passed, it will be used as-is.
684            dialect (str): the dialect used to parse the input expression.
685            opts (kwargs): other options to use to parse the input expressions.
686
687        Returns:
688            Or: the new condition.
689        """
690        return or_(self, *expressions, dialect=dialect, **opts)
691
692    def not_(self):
693        """
694        Wrap this condition with NOT.
695
696        Example:
697            >>> condition("x=1").not_().sql()
698            'NOT x = 1'
699
700        Returns:
701            Not: the new condition.
702        """
703        return not_(self)
def and_(self, *expressions, dialect=None, **opts):
654    def and_(self, *expressions, dialect=None, **opts):
655        """
656        AND this condition with one or multiple expressions.
657
658        Example:
659            >>> condition("x=1").and_("y=1").sql()
660            'x = 1 AND y = 1'
661
662        Args:
663            *expressions (str | Expression): the SQL code strings to parse.
664                If an `Expression` instance is passed, it will be used as-is.
665            dialect (str): the dialect used to parse the input expression.
666            opts (kwargs): other options to use to parse the input expressions.
667
668        Returns:
669            And: the new condition.
670        """
671        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):
673    def or_(self, *expressions, dialect=None, **opts):
674        """
675        OR this condition with one or multiple expressions.
676
677        Example:
678            >>> condition("x=1").or_("y=1").sql()
679            'x = 1 OR y = 1'
680
681        Args:
682            *expressions (str | Expression): the SQL code strings to parse.
683                If an `Expression` instance is passed, it will be used as-is.
684            dialect (str): the dialect used to parse the input expression.
685            opts (kwargs): other options to use to parse the input expressions.
686
687        Returns:
688            Or: the new condition.
689        """
690        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):
692    def not_(self):
693        """
694        Wrap this condition with NOT.
695
696        Example:
697            >>> condition("x=1").not_().sql()
698            'NOT x = 1'
699
700        Returns:
701            Not: the new condition.
702        """
703        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):
706class Predicate(Condition):
707    """Relationships like x = y, x > 1, x >= y."""

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

class DerivedTable(Expression):
710class DerivedTable(Expression):
711    @property
712    def alias_column_names(self):
713        table_alias = self.args.get("alias")
714        if not table_alias:
715            return []
716        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
717        return [c.name for c in column_list]
718
719    @property
720    def selects(self):
721        alias = self.args.get("alias")
722
723        if alias:
724            return alias.columns
725        return []
726
727    @property
728    def named_selects(self):
729        return [select.output_name for select in self.selects]
class Unionable(Expression):
732class Unionable(Expression):
733    def union(self, expression, distinct=True, dialect=None, **opts):
734        """
735        Builds a UNION expression.
736
737        Example:
738            >>> import sqlglot
739            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
740            'SELECT * FROM foo UNION SELECT * FROM bla'
741
742        Args:
743            expression (str | Expression): the SQL code string.
744                If an `Expression` instance is passed, it will be used as-is.
745            distinct (bool): set the DISTINCT flag if and only if this is true.
746            dialect (str): the dialect used to parse the input expression.
747            opts (kwargs): other options to use to parse the input expressions.
748        Returns:
749            Union: the Union expression.
750        """
751        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
752
753    def intersect(self, expression, distinct=True, dialect=None, **opts):
754        """
755        Builds an INTERSECT expression.
756
757        Example:
758            >>> import sqlglot
759            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
760            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
761
762        Args:
763            expression (str | Expression): the SQL code string.
764                If an `Expression` instance is passed, it will be used as-is.
765            distinct (bool): set the DISTINCT flag if and only if this is true.
766            dialect (str): the dialect used to parse the input expression.
767            opts (kwargs): other options to use to parse the input expressions.
768        Returns:
769            Intersect: the Intersect expression
770        """
771        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
772
773    def except_(self, expression, distinct=True, dialect=None, **opts):
774        """
775        Builds an EXCEPT expression.
776
777        Example:
778            >>> import sqlglot
779            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
780            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
781
782        Args:
783            expression (str | Expression): the SQL code string.
784                If an `Expression` instance is passed, it will be used as-is.
785            distinct (bool): set the DISTINCT flag if and only if this is true.
786            dialect (str): the dialect used to parse the input expression.
787            opts (kwargs): other options to use to parse the input expressions.
788        Returns:
789            Except: the Except expression
790        """
791        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
733    def union(self, expression, distinct=True, dialect=None, **opts):
734        """
735        Builds a UNION expression.
736
737        Example:
738            >>> import sqlglot
739            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
740            'SELECT * FROM foo UNION SELECT * FROM bla'
741
742        Args:
743            expression (str | Expression): the SQL code string.
744                If an `Expression` instance is passed, it will be used as-is.
745            distinct (bool): set the DISTINCT flag if and only if this is true.
746            dialect (str): the dialect used to parse the input expression.
747            opts (kwargs): other options to use to parse the input expressions.
748        Returns:
749            Union: the Union expression.
750        """
751        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):
753    def intersect(self, expression, distinct=True, dialect=None, **opts):
754        """
755        Builds an INTERSECT expression.
756
757        Example:
758            >>> import sqlglot
759            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
760            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
761
762        Args:
763            expression (str | Expression): the SQL code string.
764                If an `Expression` instance is passed, it will be used as-is.
765            distinct (bool): set the DISTINCT flag if and only if this is true.
766            dialect (str): the dialect used to parse the input expression.
767            opts (kwargs): other options to use to parse the input expressions.
768        Returns:
769            Intersect: the Intersect expression
770        """
771        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):
773    def except_(self, expression, distinct=True, dialect=None, **opts):
774        """
775        Builds an EXCEPT expression.
776
777        Example:
778            >>> import sqlglot
779            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
780            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
781
782        Args:
783            expression (str | Expression): the SQL code string.
784                If an `Expression` instance is passed, it will be used as-is.
785            distinct (bool): set the DISTINCT flag if and only if this is true.
786            dialect (str): the dialect used to parse the input expression.
787            opts (kwargs): other options to use to parse the input expressions.
788        Returns:
789            Except: the Except expression
790        """
791        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):
794class UDTF(DerivedTable, Unionable):
795    pass
class Cache(Expression):
798class Cache(Expression):
799    arg_types = {
800        "with": False,
801        "this": True,
802        "lazy": False,
803        "options": False,
804        "expression": False,
805    }
class Uncache(Expression):
808class Uncache(Expression):
809    arg_types = {"this": True, "exists": False}
class Create(Expression):
812class Create(Expression):
813    arg_types = {
814        "with": False,
815        "this": True,
816        "kind": True,
817        "expression": False,
818        "exists": False,
819        "properties": False,
820        "replace": False,
821        "unique": False,
822        "volatile": False,
823        "indexes": False,
824        "no_schema_binding": False,
825        "begin": False,
826    }
class Describe(Expression):
829class Describe(Expression):
830    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
833class Pragma(Expression):
834    pass
class Set(Expression):
837class Set(Expression):
838    arg_types = {"expressions": False}
class SetItem(Expression):
841class SetItem(Expression):
842    arg_types = {
843        "this": False,
844        "expressions": False,
845        "kind": False,
846        "collate": False,  # MySQL SET NAMES statement
847        "global": False,
848    }
class Show(Expression):
851class Show(Expression):
852    arg_types = {
853        "this": True,
854        "target": False,
855        "offset": False,
856        "limit": False,
857        "like": False,
858        "where": False,
859        "db": False,
860        "full": False,
861        "mutex": False,
862        "query": False,
863        "channel": False,
864        "global": False,
865        "log": False,
866        "position": False,
867        "types": False,
868    }
class UserDefinedFunction(Expression):
871class UserDefinedFunction(Expression):
872    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
875class CharacterSet(Expression):
876    arg_types = {"this": True, "default": False}
class With(Expression):
879class With(Expression):
880    arg_types = {"expressions": True, "recursive": False}
881
882    @property
883    def recursive(self) -> bool:
884        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
887class WithinGroup(Expression):
888    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
891class CTE(DerivedTable):
892    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
895class TableAlias(Expression):
896    arg_types = {"this": False, "columns": False}
897
898    @property
899    def columns(self):
900        return self.args.get("columns") or []
class BitString(Condition):
903class BitString(Condition):
904    pass
class HexString(Condition):
907class HexString(Condition):
908    pass
class ByteString(Condition):
911class ByteString(Condition):
912    pass
class Column(Condition):
915class Column(Condition):
916    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
917
918    @property
919    def table(self) -> str:
920        return self.text("table")
921
922    @property
923    def db(self) -> str:
924        return self.text("db")
925
926    @property
927    def catalog(self) -> str:
928        return self.text("catalog")
929
930    @property
931    def output_name(self) -> str:
932        return self.name
933
934    @property
935    def parts(self) -> t.List[Identifier]:
936        """Return the parts of a column in order catalog, db, table, name."""
937        return [part for part in reversed(list(self.args.values())) if part]
938
939    def to_dot(self) -> Dot:
940        """Converts the column into a dot expression."""
941        parts = self.parts
942        parent = self.parent
943
944        while parent:
945            if isinstance(parent, Dot):
946                parts.append(parent.expression)
947            parent = parent.parent
948
949        return Dot.build(parts)
output_name: str

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

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

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

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

def to_dot(self) -> sqlglot.expressions.Dot:
939    def to_dot(self) -> Dot:
940        """Converts the column into a dot expression."""
941        parts = self.parts
942        parent = self.parent
943
944        while parent:
945            if isinstance(parent, Dot):
946                parts.append(parent.expression)
947            parent = parent.parent
948
949        return Dot.build(parts)

Converts the column into a dot expression.

class ColumnPosition(Expression):
952class ColumnPosition(Expression):
953    arg_types = {"this": False, "position": True}
class ColumnDef(Expression):
956class ColumnDef(Expression):
957    arg_types = {
958        "this": True,
959        "kind": False,
960        "constraints": False,
961        "exists": False,
962        "position": False,
963    }
class AlterColumn(Expression):
966class AlterColumn(Expression):
967    arg_types = {
968        "this": True,
969        "dtype": False,
970        "collate": False,
971        "using": False,
972        "default": False,
973        "drop": False,
974    }
class RenameTable(Expression):
977class RenameTable(Expression):
978    pass
class SetTag(Expression):
981class SetTag(Expression):
982    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
985class Comment(Expression):
986    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class ColumnConstraint(Expression):
989class ColumnConstraint(Expression):
990    arg_types = {"this": False, "kind": True}
class ColumnConstraintKind(Expression):
993class ColumnConstraintKind(Expression):
994    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
997class AutoIncrementColumnConstraint(ColumnConstraintKind):
998    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1001class CaseSpecificColumnConstraint(ColumnConstraintKind):
1002    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1005class CharacterSetColumnConstraint(ColumnConstraintKind):
1006    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1009class CheckColumnConstraint(ColumnConstraintKind):
1010    pass
class CollateColumnConstraint(ColumnConstraintKind):
1013class CollateColumnConstraint(ColumnConstraintKind):
1014    pass
class CommentColumnConstraint(ColumnConstraintKind):
1017class CommentColumnConstraint(ColumnConstraintKind):
1018    pass
class CompressColumnConstraint(ColumnConstraintKind):
1021class CompressColumnConstraint(ColumnConstraintKind):
1022    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1025class DateFormatColumnConstraint(ColumnConstraintKind):
1026    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1029class DefaultColumnConstraint(ColumnConstraintKind):
1030    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1033class EncodeColumnConstraint(ColumnConstraintKind):
1034    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1037class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1038    # this: True -> ALWAYS, this: False -> BY DEFAULT
1039    arg_types = {
1040        "this": False,
1041        "start": False,
1042        "increment": False,
1043        "minvalue": False,
1044        "maxvalue": False,
1045        "cycle": False,
1046    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1049class InlineLengthColumnConstraint(ColumnConstraintKind):
1050    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1053class NotNullColumnConstraint(ColumnConstraintKind):
1054    arg_types = {"allow_null": False}
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1057class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1058    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1061class TitleColumnConstraint(ColumnConstraintKind):
1062    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1065class UniqueColumnConstraint(ColumnConstraintKind):
1066    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1069class UppercaseColumnConstraint(ColumnConstraintKind):
1070    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1073class PathColumnConstraint(ColumnConstraintKind):
1074    pass
class Constraint(Expression):
1077class Constraint(Expression):
1078    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1081class Delete(Expression):
1082    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1083
1084    def delete(
1085        self,
1086        table: ExpOrStr,
1087        dialect: DialectType = None,
1088        copy: bool = True,
1089        **opts,
1090    ) -> Delete:
1091        """
1092        Create a DELETE expression or replace the table on an existing DELETE expression.
1093
1094        Example:
1095            >>> delete("tbl").sql()
1096            'DELETE FROM tbl'
1097
1098        Args:
1099            table: the table from which to delete.
1100            dialect: the dialect used to parse the input expression.
1101            copy: if `False`, modify this expression instance in-place.
1102            opts: other options to use to parse the input expressions.
1103
1104        Returns:
1105            Delete: the modified expression.
1106        """
1107        return _apply_builder(
1108            expression=table,
1109            instance=self,
1110            arg="this",
1111            dialect=dialect,
1112            into=Table,
1113            copy=copy,
1114            **opts,
1115        )
1116
1117    def where(
1118        self,
1119        *expressions: ExpOrStr,
1120        append: bool = True,
1121        dialect: DialectType = None,
1122        copy: bool = True,
1123        **opts,
1124    ) -> Delete:
1125        """
1126        Append to or set the WHERE expressions.
1127
1128        Example:
1129            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1130            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1131
1132        Args:
1133            *expressions: the SQL code strings to parse.
1134                If an `Expression` instance is passed, it will be used as-is.
1135                Multiple expressions are combined with an AND operator.
1136            append: if `True`, AND the new expressions to any existing expression.
1137                Otherwise, this resets the expression.
1138            dialect: the dialect used to parse the input expressions.
1139            copy: if `False`, modify this expression instance in-place.
1140            opts: other options to use to parse the input expressions.
1141
1142        Returns:
1143            Delete: the modified expression.
1144        """
1145        return _apply_conjunction_builder(
1146            *expressions,
1147            instance=self,
1148            arg="where",
1149            append=append,
1150            into=Where,
1151            dialect=dialect,
1152            copy=copy,
1153            **opts,
1154        )
1155
1156    def returning(
1157        self,
1158        expression: ExpOrStr,
1159        dialect: DialectType = None,
1160        copy: bool = True,
1161        **opts,
1162    ) -> Delete:
1163        """
1164        Set the RETURNING expression. Not supported by all dialects.
1165
1166        Example:
1167            >>> delete("tbl").returning("*", dialect="postgres").sql()
1168            'DELETE FROM tbl RETURNING *'
1169
1170        Args:
1171            expression: the SQL code strings to parse.
1172                If an `Expression` instance is passed, it will be used as-is.
1173            dialect: the dialect used to parse the input expressions.
1174            copy: if `False`, modify this expression instance in-place.
1175            opts: other options to use to parse the input expressions.
1176
1177        Returns:
1178            Delete: the modified expression.
1179        """
1180        return _apply_builder(
1181            expression=expression,
1182            instance=self,
1183            arg="returning",
1184            prefix="RETURNING",
1185            dialect=dialect,
1186            copy=copy,
1187            into=Returning,
1188            **opts,
1189        )
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:
1084    def delete(
1085        self,
1086        table: ExpOrStr,
1087        dialect: DialectType = None,
1088        copy: bool = True,
1089        **opts,
1090    ) -> Delete:
1091        """
1092        Create a DELETE expression or replace the table on an existing DELETE expression.
1093
1094        Example:
1095            >>> delete("tbl").sql()
1096            'DELETE FROM tbl'
1097
1098        Args:
1099            table: the table from which to delete.
1100            dialect: the dialect used to parse the input expression.
1101            copy: if `False`, modify this expression instance in-place.
1102            opts: other options to use to parse the input expressions.
1103
1104        Returns:
1105            Delete: the modified expression.
1106        """
1107        return _apply_builder(
1108            expression=table,
1109            instance=self,
1110            arg="this",
1111            dialect=dialect,
1112            into=Table,
1113            copy=copy,
1114            **opts,
1115        )

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:
1117    def where(
1118        self,
1119        *expressions: ExpOrStr,
1120        append: bool = True,
1121        dialect: DialectType = None,
1122        copy: bool = True,
1123        **opts,
1124    ) -> Delete:
1125        """
1126        Append to or set the WHERE expressions.
1127
1128        Example:
1129            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1130            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1131
1132        Args:
1133            *expressions: the SQL code strings to parse.
1134                If an `Expression` instance is passed, it will be used as-is.
1135                Multiple expressions are combined with an AND operator.
1136            append: if `True`, AND the new expressions to any existing expression.
1137                Otherwise, this resets the expression.
1138            dialect: the dialect used to parse the input expressions.
1139            copy: if `False`, modify this expression instance in-place.
1140            opts: other options to use to parse the input expressions.
1141
1142        Returns:
1143            Delete: the modified expression.
1144        """
1145        return _apply_conjunction_builder(
1146            *expressions,
1147            instance=self,
1148            arg="where",
1149            append=append,
1150            into=Where,
1151            dialect=dialect,
1152            copy=copy,
1153            **opts,
1154        )

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:
1156    def returning(
1157        self,
1158        expression: ExpOrStr,
1159        dialect: DialectType = None,
1160        copy: bool = True,
1161        **opts,
1162    ) -> Delete:
1163        """
1164        Set the RETURNING expression. Not supported by all dialects.
1165
1166        Example:
1167            >>> delete("tbl").returning("*", dialect="postgres").sql()
1168            'DELETE FROM tbl RETURNING *'
1169
1170        Args:
1171            expression: the SQL code strings to parse.
1172                If an `Expression` instance is passed, it will be used as-is.
1173            dialect: the dialect used to parse the input expressions.
1174            copy: if `False`, modify this expression instance in-place.
1175            opts: other options to use to parse the input expressions.
1176
1177        Returns:
1178            Delete: the modified expression.
1179        """
1180        return _apply_builder(
1181            expression=expression,
1182            instance=self,
1183            arg="returning",
1184            prefix="RETURNING",
1185            dialect=dialect,
1186            copy=copy,
1187            into=Returning,
1188            **opts,
1189        )

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):
1192class Drop(Expression):
1193    arg_types = {
1194        "this": False,
1195        "kind": False,
1196        "exists": False,
1197        "temporary": False,
1198        "materialized": False,
1199        "cascade": False,
1200        "constraints": False,
1201    }
class Filter(Expression):
1204class Filter(Expression):
1205    arg_types = {"this": True, "expression": True}
class Check(Expression):
1208class Check(Expression):
1209    pass
class Directory(Expression):
1212class Directory(Expression):
1213    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1214    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1217class ForeignKey(Expression):
1218    arg_types = {
1219        "expressions": True,
1220        "reference": False,
1221        "delete": False,
1222        "update": False,
1223    }
class PrimaryKey(Expression):
1226class PrimaryKey(Expression):
1227    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1230class Unique(Expression):
1231    arg_types = {"expressions": True}
class Into(Expression):
1236class Into(Expression):
1237    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1240class From(Expression):
1241    arg_types = {"expressions": True}
class Having(Expression):
1244class Having(Expression):
1245    pass
class Hint(Expression):
1248class Hint(Expression):
1249    arg_types = {"expressions": True}
class JoinHint(Expression):
1252class JoinHint(Expression):
1253    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1256class Identifier(Expression):
1257    arg_types = {"this": True, "quoted": False}
1258
1259    @property
1260    def quoted(self):
1261        return bool(self.args.get("quoted"))
1262
1263    @property
1264    def hashable_args(self) -> t.Any:
1265        if self.quoted and any(char.isupper() for char in self.this):
1266            return (self.this, self.quoted)
1267        return self.this.lower()
1268
1269    @property
1270    def output_name(self):
1271        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):
1274class Index(Expression):
1275    arg_types = {
1276        "this": False,
1277        "table": False,
1278        "where": False,
1279        "columns": False,
1280        "unique": False,
1281        "primary": False,
1282        "amp": False,  # teradata
1283    }
class Insert(Expression):
1286class Insert(Expression):
1287    arg_types = {
1288        "with": False,
1289        "this": True,
1290        "expression": False,
1291        "returning": False,
1292        "overwrite": False,
1293        "exists": False,
1294        "partition": False,
1295        "alternative": False,
1296    }
class Returning(Expression):
1299class Returning(Expression):
1300    arg_types = {"expressions": True}
class Introducer(Expression):
1304class Introducer(Expression):
1305    arg_types = {"this": True, "expression": True}
class National(Expression):
1309class National(Expression):
1310    pass
class LoadData(Expression):
1313class LoadData(Expression):
1314    arg_types = {
1315        "this": True,
1316        "local": False,
1317        "overwrite": False,
1318        "inpath": True,
1319        "partition": False,
1320        "input_format": False,
1321        "serde": False,
1322    }
class Partition(Expression):
1325class Partition(Expression):
1326    arg_types = {"expressions": True}
class Fetch(Expression):
1329class Fetch(Expression):
1330    arg_types = {"direction": False, "count": False}
class Group(Expression):
1333class Group(Expression):
1334    arg_types = {
1335        "expressions": False,
1336        "grouping_sets": False,
1337        "cube": False,
1338        "rollup": False,
1339    }
class Lambda(Expression):
1342class Lambda(Expression):
1343    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1346class Limit(Expression):
1347    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1350class Literal(Condition):
1351    arg_types = {"this": True, "is_string": True}
1352
1353    @property
1354    def hashable_args(self) -> t.Any:
1355        return (self.this, self.args.get("is_string"))
1356
1357    @classmethod
1358    def number(cls, number) -> Literal:
1359        return cls(this=str(number), is_string=False)
1360
1361    @classmethod
1362    def string(cls, string) -> Literal:
1363        return cls(this=str(string), is_string=True)
1364
1365    @property
1366    def output_name(self):
1367        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1357    @classmethod
1358    def number(cls, number) -> Literal:
1359        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1361    @classmethod
1362    def string(cls, string) -> Literal:
1363        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):
1370class Join(Expression):
1371    arg_types = {
1372        "this": True,
1373        "on": False,
1374        "side": False,
1375        "kind": False,
1376        "using": False,
1377        "natural": False,
1378    }
1379
1380    @property
1381    def kind(self):
1382        return self.text("kind").upper()
1383
1384    @property
1385    def side(self):
1386        return self.text("side").upper()
1387
1388    @property
1389    def alias_or_name(self):
1390        return self.this.alias_or_name
1391
1392    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1393        """
1394        Append to or set the ON expressions.
1395
1396        Example:
1397            >>> import sqlglot
1398            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1399            'JOIN x ON y = 1'
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                Multiple expressions are combined with an AND operator.
1405            append (bool): if `True`, AND the new expressions to any existing expression.
1406                Otherwise, this resets the expression.
1407            dialect (str): the dialect used to parse the input expressions.
1408            copy (bool): if `False`, modify this expression instance in-place.
1409            opts (kwargs): other options to use to parse the input expressions.
1410
1411        Returns:
1412            Join: the modified join expression.
1413        """
1414        join = _apply_conjunction_builder(
1415            *expressions,
1416            instance=self,
1417            arg="on",
1418            append=append,
1419            dialect=dialect,
1420            copy=copy,
1421            **opts,
1422        )
1423
1424        if join.kind == "CROSS":
1425            join.set("kind", None)
1426
1427        return join
1428
1429    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1430        """
1431        Append to or set the USING expressions.
1432
1433        Example:
1434            >>> import sqlglot
1435            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1436            'JOIN x USING (foo, bla)'
1437
1438        Args:
1439            *expressions (str | Expression): the SQL code strings to parse.
1440                If an `Expression` instance is passed, it will be used as-is.
1441            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1442                Otherwise, this resets the expression.
1443            dialect (str): the dialect used to parse the input expressions.
1444            copy (bool): if `False`, modify this expression instance in-place.
1445            opts (kwargs): other options to use to parse the input expressions.
1446
1447        Returns:
1448            Join: the modified join expression.
1449        """
1450        join = _apply_list_builder(
1451            *expressions,
1452            instance=self,
1453            arg="using",
1454            append=append,
1455            dialect=dialect,
1456            copy=copy,
1457            **opts,
1458        )
1459
1460        if join.kind == "CROSS":
1461            join.set("kind", None)
1462
1463        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1392    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1393        """
1394        Append to or set the ON expressions.
1395
1396        Example:
1397            >>> import sqlglot
1398            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1399            'JOIN x ON y = 1'
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                Multiple expressions are combined with an AND operator.
1405            append (bool): if `True`, AND the new expressions to any existing expression.
1406                Otherwise, this resets the expression.
1407            dialect (str): the dialect used to parse the input expressions.
1408            copy (bool): if `False`, modify this expression instance in-place.
1409            opts (kwargs): other options to use to parse the input expressions.
1410
1411        Returns:
1412            Join: the modified join expression.
1413        """
1414        join = _apply_conjunction_builder(
1415            *expressions,
1416            instance=self,
1417            arg="on",
1418            append=append,
1419            dialect=dialect,
1420            copy=copy,
1421            **opts,
1422        )
1423
1424        if join.kind == "CROSS":
1425            join.set("kind", None)
1426
1427        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):
1429    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1430        """
1431        Append to or set the USING expressions.
1432
1433        Example:
1434            >>> import sqlglot
1435            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1436            'JOIN x USING (foo, bla)'
1437
1438        Args:
1439            *expressions (str | Expression): the SQL code strings to parse.
1440                If an `Expression` instance is passed, it will be used as-is.
1441            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1442                Otherwise, this resets the expression.
1443            dialect (str): the dialect used to parse the input expressions.
1444            copy (bool): if `False`, modify this expression instance in-place.
1445            opts (kwargs): other options to use to parse the input expressions.
1446
1447        Returns:
1448            Join: the modified join expression.
1449        """
1450        join = _apply_list_builder(
1451            *expressions,
1452            instance=self,
1453            arg="using",
1454            append=append,
1455            dialect=dialect,
1456            copy=copy,
1457            **opts,
1458        )
1459
1460        if join.kind == "CROSS":
1461            join.set("kind", None)
1462
1463        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):
1466class Lateral(UDTF):
1467    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1470class MatchRecognize(Expression):
1471    arg_types = {
1472        "partition_by": False,
1473        "order": False,
1474        "measures": False,
1475        "rows": False,
1476        "after": False,
1477        "pattern": False,
1478        "define": False,
1479    }
class Final(Expression):
1484class Final(Expression):
1485    pass
class Offset(Expression):
1488class Offset(Expression):
1489    arg_types = {"this": False, "expression": True}
class Order(Expression):
1492class Order(Expression):
1493    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1498class Cluster(Order):
1499    pass
class Distribute(Order):
1502class Distribute(Order):
1503    pass
class Sort(Order):
1506class Sort(Order):
1507    pass
class Ordered(Expression):
1510class Ordered(Expression):
1511    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1514class Property(Expression):
1515    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1518class AfterJournalProperty(Property):
1519    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1522class AlgorithmProperty(Property):
1523    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1526class AutoIncrementProperty(Property):
1527    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1530class BlockCompressionProperty(Property):
1531    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1534class CharacterSetProperty(Property):
1535    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1538class ChecksumProperty(Property):
1539    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1542class CollateProperty(Property):
1543    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1546class DataBlocksizeProperty(Property):
1547    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1550class DefinerProperty(Property):
1551    arg_types = {"this": True}
class DistKeyProperty(Property):
1554class DistKeyProperty(Property):
1555    arg_types = {"this": True}
class DistStyleProperty(Property):
1558class DistStyleProperty(Property):
1559    arg_types = {"this": True}
class EngineProperty(Property):
1562class EngineProperty(Property):
1563    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1566class ExecuteAsProperty(Property):
1567    arg_types = {"this": True}
class ExternalProperty(Property):
1570class ExternalProperty(Property):
1571    arg_types = {"this": False}
class FallbackProperty(Property):
1574class FallbackProperty(Property):
1575    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1578class FileFormatProperty(Property):
1579    arg_types = {"this": True}
class FreespaceProperty(Property):
1582class FreespaceProperty(Property):
1583    arg_types = {"this": True, "percent": False}
class IsolatedLoadingProperty(Property):
1586class IsolatedLoadingProperty(Property):
1587    arg_types = {
1588        "no": True,
1589        "concurrent": True,
1590        "for_all": True,
1591        "for_insert": True,
1592        "for_none": True,
1593    }
class JournalProperty(Property):
1596class JournalProperty(Property):
1597    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1600class LanguageProperty(Property):
1601    arg_types = {"this": True}
class LikeProperty(Property):
1604class LikeProperty(Property):
1605    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1608class LocationProperty(Property):
1609    arg_types = {"this": True}
class LockingProperty(Property):
1612class LockingProperty(Property):
1613    arg_types = {
1614        "this": False,
1615        "kind": True,
1616        "for_or_in": True,
1617        "lock_type": True,
1618        "override": False,
1619    }
class LogProperty(Property):
1622class LogProperty(Property):
1623    arg_types = {"no": True}
class MaterializedProperty(Property):
1626class MaterializedProperty(Property):
1627    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1630class MergeBlockRatioProperty(Property):
1631    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1634class NoPrimaryIndexProperty(Property):
1635    arg_types = {"this": False}
class OnCommitProperty(Property):
1638class OnCommitProperty(Property):
1639    arg_type = {"this": False}
class PartitionedByProperty(Property):
1642class PartitionedByProperty(Property):
1643    arg_types = {"this": True}
class ReturnsProperty(Property):
1646class ReturnsProperty(Property):
1647    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatDelimitedProperty(Property):
1650class RowFormatDelimitedProperty(Property):
1651    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1652    arg_types = {
1653        "fields": False,
1654        "escaped": False,
1655        "collection_items": False,
1656        "map_keys": False,
1657        "lines": False,
1658        "null": False,
1659        "serde": False,
1660    }
class RowFormatSerdeProperty(Property):
1663class RowFormatSerdeProperty(Property):
1664    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1667class SchemaCommentProperty(Property):
1668    arg_types = {"this": True}
class SerdeProperties(Property):
1671class SerdeProperties(Property):
1672    arg_types = {"expressions": True}
class SetProperty(Property):
1675class SetProperty(Property):
1676    arg_types = {"multi": True}
class SortKeyProperty(Property):
1679class SortKeyProperty(Property):
1680    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1683class SqlSecurityProperty(Property):
1684    arg_types = {"definer": True}
class TableFormatProperty(Property):
1687class TableFormatProperty(Property):
1688    arg_types = {"this": True}
class TemporaryProperty(Property):
1691class TemporaryProperty(Property):
1692    arg_types = {"global_": True}
class TransientProperty(Property):
1695class TransientProperty(Property):
1696    arg_types = {"this": False}
class VolatilityProperty(Property):
1699class VolatilityProperty(Property):
1700    arg_types = {"this": True}
class WithDataProperty(Property):
1703class WithDataProperty(Property):
1704    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1707class WithJournalTableProperty(Property):
1708    arg_types = {"this": True}
class Properties(Expression):
1711class Properties(Expression):
1712    arg_types = {"expressions": True}
1713
1714    NAME_TO_PROPERTY = {
1715        "ALGORITHM": AlgorithmProperty,
1716        "AUTO_INCREMENT": AutoIncrementProperty,
1717        "CHARACTER SET": CharacterSetProperty,
1718        "COLLATE": CollateProperty,
1719        "COMMENT": SchemaCommentProperty,
1720        "DEFINER": DefinerProperty,
1721        "DISTKEY": DistKeyProperty,
1722        "DISTSTYLE": DistStyleProperty,
1723        "ENGINE": EngineProperty,
1724        "EXECUTE AS": ExecuteAsProperty,
1725        "FORMAT": FileFormatProperty,
1726        "LANGUAGE": LanguageProperty,
1727        "LOCATION": LocationProperty,
1728        "PARTITIONED_BY": PartitionedByProperty,
1729        "RETURNS": ReturnsProperty,
1730        "SORTKEY": SortKeyProperty,
1731        "TABLE_FORMAT": TableFormatProperty,
1732    }
1733
1734    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1735
1736    # CREATE property locations
1737    # Form: schema specified
1738    #   create [POST_CREATE]
1739    #     table a [POST_NAME]
1740    #     (b int) [POST_SCHEMA]
1741    #     with ([POST_WITH])
1742    #     index (b) [POST_INDEX]
1743    #
1744    # Form: alias selection
1745    #   create [POST_CREATE]
1746    #     table a [POST_NAME]
1747    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1748    #     index (c) [POST_INDEX]
1749    class Location(AutoName):
1750        POST_CREATE = auto()
1751        POST_NAME = auto()
1752        POST_SCHEMA = auto()
1753        POST_WITH = auto()
1754        POST_ALIAS = auto()
1755        POST_EXPRESSION = auto()
1756        POST_INDEX = auto()
1757        UNSUPPORTED = auto()
1758
1759    @classmethod
1760    def from_dict(cls, properties_dict) -> Properties:
1761        expressions = []
1762        for key, value in properties_dict.items():
1763            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1764            if property_cls:
1765                expressions.append(property_cls(this=convert(value)))
1766            else:
1767                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1768
1769        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
1759    @classmethod
1760    def from_dict(cls, properties_dict) -> Properties:
1761        expressions = []
1762        for key, value in properties_dict.items():
1763            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1764            if property_cls:
1765                expressions.append(property_cls(this=convert(value)))
1766            else:
1767                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1768
1769        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
1749    class Location(AutoName):
1750        POST_CREATE = auto()
1751        POST_NAME = auto()
1752        POST_SCHEMA = auto()
1753        POST_WITH = auto()
1754        POST_ALIAS = auto()
1755        POST_EXPRESSION = auto()
1756        POST_INDEX = auto()
1757        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):
1772class Qualify(Expression):
1773    pass
class Return(Expression):
1777class Return(Expression):
1778    pass
class Reference(Expression):
1781class Reference(Expression):
1782    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
1785class Tuple(Expression):
1786    arg_types = {"expressions": False}
class Subqueryable(Unionable):
1789class Subqueryable(Unionable):
1790    def subquery(self, alias=None, copy=True) -> Subquery:
1791        """
1792        Convert this expression to an aliased expression that can be used as a Subquery.
1793
1794        Example:
1795            >>> subquery = Select().select("x").from_("tbl").subquery()
1796            >>> Select().select("x").from_(subquery).sql()
1797            'SELECT x FROM (SELECT x FROM tbl)'
1798
1799        Args:
1800            alias (str | Identifier): an optional alias for the subquery
1801            copy (bool): if `False`, modify this expression instance in-place.
1802
1803        Returns:
1804            Alias: the subquery
1805        """
1806        instance = _maybe_copy(self, copy)
1807        return Subquery(
1808            this=instance,
1809            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1810        )
1811
1812    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1813        raise NotImplementedError
1814
1815    @property
1816    def ctes(self):
1817        with_ = self.args.get("with")
1818        if not with_:
1819            return []
1820        return with_.expressions
1821
1822    @property
1823    def selects(self):
1824        raise NotImplementedError("Subqueryable objects must implement `selects`")
1825
1826    @property
1827    def named_selects(self):
1828        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1829
1830    def with_(
1831        self,
1832        alias,
1833        as_,
1834        recursive=None,
1835        append=True,
1836        dialect=None,
1837        copy=True,
1838        **opts,
1839    ):
1840        """
1841        Append to or set the common table expressions.
1842
1843        Example:
1844            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1845            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1846
1847        Args:
1848            alias (str | Expression): the SQL code string to parse as the table name.
1849                If an `Expression` instance is passed, this is used as-is.
1850            as_ (str | Expression): the SQL code string to parse as the table expression.
1851                If an `Expression` instance is passed, it will be used as-is.
1852            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1853            append (bool): if `True`, add to any existing expressions.
1854                Otherwise, this resets the expressions.
1855            dialect (str): the dialect used to parse the input expression.
1856            copy (bool): if `False`, modify this expression instance in-place.
1857            opts (kwargs): other options to use to parse the input expressions.
1858
1859        Returns:
1860            Select: the modified expression.
1861        """
1862        alias_expression = maybe_parse(
1863            alias,
1864            dialect=dialect,
1865            into=TableAlias,
1866            **opts,
1867        )
1868        as_expression = maybe_parse(
1869            as_,
1870            dialect=dialect,
1871            **opts,
1872        )
1873        cte = CTE(
1874            this=as_expression,
1875            alias=alias_expression,
1876        )
1877        return _apply_child_list_builder(
1878            cte,
1879            instance=self,
1880            arg="with",
1881            append=append,
1882            copy=copy,
1883            into=With,
1884            properties={"recursive": recursive or False},
1885        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
1790    def subquery(self, alias=None, copy=True) -> Subquery:
1791        """
1792        Convert this expression to an aliased expression that can be used as a Subquery.
1793
1794        Example:
1795            >>> subquery = Select().select("x").from_("tbl").subquery()
1796            >>> Select().select("x").from_(subquery).sql()
1797            'SELECT x FROM (SELECT x FROM tbl)'
1798
1799        Args:
1800            alias (str | Identifier): an optional alias for the subquery
1801            copy (bool): if `False`, modify this expression instance in-place.
1802
1803        Returns:
1804            Alias: the subquery
1805        """
1806        instance = _maybe_copy(self, copy)
1807        return Subquery(
1808            this=instance,
1809            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1810        )

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:
1812    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1813        raise NotImplementedError
def with_( self, alias, as_, recursive=None, append=True, dialect=None, copy=True, **opts):
1830    def with_(
1831        self,
1832        alias,
1833        as_,
1834        recursive=None,
1835        append=True,
1836        dialect=None,
1837        copy=True,
1838        **opts,
1839    ):
1840        """
1841        Append to or set the common table expressions.
1842
1843        Example:
1844            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1845            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1846
1847        Args:
1848            alias (str | Expression): the SQL code string to parse as the table name.
1849                If an `Expression` instance is passed, this is used as-is.
1850            as_ (str | Expression): the SQL code string to parse as the table expression.
1851                If an `Expression` instance is passed, it will be used as-is.
1852            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1853            append (bool): if `True`, add to any existing expressions.
1854                Otherwise, this resets the expressions.
1855            dialect (str): the dialect used to parse the input expression.
1856            copy (bool): if `False`, modify this expression instance in-place.
1857            opts (kwargs): other options to use to parse the input expressions.
1858
1859        Returns:
1860            Select: the modified expression.
1861        """
1862        alias_expression = maybe_parse(
1863            alias,
1864            dialect=dialect,
1865            into=TableAlias,
1866            **opts,
1867        )
1868        as_expression = maybe_parse(
1869            as_,
1870            dialect=dialect,
1871            **opts,
1872        )
1873        cte = CTE(
1874            this=as_expression,
1875            alias=alias_expression,
1876        )
1877        return _apply_child_list_builder(
1878            cte,
1879            instance=self,
1880            arg="with",
1881            append=append,
1882            copy=copy,
1883            into=With,
1884            properties={"recursive": recursive or False},
1885        )

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):
1909class Table(Expression):
1910    arg_types = {
1911        "this": True,
1912        "alias": False,
1913        "db": False,
1914        "catalog": False,
1915        "laterals": False,
1916        "joins": False,
1917        "pivots": False,
1918        "hints": False,
1919        "system_time": False,
1920    }
1921
1922    @property
1923    def db(self) -> str:
1924        return self.text("db")
1925
1926    @property
1927    def catalog(self) -> str:
1928        return self.text("catalog")
class SystemTime(Expression):
1932class SystemTime(Expression):
1933    arg_types = {
1934        "this": False,
1935        "expression": False,
1936        "kind": True,
1937    }
class Union(Subqueryable):
1940class Union(Subqueryable):
1941    arg_types = {
1942        "with": False,
1943        "this": True,
1944        "expression": True,
1945        "distinct": False,
1946        **QUERY_MODIFIERS,
1947    }
1948
1949    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1950        """
1951        Set the LIMIT expression.
1952
1953        Example:
1954            >>> select("1").union(select("1")).limit(1).sql()
1955            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1956
1957        Args:
1958            expression (str | int | Expression): the SQL code string to parse.
1959                This can also be an integer.
1960                If a `Limit` instance is passed, this is used as-is.
1961                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1962            dialect (str): the dialect used to parse the input expression.
1963            copy (bool): if `False`, modify this expression instance in-place.
1964            opts (kwargs): other options to use to parse the input expressions.
1965
1966        Returns:
1967            Select: The limited subqueryable.
1968        """
1969        return (
1970            select("*")
1971            .from_(self.subquery(alias="_l_0", copy=copy))
1972            .limit(expression, dialect=dialect, copy=False, **opts)
1973        )
1974
1975    def select(
1976        self,
1977        *expressions: ExpOrStr,
1978        append: bool = True,
1979        dialect: DialectType = None,
1980        copy: bool = True,
1981        **opts,
1982    ) -> Union:
1983        """Append to or set the SELECT of the union recursively.
1984
1985        Example:
1986            >>> from sqlglot import parse_one
1987            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1988            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1989
1990        Args:
1991            *expressions: the SQL code strings to parse.
1992                If an `Expression` instance is passed, it will be used as-is.
1993            append: if `True`, add to any existing expressions.
1994                Otherwise, this resets the expressions.
1995            dialect: the dialect used to parse the input expressions.
1996            copy: if `False`, modify this expression instance in-place.
1997            opts: other options to use to parse the input expressions.
1998
1999        Returns:
2000            Union: the modified expression.
2001        """
2002        this = self.copy() if copy else self
2003        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2004        this.expression.unnest().select(
2005            *expressions, append=append, dialect=dialect, copy=False, **opts
2006        )
2007        return this
2008
2009    @property
2010    def named_selects(self):
2011        return self.this.unnest().named_selects
2012
2013    @property
2014    def is_star(self) -> bool:
2015        return self.this.is_star or self.expression.is_star
2016
2017    @property
2018    def selects(self):
2019        return self.this.unnest().selects
2020
2021    @property
2022    def left(self):
2023        return self.this
2024
2025    @property
2026    def right(self):
2027        return self.expression
def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1949    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1950        """
1951        Set the LIMIT expression.
1952
1953        Example:
1954            >>> select("1").union(select("1")).limit(1).sql()
1955            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1956
1957        Args:
1958            expression (str | int | Expression): the SQL code string to parse.
1959                This can also be an integer.
1960                If a `Limit` instance is passed, this is used as-is.
1961                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1962            dialect (str): the dialect used to parse the input expression.
1963            copy (bool): if `False`, modify this expression instance in-place.
1964            opts (kwargs): other options to use to parse the input expressions.
1965
1966        Returns:
1967            Select: The limited subqueryable.
1968        """
1969        return (
1970            select("*")
1971            .from_(self.subquery(alias="_l_0", copy=copy))
1972            .limit(expression, dialect=dialect, copy=False, **opts)
1973        )

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

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:
2125    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2126        """
2127        Set the GROUP BY expression.
2128
2129        Example:
2130            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2131            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2132
2133        Args:
2134            *expressions (str | Expression): the SQL code strings to parse.
2135                If a `Group` instance is passed, this is used as-is.
2136                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2137                If nothing is passed in then a group by is not applied to the expression
2138            append (bool): if `True`, add to any existing expressions.
2139                Otherwise, this flattens all the `Group` expression into a single expression.
2140            dialect (str): the dialect used to parse the input expression.
2141            copy (bool): if `False`, modify this expression instance in-place.
2142            opts (kwargs): other options to use to parse the input expressions.
2143
2144        Returns:
2145            Select: the modified expression.
2146        """
2147        if not expressions:
2148            return self if not copy else self.copy()
2149        return _apply_child_list_builder(
2150            *expressions,
2151            instance=self,
2152            arg="group",
2153            append=append,
2154            copy=copy,
2155            prefix="GROUP BY",
2156            into=Group,
2157            dialect=dialect,
2158            **opts,
2159        )

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

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

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:
2227    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2228        """
2229        Set the CLUSTER BY expression.
2230
2231        Example:
2232            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2233            'SELECT x FROM tbl CLUSTER BY x DESC'
2234
2235        Args:
2236            *expressions (str | Expression): the SQL code strings to parse.
2237                If a `Group` instance is passed, this is used as-is.
2238                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2239            append (bool): if `True`, add to any existing expressions.
2240                Otherwise, this flattens all the `Order` expression into a single expression.
2241            dialect (str): the dialect used to parse the input expression.
2242            copy (bool): if `False`, modify this expression instance in-place.
2243            opts (kwargs): other options to use to parse the input expressions.
2244
2245        Returns:
2246            Select: the modified expression.
2247        """
2248        return _apply_child_list_builder(
2249            *expressions,
2250            instance=self,
2251            arg="cluster",
2252            append=append,
2253            copy=copy,
2254            prefix="CLUSTER BY",
2255            into=Cluster,
2256            dialect=dialect,
2257            **opts,
2258        )

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:
2260    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2261        """
2262        Set the LIMIT expression.
2263
2264        Example:
2265            >>> Select().from_("tbl").select("x").limit(10).sql()
2266            'SELECT x FROM tbl LIMIT 10'
2267
2268        Args:
2269            expression (str | int | Expression): the SQL code string to parse.
2270                This can also be an integer.
2271                If a `Limit` instance is passed, this is used as-is.
2272                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2273            dialect (str): the dialect used to parse the input expression.
2274            copy (bool): if `False`, modify this expression instance in-place.
2275            opts (kwargs): other options to use to parse the input expressions.
2276
2277        Returns:
2278            Select: the modified expression.
2279        """
2280        return _apply_builder(
2281            expression=expression,
2282            instance=self,
2283            arg="limit",
2284            into=Limit,
2285            prefix="LIMIT",
2286            dialect=dialect,
2287            copy=copy,
2288            **opts,
2289        )

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:
2291    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2292        """
2293        Set the OFFSET expression.
2294
2295        Example:
2296            >>> Select().from_("tbl").select("x").offset(10).sql()
2297            'SELECT x FROM tbl OFFSET 10'
2298
2299        Args:
2300            expression (str | int | Expression): the SQL code string to parse.
2301                This can also be an integer.
2302                If a `Offset` instance is passed, this is used as-is.
2303                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2304            dialect (str): the dialect used to parse the input expression.
2305            copy (bool): if `False`, modify this expression instance in-place.
2306            opts (kwargs): other options to use to parse the input expressions.
2307
2308        Returns:
2309            Select: the modified expression.
2310        """
2311        return _apply_builder(
2312            expression=expression,
2313            instance=self,
2314            arg="offset",
2315            into=Offset,
2316            prefix="OFFSET",
2317            dialect=dialect,
2318            copy=copy,
2319            **opts,
2320        )

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:
2322    def select(
2323        self,
2324        *expressions: ExpOrStr,
2325        append: bool = True,
2326        dialect: DialectType = None,
2327        copy: bool = True,
2328        **opts,
2329    ) -> Select:
2330        """
2331        Append to or set the SELECT expressions.
2332
2333        Example:
2334            >>> Select().select("x", "y").sql()
2335            'SELECT x, y'
2336
2337        Args:
2338            *expressions: the SQL code strings to parse.
2339                If an `Expression` instance is passed, it will be used as-is.
2340            append: if `True`, add to any existing expressions.
2341                Otherwise, this resets the expressions.
2342            dialect: the dialect used to parse the input expressions.
2343            copy: if `False`, modify this expression instance in-place.
2344            opts: other options to use to parse the input expressions.
2345
2346        Returns:
2347            Select: the modified expression.
2348        """
2349        return _apply_list_builder(
2350            *expressions,
2351            instance=self,
2352            arg="expressions",
2353            append=append,
2354            dialect=dialect,
2355            copy=copy,
2356            **opts,
2357        )

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:
2359    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2360        """
2361        Append to or set the LATERAL expressions.
2362
2363        Example:
2364            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2365            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2366
2367        Args:
2368            *expressions (str | Expression): the SQL code strings to parse.
2369                If an `Expression` instance is passed, it will be used as-is.
2370            append (bool): if `True`, add to any existing expressions.
2371                Otherwise, this resets the expressions.
2372            dialect (str): the dialect used to parse the input expressions.
2373            copy (bool): if `False`, modify this expression instance in-place.
2374            opts (kwargs): other options to use to parse the input expressions.
2375
2376        Returns:
2377            Select: the modified expression.
2378        """
2379        return _apply_list_builder(
2380            *expressions,
2381            instance=self,
2382            arg="laterals",
2383            append=append,
2384            into=Lateral,
2385            prefix="LATERAL VIEW",
2386            dialect=dialect,
2387            copy=copy,
2388            **opts,
2389        )

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:
2391    def join(
2392        self,
2393        expression,
2394        on=None,
2395        using=None,
2396        append=True,
2397        join_type=None,
2398        join_alias=None,
2399        dialect=None,
2400        copy=True,
2401        **opts,
2402    ) -> Select:
2403        """
2404        Append to or set the JOIN expressions.
2405
2406        Example:
2407            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2408            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2409
2410            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2411            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2412
2413            Use `join_type` to change the type of join:
2414
2415            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2416            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2417
2418        Args:
2419            expression (str | Expression): the SQL code string to parse.
2420                If an `Expression` instance is passed, it will be used as-is.
2421            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2422                If an `Expression` instance is passed, it will be used as-is.
2423            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2424                If an `Expression` instance is passed, it will be used as-is.
2425            append (bool): if `True`, add to any existing expressions.
2426                Otherwise, this resets the expressions.
2427            join_type (str): If set, alter the parsed join type
2428            dialect (str): the dialect used to parse the input expressions.
2429            copy (bool): if `False`, modify this expression instance in-place.
2430            opts (kwargs): other options to use to parse the input expressions.
2431
2432        Returns:
2433            Select: the modified expression.
2434        """
2435        parse_args = {"dialect": dialect, **opts}
2436
2437        try:
2438            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2439        except ParseError:
2440            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2441
2442        join = expression if isinstance(expression, Join) else Join(this=expression)
2443
2444        if isinstance(join.this, Select):
2445            join.this.replace(join.this.subquery())
2446
2447        if join_type:
2448            natural: t.Optional[Token]
2449            side: t.Optional[Token]
2450            kind: t.Optional[Token]
2451
2452            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2453
2454            if natural:
2455                join.set("natural", True)
2456            if side:
2457                join.set("side", side.text)
2458            if kind:
2459                join.set("kind", kind.text)
2460
2461        if on:
2462            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2463            join.set("on", on)
2464
2465        if using:
2466            join = _apply_list_builder(
2467                *ensure_collection(using),
2468                instance=join,
2469                arg="using",
2470                append=append,
2471                copy=copy,
2472                **opts,
2473            )
2474
2475        if join_alias:
2476            join.set("this", alias_(join.this, join_alias, table=True))
2477        return _apply_list_builder(
2478            join,
2479            instance=self,
2480            arg="joins",
2481            append=append,
2482            copy=copy,
2483            **opts,
2484        )

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:
2486    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2487        """
2488        Append to or set the WHERE expressions.
2489
2490        Example:
2491            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2492            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2493
2494        Args:
2495            *expressions (str | Expression): the SQL code strings to parse.
2496                If an `Expression` instance is passed, it will be used as-is.
2497                Multiple expressions are combined with an AND operator.
2498            append (bool): if `True`, AND the new expressions to any existing expression.
2499                Otherwise, this resets the expression.
2500            dialect (str): the dialect used to parse the input expressions.
2501            copy (bool): if `False`, modify this expression instance in-place.
2502            opts (kwargs): other options to use to parse the input expressions.
2503
2504        Returns:
2505            Select: the modified expression.
2506        """
2507        return _apply_conjunction_builder(
2508            *expressions,
2509            instance=self,
2510            arg="where",
2511            append=append,
2512            into=Where,
2513            dialect=dialect,
2514            copy=copy,
2515            **opts,
2516        )

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:
2518    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2519        """
2520        Append to or set the HAVING expressions.
2521
2522        Example:
2523            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2524            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2525
2526        Args:
2527            *expressions (str | Expression): the SQL code strings to parse.
2528                If an `Expression` instance is passed, it will be used as-is.
2529                Multiple expressions are combined with an AND operator.
2530            append (bool): if `True`, AND the new expressions to any existing expression.
2531                Otherwise, this resets the expression.
2532            dialect (str): the dialect used to parse the input expressions.
2533            copy (bool): if `False`, modify this expression instance in-place.
2534            opts (kwargs): other options to use to parse the input expressions.
2535
2536        Returns:
2537            Select: the modified expression.
2538        """
2539        return _apply_conjunction_builder(
2540            *expressions,
2541            instance=self,
2542            arg="having",
2543            append=append,
2544            into=Having,
2545            dialect=dialect,
2546            copy=copy,
2547            **opts,
2548        )

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:
2550    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2551        return _apply_list_builder(
2552            *expressions,
2553            instance=self,
2554            arg="windows",
2555            append=append,
2556            into=Window,
2557            dialect=dialect,
2558            copy=copy,
2559            **opts,
2560        )
def qualify( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2562    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2563        return _apply_conjunction_builder(
2564            *expressions,
2565            instance=self,
2566            arg="qualify",
2567            append=append,
2568            into=Qualify,
2569            dialect=dialect,
2570            copy=copy,
2571            **opts,
2572        )
def distinct(self, distinct=True, copy=True) -> sqlglot.expressions.Select:
2574    def distinct(self, distinct=True, copy=True) -> Select:
2575        """
2576        Set the OFFSET expression.
2577
2578        Example:
2579            >>> Select().from_("tbl").select("x").distinct().sql()
2580            'SELECT DISTINCT x FROM tbl'
2581
2582        Args:
2583            distinct (bool): whether the Select should be distinct
2584            copy (bool): if `False`, modify this expression instance in-place.
2585
2586        Returns:
2587            Select: the modified expression.
2588        """
2589        instance = _maybe_copy(self, copy)
2590        instance.set("distinct", Distinct() if distinct else None)
2591        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:
2593    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2594        """
2595        Convert this expression to a CREATE TABLE AS statement.
2596
2597        Example:
2598            >>> Select().select("*").from_("tbl").ctas("x").sql()
2599            'CREATE TABLE x AS SELECT * FROM tbl'
2600
2601        Args:
2602            table (str | Expression): the SQL code string to parse as the table name.
2603                If another `Expression` instance is passed, it will be used as-is.
2604            properties (dict): an optional mapping of table properties
2605            dialect (str): the dialect used to parse the input table.
2606            copy (bool): if `False`, modify this expression instance in-place.
2607            opts (kwargs): other options to use to parse the input table.
2608
2609        Returns:
2610            Create: the CREATE TABLE AS expression
2611        """
2612        instance = _maybe_copy(self, copy)
2613        table_expression = maybe_parse(
2614            table,
2615            into=Table,
2616            dialect=dialect,
2617            **opts,
2618        )
2619        properties_expression = None
2620        if properties:
2621            properties_expression = Properties.from_dict(properties)
2622
2623        return Create(
2624            this=table_expression,
2625            kind="table",
2626            expression=instance,
2627            properties=properties_expression,
2628        )

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:
2630    def lock(self, update: bool = True, copy: bool = True) -> Select:
2631        """
2632        Set the locking read mode for this expression.
2633
2634        Examples:
2635            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2636            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2637
2638            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2639            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2640
2641        Args:
2642            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2643            copy: if `False`, modify this expression instance in-place.
2644
2645        Returns:
2646            The modified expression.
2647        """
2648
2649        inst = _maybe_copy(self, copy)
2650        inst.set("lock", Lock(update=update))
2651
2652        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):
2667class Subquery(DerivedTable, Unionable):
2668    arg_types = {
2669        "this": True,
2670        "alias": False,
2671        "with": False,
2672        **QUERY_MODIFIERS,
2673    }
2674
2675    def unnest(self):
2676        """
2677        Returns the first non subquery.
2678        """
2679        expression = self
2680        while isinstance(expression, Subquery):
2681            expression = expression.this
2682        return expression
2683
2684    @property
2685    def is_star(self) -> bool:
2686        return self.this.is_star
2687
2688    @property
2689    def output_name(self):
2690        return self.alias
def unnest(self):
2675    def unnest(self):
2676        """
2677        Returns the first non subquery.
2678        """
2679        expression = self
2680        while isinstance(expression, Subquery):
2681            expression = expression.this
2682        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):
2693class TableSample(Expression):
2694    arg_types = {
2695        "this": False,
2696        "method": False,
2697        "bucket_numerator": False,
2698        "bucket_denominator": False,
2699        "bucket_field": False,
2700        "percent": False,
2701        "rows": False,
2702        "size": False,
2703        "seed": False,
2704        "kind": False,
2705    }
class Tag(Expression):
2708class Tag(Expression):
2709    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2710
2711    arg_types = {
2712        "this": False,
2713        "prefix": False,
2714        "postfix": False,
2715    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2718class Pivot(Expression):
2719    arg_types = {
2720        "this": False,
2721        "alias": False,
2722        "expressions": True,
2723        "field": True,
2724        "unpivot": True,
2725    }
class Window(Expression):
2728class Window(Expression):
2729    arg_types = {
2730        "this": True,
2731        "partition_by": False,
2732        "order": False,
2733        "spec": False,
2734        "alias": False,
2735    }
class WindowSpec(Expression):
2738class WindowSpec(Expression):
2739    arg_types = {
2740        "kind": False,
2741        "start": False,
2742        "start_side": False,
2743        "end": False,
2744        "end_side": False,
2745    }
class Where(Expression):
2748class Where(Expression):
2749    pass
class Star(Expression):
2752class Star(Expression):
2753    arg_types = {"except": False, "replace": False}
2754
2755    @property
2756    def name(self) -> str:
2757        return "*"
2758
2759    @property
2760    def output_name(self):
2761        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):
2764class Parameter(Expression):
2765    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
2768class SessionParameter(Expression):
2769    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
2772class Placeholder(Expression):
2773    arg_types = {"this": False}
class Null(Condition):
2776class Null(Condition):
2777    arg_types: t.Dict[str, t.Any] = {}
2778
2779    @property
2780    def name(self) -> str:
2781        return "NULL"
class Boolean(Condition):
2784class Boolean(Condition):
2785    pass
class DataType(Expression):
2788class DataType(Expression):
2789    arg_types = {
2790        "this": True,
2791        "expressions": False,
2792        "nested": False,
2793        "values": False,
2794        "prefix": False,
2795    }
2796
2797    class Type(AutoName):
2798        CHAR = auto()
2799        NCHAR = auto()
2800        VARCHAR = auto()
2801        NVARCHAR = auto()
2802        TEXT = auto()
2803        MEDIUMTEXT = auto()
2804        LONGTEXT = auto()
2805        MEDIUMBLOB = auto()
2806        LONGBLOB = auto()
2807        BINARY = auto()
2808        VARBINARY = auto()
2809        INT = auto()
2810        UINT = auto()
2811        TINYINT = auto()
2812        UTINYINT = auto()
2813        SMALLINT = auto()
2814        USMALLINT = auto()
2815        BIGINT = auto()
2816        UBIGINT = auto()
2817        FLOAT = auto()
2818        DOUBLE = auto()
2819        DECIMAL = auto()
2820        BIT = auto()
2821        BOOLEAN = auto()
2822        JSON = auto()
2823        JSONB = auto()
2824        INTERVAL = auto()
2825        TIME = auto()
2826        TIMESTAMP = auto()
2827        TIMESTAMPTZ = auto()
2828        TIMESTAMPLTZ = auto()
2829        DATE = auto()
2830        DATETIME = auto()
2831        ARRAY = auto()
2832        MAP = auto()
2833        UUID = auto()
2834        GEOGRAPHY = auto()
2835        GEOMETRY = auto()
2836        STRUCT = auto()
2837        NULLABLE = auto()
2838        HLLSKETCH = auto()
2839        HSTORE = auto()
2840        SUPER = auto()
2841        SERIAL = auto()
2842        SMALLSERIAL = auto()
2843        BIGSERIAL = auto()
2844        XML = auto()
2845        UNIQUEIDENTIFIER = auto()
2846        MONEY = auto()
2847        SMALLMONEY = auto()
2848        ROWVERSION = auto()
2849        IMAGE = auto()
2850        VARIANT = auto()
2851        OBJECT = auto()
2852        INET = auto()
2853        NULL = auto()
2854        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2855
2856    TEXT_TYPES = {
2857        Type.CHAR,
2858        Type.NCHAR,
2859        Type.VARCHAR,
2860        Type.NVARCHAR,
2861        Type.TEXT,
2862    }
2863
2864    INTEGER_TYPES = {
2865        Type.INT,
2866        Type.TINYINT,
2867        Type.SMALLINT,
2868        Type.BIGINT,
2869    }
2870
2871    FLOAT_TYPES = {
2872        Type.FLOAT,
2873        Type.DOUBLE,
2874    }
2875
2876    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2877
2878    TEMPORAL_TYPES = {
2879        Type.TIMESTAMP,
2880        Type.TIMESTAMPTZ,
2881        Type.TIMESTAMPLTZ,
2882        Type.DATE,
2883        Type.DATETIME,
2884    }
2885
2886    @classmethod
2887    def build(
2888        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2889    ) -> DataType:
2890        from sqlglot import parse_one
2891
2892        if isinstance(dtype, str):
2893            if dtype.upper() in cls.Type.__members__:
2894                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2895            else:
2896                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2897            if data_type_exp is None:
2898                raise ValueError(f"Unparsable data type value: {dtype}")
2899        elif isinstance(dtype, DataType.Type):
2900            data_type_exp = DataType(this=dtype)
2901        elif isinstance(dtype, DataType):
2902            return dtype
2903        else:
2904            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2905        return DataType(**{**data_type_exp.args, **kwargs})
2906
2907    def is_type(self, dtype: DataType.Type) -> bool:
2908        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:
2886    @classmethod
2887    def build(
2888        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2889    ) -> DataType:
2890        from sqlglot import parse_one
2891
2892        if isinstance(dtype, str):
2893            if dtype.upper() in cls.Type.__members__:
2894                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2895            else:
2896                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2897            if data_type_exp is None:
2898                raise ValueError(f"Unparsable data type value: {dtype}")
2899        elif isinstance(dtype, DataType.Type):
2900            data_type_exp = DataType(this=dtype)
2901        elif isinstance(dtype, DataType):
2902            return dtype
2903        else:
2904            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2905        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
2907    def is_type(self, dtype: DataType.Type) -> bool:
2908        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
2797    class Type(AutoName):
2798        CHAR = auto()
2799        NCHAR = auto()
2800        VARCHAR = auto()
2801        NVARCHAR = auto()
2802        TEXT = auto()
2803        MEDIUMTEXT = auto()
2804        LONGTEXT = auto()
2805        MEDIUMBLOB = auto()
2806        LONGBLOB = auto()
2807        BINARY = auto()
2808        VARBINARY = auto()
2809        INT = auto()
2810        UINT = auto()
2811        TINYINT = auto()
2812        UTINYINT = auto()
2813        SMALLINT = auto()
2814        USMALLINT = auto()
2815        BIGINT = auto()
2816        UBIGINT = auto()
2817        FLOAT = auto()
2818        DOUBLE = auto()
2819        DECIMAL = auto()
2820        BIT = auto()
2821        BOOLEAN = auto()
2822        JSON = auto()
2823        JSONB = auto()
2824        INTERVAL = auto()
2825        TIME = auto()
2826        TIMESTAMP = auto()
2827        TIMESTAMPTZ = auto()
2828        TIMESTAMPLTZ = auto()
2829        DATE = auto()
2830        DATETIME = auto()
2831        ARRAY = auto()
2832        MAP = auto()
2833        UUID = auto()
2834        GEOGRAPHY = auto()
2835        GEOMETRY = auto()
2836        STRUCT = auto()
2837        NULLABLE = auto()
2838        HLLSKETCH = auto()
2839        HSTORE = auto()
2840        SUPER = auto()
2841        SERIAL = auto()
2842        SMALLSERIAL = auto()
2843        BIGSERIAL = auto()
2844        XML = auto()
2845        UNIQUEIDENTIFIER = auto()
2846        MONEY = auto()
2847        SMALLMONEY = auto()
2848        ROWVERSION = auto()
2849        IMAGE = auto()
2850        VARIANT = auto()
2851        OBJECT = auto()
2852        INET = auto()
2853        NULL = auto()
2854        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):
2912class PseudoType(Expression):
2913    pass
class StructKwarg(Expression):
2916class StructKwarg(Expression):
2917    arg_types = {"this": True, "expression": True}
class SubqueryPredicate(Predicate):
2921class SubqueryPredicate(Predicate):
2922    pass
class All(SubqueryPredicate):
2925class All(SubqueryPredicate):
2926    pass
class Any(SubqueryPredicate):
2929class Any(SubqueryPredicate):
2930    pass
class Exists(SubqueryPredicate):
2933class Exists(SubqueryPredicate):
2934    pass
class Command(Expression):
2939class Command(Expression):
2940    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
2943class Transaction(Expression):
2944    arg_types = {"this": False, "modes": False}
class Commit(Expression):
2947class Commit(Expression):
2948    arg_types = {"chain": False}
class Rollback(Expression):
2951class Rollback(Expression):
2952    arg_types = {"savepoint": False}
class AlterTable(Expression):
2955class AlterTable(Expression):
2956    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
2959class AddConstraint(Expression):
2960    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
2963class DropPartition(Expression):
2964    arg_types = {"expressions": True, "exists": False}
class Binary(Expression):
2968class Binary(Expression):
2969    arg_types = {"this": True, "expression": True}
2970
2971    @property
2972    def left(self):
2973        return self.this
2974
2975    @property
2976    def right(self):
2977        return self.expression
class Add(Binary):
2980class Add(Binary):
2981    pass
class Connector(Binary, Condition):
2984class Connector(Binary, Condition):
2985    pass
class And(Connector):
2988class And(Connector):
2989    pass
class Or(Connector):
2992class Or(Connector):
2993    pass
class BitwiseAnd(Binary):
2996class BitwiseAnd(Binary):
2997    pass
class BitwiseLeftShift(Binary):
3000class BitwiseLeftShift(Binary):
3001    pass
class BitwiseOr(Binary):
3004class BitwiseOr(Binary):
3005    pass
class BitwiseRightShift(Binary):
3008class BitwiseRightShift(Binary):
3009    pass
class BitwiseXor(Binary):
3012class BitwiseXor(Binary):
3013    pass
class Div(Binary):
3016class Div(Binary):
3017    pass
class Overlaps(Binary):
3020class Overlaps(Binary):
3021    pass
class Dot(Binary):
3024class Dot(Binary):
3025    @property
3026    def name(self) -> str:
3027        return self.expression.name
3028
3029    @classmethod
3030    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3031        """Build a Dot object with a sequence of expressions."""
3032        if len(expressions) < 2:
3033            raise ValueError(f"Dot requires >= 2 expressions.")
3034
3035        a, b, *expressions = expressions
3036        dot = Dot(this=a, expression=b)
3037
3038        for expression in expressions:
3039            dot = Dot(this=dot, expression=expression)
3040
3041        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3029    @classmethod
3030    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3031        """Build a Dot object with a sequence of expressions."""
3032        if len(expressions) < 2:
3033            raise ValueError(f"Dot requires >= 2 expressions.")
3034
3035        a, b, *expressions = expressions
3036        dot = Dot(this=a, expression=b)
3037
3038        for expression in expressions:
3039            dot = Dot(this=dot, expression=expression)
3040
3041        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3044class DPipe(Binary):
3045    pass
class EQ(Binary, Predicate):
3048class EQ(Binary, Predicate):
3049    pass
class NullSafeEQ(Binary, Predicate):
3052class NullSafeEQ(Binary, Predicate):
3053    pass
class NullSafeNEQ(Binary, Predicate):
3056class NullSafeNEQ(Binary, Predicate):
3057    pass
class Distance(Binary):
3060class Distance(Binary):
3061    pass
class Escape(Binary):
3064class Escape(Binary):
3065    pass
class Glob(Binary, Predicate):
3068class Glob(Binary, Predicate):
3069    pass
class GT(Binary, Predicate):
3072class GT(Binary, Predicate):
3073    pass
class GTE(Binary, Predicate):
3076class GTE(Binary, Predicate):
3077    pass
class ILike(Binary, Predicate):
3080class ILike(Binary, Predicate):
3081    pass
class ILikeAny(Binary, Predicate):
3084class ILikeAny(Binary, Predicate):
3085    pass
class IntDiv(Binary):
3088class IntDiv(Binary):
3089    pass
class Is(Binary, Predicate):
3092class Is(Binary, Predicate):
3093    pass
class Kwarg(Binary):
3096class Kwarg(Binary):
3097    """Kwarg in special functions like func(kwarg => y)."""

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

class Like(Binary, Predicate):
3100class Like(Binary, Predicate):
3101    pass
class LikeAny(Binary, Predicate):
3104class LikeAny(Binary, Predicate):
3105    pass
class LT(Binary, Predicate):
3108class LT(Binary, Predicate):
3109    pass
class LTE(Binary, Predicate):
3112class LTE(Binary, Predicate):
3113    pass
class Mod(Binary):
3116class Mod(Binary):
3117    pass
class Mul(Binary):
3120class Mul(Binary):
3121    pass
class NEQ(Binary, Predicate):
3124class NEQ(Binary, Predicate):
3125    pass
class SimilarTo(Binary, Predicate):
3128class SimilarTo(Binary, Predicate):
3129    pass
class Slice(Binary):
3132class Slice(Binary):
3133    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3136class Sub(Binary):
3137    pass
class ArrayOverlaps(Binary):
3140class ArrayOverlaps(Binary):
3141    pass
class Unary(Expression):
3146class Unary(Expression):
3147    pass
class BitwiseNot(Unary):
3150class BitwiseNot(Unary):
3151    pass
class Not(Unary, Condition):
3154class Not(Unary, Condition):
3155    pass
class Paren(Unary, Condition):
3158class Paren(Unary, Condition):
3159    arg_types = {"this": True, "with": False}
class Neg(Unary):
3162class Neg(Unary):
3163    pass
class Alias(Expression):
3167class Alias(Expression):
3168    arg_types = {"this": True, "alias": False}
3169
3170    @property
3171    def output_name(self):
3172        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):
3175class Aliases(Expression):
3176    arg_types = {"this": True, "expressions": True}
3177
3178    @property
3179    def aliases(self):
3180        return self.expressions
class AtTimeZone(Expression):
3183class AtTimeZone(Expression):
3184    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3187class Between(Predicate):
3188    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3191class Bracket(Condition):
3192    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3195class Distinct(Expression):
3196    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3199class In(Predicate):
3200    arg_types = {
3201        "this": True,
3202        "expressions": False,
3203        "query": False,
3204        "unnest": False,
3205        "field": False,
3206        "is_global": False,
3207    }
class TimeUnit(Expression):
3210class TimeUnit(Expression):
3211    """Automatically converts unit arg into a var."""
3212
3213    arg_types = {"unit": False}
3214
3215    def __init__(self, **args):
3216        unit = args.get("unit")
3217        if isinstance(unit, (Column, Literal)):
3218            args["unit"] = Var(this=unit.name)
3219        elif isinstance(unit, Week):
3220            unit.set("this", Var(this=unit.this.name))
3221        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3215    def __init__(self, **args):
3216        unit = args.get("unit")
3217        if isinstance(unit, (Column, Literal)):
3218            args["unit"] = Var(this=unit.name)
3219        elif isinstance(unit, Week):
3220            unit.set("this", Var(this=unit.this.name))
3221        super().__init__(**args)
class Interval(TimeUnit):
3224class Interval(TimeUnit):
3225    arg_types = {"this": False, "unit": False}
class IgnoreNulls(Expression):
3228class IgnoreNulls(Expression):
3229    pass
class RespectNulls(Expression):
3232class RespectNulls(Expression):
3233    pass
class Func(Condition):
3237class Func(Condition):
3238    """
3239    The base class for all function expressions.
3240
3241    Attributes:
3242        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3243            treated as a variable length argument and the argument's value will be stored as a list.
3244        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3245            for this function expression. These values are used to map this node to a name during parsing
3246            as well as to provide the function's name during SQL string generation. By default the SQL
3247            name is set to the expression's class name transformed to snake case.
3248    """
3249
3250    is_var_len_args = False
3251
3252    @classmethod
3253    def from_arg_list(cls, args):
3254        if cls.is_var_len_args:
3255            all_arg_keys = list(cls.arg_types)
3256            # If this function supports variable length argument treat the last argument as such.
3257            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3258            num_non_var = len(non_var_len_arg_keys)
3259
3260            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3261            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3262        else:
3263            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3264
3265        return cls(**args_dict)
3266
3267    @classmethod
3268    def sql_names(cls):
3269        if cls is Func:
3270            raise NotImplementedError(
3271                "SQL name is only supported by concrete function implementations"
3272            )
3273        if "_sql_names" not in cls.__dict__:
3274            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3275        return cls._sql_names
3276
3277    @classmethod
3278    def sql_name(cls):
3279        return cls.sql_names()[0]
3280
3281    @classmethod
3282    def default_parser_mappings(cls):
3283        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):
3252    @classmethod
3253    def from_arg_list(cls, args):
3254        if cls.is_var_len_args:
3255            all_arg_keys = list(cls.arg_types)
3256            # If this function supports variable length argument treat the last argument as such.
3257            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3258            num_non_var = len(non_var_len_arg_keys)
3259
3260            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3261            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3262        else:
3263            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3264
3265        return cls(**args_dict)
@classmethod
def sql_names(cls):
3267    @classmethod
3268    def sql_names(cls):
3269        if cls is Func:
3270            raise NotImplementedError(
3271                "SQL name is only supported by concrete function implementations"
3272            )
3273        if "_sql_names" not in cls.__dict__:
3274            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3275        return cls._sql_names
@classmethod
def sql_name(cls):
3277    @classmethod
3278    def sql_name(cls):
3279        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3281    @classmethod
3282    def default_parser_mappings(cls):
3283        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3286class AggFunc(Func):
3287    pass
class Abs(Func):
3290class Abs(Func):
3291    pass
class Anonymous(Func):
3294class Anonymous(Func):
3295    arg_types = {"this": True, "expressions": False}
3296    is_var_len_args = True
class Hll(AggFunc):
3301class Hll(AggFunc):
3302    arg_types = {"this": True, "expressions": False}
3303    is_var_len_args = True
class ApproxDistinct(AggFunc):
3306class ApproxDistinct(AggFunc):
3307    arg_types = {"this": True, "accuracy": False}
class Array(Func):
3310class Array(Func):
3311    arg_types = {"expressions": False}
3312    is_var_len_args = True
class ToChar(Func):
3316class ToChar(Func):
3317    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3320class GenerateSeries(Func):
3321    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3324class ArrayAgg(AggFunc):
3325    pass
class ArrayAll(Func):
3328class ArrayAll(Func):
3329    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3332class ArrayAny(Func):
3333    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3336class ArrayConcat(Func):
3337    arg_types = {"this": True, "expressions": False}
3338    is_var_len_args = True
class ArrayContains(Binary, Func):
3341class ArrayContains(Binary, Func):
3342    pass
class ArrayContained(Binary):
3345class ArrayContained(Binary):
3346    pass
class ArrayFilter(Func):
3349class ArrayFilter(Func):
3350    arg_types = {"this": True, "expression": True}
3351    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3354class ArrayJoin(Func):
3355    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3358class ArraySize(Func):
3359    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3362class ArraySort(Func):
3363    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3366class ArraySum(Func):
3367    pass
class ArrayUnionAgg(AggFunc):
3370class ArrayUnionAgg(AggFunc):
3371    pass
class Avg(AggFunc):
3374class Avg(AggFunc):
3375    pass
class AnyValue(AggFunc):
3378class AnyValue(AggFunc):
3379    pass
class Case(Func):
3382class Case(Func):
3383    arg_types = {"this": False, "ifs": True, "default": False}
class Cast(Func):
3386class Cast(Func):
3387    arg_types = {"this": True, "to": True}
3388
3389    @property
3390    def name(self) -> str:
3391        return self.this.name
3392
3393    @property
3394    def to(self):
3395        return self.args["to"]
3396
3397    @property
3398    def output_name(self):
3399        return self.name
3400
3401    def is_type(self, dtype: DataType.Type) -> bool:
3402        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:
3401    def is_type(self, dtype: DataType.Type) -> bool:
3402        return self.to.is_type(dtype)
class Collate(Binary):
3405class Collate(Binary):
3406    pass
class TryCast(Cast):
3409class TryCast(Cast):
3410    pass
class Ceil(Func):
3413class Ceil(Func):
3414    arg_types = {"this": True, "decimals": False}
3415    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3418class Coalesce(Func):
3419    arg_types = {"this": True, "expressions": False}
3420    is_var_len_args = True
class Concat(Func):
3423class Concat(Func):
3424    arg_types = {"expressions": True}
3425    is_var_len_args = True
class ConcatWs(Concat):
3428class ConcatWs(Concat):
3429    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3432class Count(AggFunc):
3433    arg_types = {"this": False}
class CountIf(AggFunc):
3436class CountIf(AggFunc):
3437    pass
class CurrentDate(Func):
3440class CurrentDate(Func):
3441    arg_types = {"this": False}
class CurrentDatetime(Func):
3444class CurrentDatetime(Func):
3445    arg_types = {"this": False}
class CurrentTime(Func):
3448class CurrentTime(Func):
3449    arg_types = {"this": False}
class CurrentTimestamp(Func):
3452class CurrentTimestamp(Func):
3453    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3456class DateAdd(Func, TimeUnit):
3457    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3460class DateSub(Func, TimeUnit):
3461    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3464class DateDiff(Func, TimeUnit):
3465    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3466    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3469class DateTrunc(Func):
3470    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3473class DatetimeAdd(Func, TimeUnit):
3474    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3477class DatetimeSub(Func, TimeUnit):
3478    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3481class DatetimeDiff(Func, TimeUnit):
3482    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3485class DatetimeTrunc(Func, TimeUnit):
3486    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3489class DayOfWeek(Func):
3490    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3493class DayOfMonth(Func):
3494    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3497class DayOfYear(Func):
3498    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3501class WeekOfYear(Func):
3502    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3505class LastDateOfMonth(Func):
3506    pass
class Extract(Func):
3509class Extract(Func):
3510    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3513class TimestampAdd(Func, TimeUnit):
3514    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3517class TimestampSub(Func, TimeUnit):
3518    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3521class TimestampDiff(Func, TimeUnit):
3522    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3525class TimestampTrunc(Func, TimeUnit):
3526    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3529class TimeAdd(Func, TimeUnit):
3530    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3533class TimeSub(Func, TimeUnit):
3534    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3537class TimeDiff(Func, TimeUnit):
3538    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3541class TimeTrunc(Func, TimeUnit):
3542    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3545class DateFromParts(Func):
3546    _sql_names = ["DATEFROMPARTS"]
3547    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3550class DateStrToDate(Func):
3551    pass
class DateToDateStr(Func):
3554class DateToDateStr(Func):
3555    pass
class DateToDi(Func):
3558class DateToDi(Func):
3559    pass
class Day(Func):
3562class Day(Func):
3563    pass
class Decode(Func):
3566class Decode(Func):
3567    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3570class DiToDate(Func):
3571    pass
class Encode(Func):
3574class Encode(Func):
3575    arg_types = {"this": True, "charset": True}
class Exp(Func):
3578class Exp(Func):
3579    pass
class Explode(Func):
3582class Explode(Func):
3583    pass
class ExponentialTimeDecayedAvg(AggFunc):
3586class ExponentialTimeDecayedAvg(AggFunc):
3587    arg_types = {"this": True, "time": False, "decay": False}
class Floor(Func):
3590class Floor(Func):
3591    arg_types = {"this": True, "decimals": False}
class Greatest(Func):
3594class Greatest(Func):
3595    arg_types = {"this": True, "expressions": False}
3596    is_var_len_args = True
class GroupConcat(Func):
3599class GroupConcat(Func):
3600    arg_types = {"this": True, "separator": False}
class GroupUniqArray(AggFunc):
3603class GroupUniqArray(AggFunc):
3604    arg_types = {"this": True, "size": False}
class Hex(Func):
3607class Hex(Func):
3608    pass
class Histogram(AggFunc):
3611class Histogram(AggFunc):
3612    arg_types = {"this": True, "bins": False}
class If(Func):
3615class If(Func):
3616    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3619class IfNull(Func):
3620    arg_types = {"this": True, "expression": False}
3621    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3624class Initcap(Func):
3625    pass
class JSONKeyValue(Expression):
3628class JSONKeyValue(Expression):
3629    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
3632class JSONObject(Func):
3633    arg_types = {
3634        "expressions": False,
3635        "null_handling": False,
3636        "unique_keys": False,
3637        "return_type": False,
3638        "format_json": False,
3639        "encoding": False,
3640    }
class JSONBContains(Binary):
3643class JSONBContains(Binary):
3644    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3647class JSONExtract(Binary, Func):
3648    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3651class JSONExtractScalar(JSONExtract):
3652    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3655class JSONBExtract(JSONExtract):
3656    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3659class JSONBExtractScalar(JSONExtract):
3660    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
3663class JSONFormat(Func):
3664    arg_types = {"this": False, "options": False}
3665    _sql_names = ["JSON_FORMAT"]
class Least(Func):
3668class Least(Func):
3669    arg_types = {"expressions": False}
3670    is_var_len_args = True
class Length(Func):
3673class Length(Func):
3674    pass
class Levenshtein(Func):
3677class Levenshtein(Func):
3678    arg_types = {
3679        "this": True,
3680        "expression": False,
3681        "ins_cost": False,
3682        "del_cost": False,
3683        "sub_cost": False,
3684    }
class Ln(Func):
3687class Ln(Func):
3688    pass
class Log(Func):
3691class Log(Func):
3692    arg_types = {"this": True, "expression": False}
class Log2(Func):
3695class Log2(Func):
3696    pass
class Log10(Func):
3699class Log10(Func):
3700    pass
class LogicalOr(AggFunc):
3703class LogicalOr(AggFunc):
3704    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
3707class LogicalAnd(AggFunc):
3708    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
3711class Lower(Func):
3712    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
3715class Map(Func):
3716    arg_types = {"keys": False, "values": False}
class VarMap(Func):
3719class VarMap(Func):
3720    arg_types = {"keys": True, "values": True}
3721    is_var_len_args = True
class MatchAgainst(Func):
3725class MatchAgainst(Func):
3726    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
3729class Max(AggFunc):
3730    arg_types = {"this": True, "expressions": False}
3731    is_var_len_args = True
class Min(AggFunc):
3734class Min(AggFunc):
3735    arg_types = {"this": True, "expressions": False}
3736    is_var_len_args = True
class Month(Func):
3739class Month(Func):
3740    pass
class Nvl2(Func):
3743class Nvl2(Func):
3744    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
3747class Posexplode(Func):
3748    pass
class Pow(Binary, Func):
3751class Pow(Binary, Func):
3752    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
3755class PercentileCont(AggFunc):
3756    pass
class PercentileDisc(AggFunc):
3759class PercentileDisc(AggFunc):
3760    pass
class Quantile(AggFunc):
3763class Quantile(AggFunc):
3764    arg_types = {"this": True, "quantile": True}
class Quantiles(AggFunc):
3769class Quantiles(AggFunc):
3770    arg_types = {"parameters": True, "expressions": True}
3771    is_var_len_args = True
class QuantileIf(AggFunc):
3774class QuantileIf(AggFunc):
3775    arg_types = {"parameters": True, "expressions": True}
class ApproxQuantile(Quantile):
3778class ApproxQuantile(Quantile):
3779    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
3782class RangeN(Func):
3783    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
3786class ReadCSV(Func):
3787    _sql_names = ["READ_CSV"]
3788    is_var_len_args = True
3789    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
3792class Reduce(Func):
3793    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
3796class RegexpExtract(Func):
3797    arg_types = {
3798        "this": True,
3799        "expression": True,
3800        "position": False,
3801        "occurrence": False,
3802        "group": False,
3803    }
class RegexpLike(Func):
3806class RegexpLike(Func):
3807    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
3810class RegexpILike(Func):
3811    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
3816class RegexpSplit(Func):
3817    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
3820class Repeat(Func):
3821    arg_types = {"this": True, "times": True}
class Round(Func):
3824class Round(Func):
3825    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
3828class RowNumber(Func):
3829    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
3832class SafeDivide(Func):
3833    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
3836class SetAgg(AggFunc):
3837    pass
class SortArray(Func):
3840class SortArray(Func):
3841    arg_types = {"this": True, "asc": False}
class Split(Func):
3844class Split(Func):
3845    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
3850class Substring(Func):
3851    arg_types = {"this": True, "start": False, "length": False}
class StrPosition(Func):
3854class StrPosition(Func):
3855    arg_types = {
3856        "this": True,
3857        "substr": True,
3858        "position": False,
3859        "instance": False,
3860    }
class StrToDate(Func):
3863class StrToDate(Func):
3864    arg_types = {"this": True, "format": True}
class StrToTime(Func):
3867class StrToTime(Func):
3868    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
3873class StrToUnix(Func):
3874    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
3877class NumberToStr(Func):
3878    arg_types = {"this": True, "format": True}
class Struct(Func):
3881class Struct(Func):
3882    arg_types = {"expressions": True}
3883    is_var_len_args = True
class StructExtract(Func):
3886class StructExtract(Func):
3887    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
3890class Sum(AggFunc):
3891    pass
class Sqrt(Func):
3894class Sqrt(Func):
3895    pass
class Stddev(AggFunc):
3898class Stddev(AggFunc):
3899    pass
class StddevPop(AggFunc):
3902class StddevPop(AggFunc):
3903    pass
class StddevSamp(AggFunc):
3906class StddevSamp(AggFunc):
3907    pass
class TimeToStr(Func):
3910class TimeToStr(Func):
3911    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
3914class TimeToTimeStr(Func):
3915    pass
class TimeToUnix(Func):
3918class TimeToUnix(Func):
3919    pass
class TimeStrToDate(Func):
3922class TimeStrToDate(Func):
3923    pass
class TimeStrToTime(Func):
3926class TimeStrToTime(Func):
3927    pass
class TimeStrToUnix(Func):
3930class TimeStrToUnix(Func):
3931    pass
class Trim(Func):
3934class Trim(Func):
3935    arg_types = {
3936        "this": True,
3937        "expression": False,
3938        "position": False,
3939        "collation": False,
3940    }
class TsOrDsAdd(Func, TimeUnit):
3943class TsOrDsAdd(Func, TimeUnit):
3944    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
3947class TsOrDsToDateStr(Func):
3948    pass
class TsOrDsToDate(Func):
3951class TsOrDsToDate(Func):
3952    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
3955class TsOrDiToDi(Func):
3956    pass
class Unhex(Func):
3959class Unhex(Func):
3960    pass
class UnixToStr(Func):
3963class UnixToStr(Func):
3964    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
3969class UnixToTime(Func):
3970    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
3971
3972    SECONDS = Literal.string("seconds")
3973    MILLIS = Literal.string("millis")
3974    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
3977class UnixToTimeStr(Func):
3978    pass
class Upper(Func):
3981class Upper(Func):
3982    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
3985class Variance(AggFunc):
3986    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
3989class VariancePop(AggFunc):
3990    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
3993class Week(Func):
3994    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
3997class XMLTable(Func):
3998    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4001class Year(Func):
4002    pass
class Use(Expression):
4005class Use(Expression):
4006    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4009class Merge(Expression):
4010    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4013class When(Func):
4014    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:
4025def maybe_parse(
4026    sql_or_expression: ExpOrStr,
4027    *,
4028    into: t.Optional[IntoType] = None,
4029    dialect: DialectType = None,
4030    prefix: t.Optional[str] = None,
4031    copy: bool = False,
4032    **opts,
4033) -> Expression:
4034    """Gracefully handle a possible string or expression.
4035
4036    Example:
4037        >>> maybe_parse("1")
4038        (LITERAL this: 1, is_string: False)
4039        >>> maybe_parse(to_identifier("x"))
4040        (IDENTIFIER this: x, quoted: False)
4041
4042    Args:
4043        sql_or_expression: the SQL code string or an expression
4044        into: the SQLGlot Expression to parse into
4045        dialect: the dialect used to parse the input expressions (in the case that an
4046            input expression is a SQL string).
4047        prefix: a string to prefix the sql with before it gets parsed
4048            (automatically includes a space)
4049        copy: whether or not to copy the expression.
4050        **opts: other options to use to parse the input expressions (again, in the case
4051            that an input expression is a SQL string).
4052
4053    Returns:
4054        Expression: the parsed or given expression.
4055    """
4056    if isinstance(sql_or_expression, Expression):
4057        if copy:
4058            return sql_or_expression.copy()
4059        return sql_or_expression
4060
4061    import sqlglot
4062
4063    sql = str(sql_or_expression)
4064    if prefix:
4065        sql = f"{prefix} {sql}"
4066    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):
4212def union(left, right, distinct=True, dialect=None, **opts):
4213    """
4214    Initializes a syntax tree from one UNION expression.
4215
4216    Example:
4217        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4218        'SELECT * FROM foo UNION SELECT * FROM bla'
4219
4220    Args:
4221        left (str | Expression): the SQL code string corresponding to the left-hand side.
4222            If an `Expression` instance is passed, it will be used as-is.
4223        right (str | Expression): the SQL code string corresponding to the right-hand side.
4224            If an `Expression` instance is passed, it will be used as-is.
4225        distinct (bool): set the DISTINCT flag if and only if this is true.
4226        dialect (str): the dialect used to parse the input expression.
4227        opts (kwargs): other options to use to parse the input expressions.
4228    Returns:
4229        Union: the syntax tree for the UNION expression.
4230    """
4231    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4232    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4233
4234    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):
4237def intersect(left, right, distinct=True, dialect=None, **opts):
4238    """
4239    Initializes a syntax tree from one INTERSECT expression.
4240
4241    Example:
4242        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4243        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4244
4245    Args:
4246        left (str | Expression): the SQL code string corresponding to the left-hand side.
4247            If an `Expression` instance is passed, it will be used as-is.
4248        right (str | Expression): the SQL code string corresponding to the right-hand side.
4249            If an `Expression` instance is passed, it will be used as-is.
4250        distinct (bool): set the DISTINCT flag if and only if this is true.
4251        dialect (str): the dialect used to parse the input expression.
4252        opts (kwargs): other options to use to parse the input expressions.
4253    Returns:
4254        Intersect: the syntax tree for the INTERSECT expression.
4255    """
4256    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4257    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4258
4259    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):
4262def except_(left, right, distinct=True, dialect=None, **opts):
4263    """
4264    Initializes a syntax tree from one EXCEPT expression.
4265
4266    Example:
4267        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4268        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4269
4270    Args:
4271        left (str | Expression): the SQL code string corresponding to the left-hand side.
4272            If an `Expression` instance is passed, it will be used as-is.
4273        right (str | Expression): the SQL code string corresponding to the right-hand side.
4274            If an `Expression` instance is passed, it will be used as-is.
4275        distinct (bool): set the DISTINCT flag if and only if this is true.
4276        dialect (str): the dialect used to parse the input expression.
4277        opts (kwargs): other options to use to parse the input expressions.
4278    Returns:
4279        Except: the syntax tree for the EXCEPT statement.
4280    """
4281    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4282    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4283
4284    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:
4287def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4288    """
4289    Initializes a syntax tree from one or multiple SELECT expressions.
4290
4291    Example:
4292        >>> select("col1", "col2").from_("tbl").sql()
4293        'SELECT col1, col2 FROM tbl'
4294
4295    Args:
4296        *expressions: the SQL code string to parse as the expressions of a
4297            SELECT statement. If an Expression instance is passed, this is used as-is.
4298        dialect: the dialect used to parse the input expressions (in the case that an
4299            input expression is a SQL string).
4300        **opts: other options to use to parse the input expressions (again, in the case
4301            that an input expression is a SQL string).
4302
4303    Returns:
4304        Select: the syntax tree for the SELECT statement.
4305    """
4306    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:
4309def from_(*expressions, dialect=None, **opts) -> Select:
4310    """
4311    Initializes a syntax tree from a FROM expression.
4312
4313    Example:
4314        >>> from_("tbl").select("col1", "col2").sql()
4315        'SELECT col1, col2 FROM tbl'
4316
4317    Args:
4318        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4319            SELECT statement. If an Expression instance is passed, this is used as-is.
4320        dialect (str): the dialect used to parse the input expression (in the case that the
4321            input expression is a SQL string).
4322        **opts: other options to use to parse the input expressions (again, in the case
4323            that the input expression is a SQL string).
4324
4325    Returns:
4326        Select: the syntax tree for the SELECT statement.
4327    """
4328    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:
4331def update(
4332    table: str | Table,
4333    properties: dict,
4334    where: t.Optional[ExpOrStr] = None,
4335    from_: t.Optional[ExpOrStr] = None,
4336    dialect: DialectType = None,
4337    **opts,
4338) -> Update:
4339    """
4340    Creates an update statement.
4341
4342    Example:
4343        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4344        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4345
4346    Args:
4347        *properties: dictionary of properties to set which are
4348            auto converted to sql objects eg None -> NULL
4349        where: sql conditional parsed into a WHERE statement
4350        from_: sql statement parsed into a FROM statement
4351        dialect: the dialect used to parse the input expressions.
4352        **opts: other options to use to parse the input expressions.
4353
4354    Returns:
4355        Update: the syntax tree for the UPDATE statement.
4356    """
4357    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4358    update_expr.set(
4359        "expressions",
4360        [
4361            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4362            for k, v in properties.items()
4363        ],
4364    )
4365    if from_:
4366        update_expr.set(
4367            "from",
4368            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4369        )
4370    if isinstance(where, Condition):
4371        where = Where(this=where)
4372    if where:
4373        update_expr.set(
4374            "where",
4375            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4376        )
4377    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:
4380def delete(
4381    table: ExpOrStr,
4382    where: t.Optional[ExpOrStr] = None,
4383    returning: t.Optional[ExpOrStr] = None,
4384    dialect: DialectType = None,
4385    **opts,
4386) -> Delete:
4387    """
4388    Builds a delete statement.
4389
4390    Example:
4391        >>> delete("my_table", where="id > 1").sql()
4392        'DELETE FROM my_table WHERE id > 1'
4393
4394    Args:
4395        where: sql conditional parsed into a WHERE statement
4396        returning: sql conditional parsed into a RETURNING statement
4397        dialect: the dialect used to parse the input expressions.
4398        **opts: other options to use to parse the input expressions.
4399
4400    Returns:
4401        Delete: the syntax tree for the DELETE statement.
4402    """
4403    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4404    if where:
4405        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4406    if returning:
4407        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4408    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:
4411def condition(expression, dialect=None, **opts) -> Condition:
4412    """
4413    Initialize a logical condition expression.
4414
4415    Example:
4416        >>> condition("x=1").sql()
4417        'x = 1'
4418
4419        This is helpful for composing larger logical syntax trees:
4420        >>> where = condition("x=1")
4421        >>> where = where.and_("y=1")
4422        >>> Select().from_("tbl").select("*").where(where).sql()
4423        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4424
4425    Args:
4426        *expression (str | Expression): the SQL code string to parse.
4427            If an Expression instance is passed, this is used as-is.
4428        dialect (str): the dialect used to parse the input expression (in the case that the
4429            input expression is a SQL string).
4430        **opts: other options to use to parse the input expressions (again, in the case
4431            that the input expression is a SQL string).
4432
4433    Returns:
4434        Condition: the expression
4435    """
4436    return maybe_parse(  # type: ignore
4437        expression,
4438        into=Condition,
4439        dialect=dialect,
4440        **opts,
4441    )

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:
4444def and_(*expressions, dialect=None, **opts) -> And:
4445    """
4446    Combine multiple conditions with an AND logical operator.
4447
4448    Example:
4449        >>> and_("x=1", and_("y=1", "z=1")).sql()
4450        'x = 1 AND (y = 1 AND z = 1)'
4451
4452    Args:
4453        *expressions (str | Expression): the SQL code strings to parse.
4454            If an Expression instance is passed, this is used as-is.
4455        dialect (str): the dialect used to parse the input expression.
4456        **opts: other options to use to parse the input expressions.
4457
4458    Returns:
4459        And: the new condition
4460    """
4461    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:
4464def or_(*expressions, dialect=None, **opts) -> Or:
4465    """
4466    Combine multiple conditions with an OR logical operator.
4467
4468    Example:
4469        >>> or_("x=1", or_("y=1", "z=1")).sql()
4470        'x = 1 OR (y = 1 OR z = 1)'
4471
4472    Args:
4473        *expressions (str | Expression): the SQL code strings to parse.
4474            If an Expression instance is passed, this is used as-is.
4475        dialect (str): the dialect used to parse the input expression.
4476        **opts: other options to use to parse the input expressions.
4477
4478    Returns:
4479        Or: the new condition
4480    """
4481    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:
4484def not_(expression, dialect=None, **opts) -> Not:
4485    """
4486    Wrap a condition with a NOT operator.
4487
4488    Example:
4489        >>> not_("this_suit='black'").sql()
4490        "NOT this_suit = 'black'"
4491
4492    Args:
4493        expression (str | Expression): the SQL code strings to parse.
4494            If an Expression instance is passed, this is used as-is.
4495        dialect (str): the dialect used to parse the input expression.
4496        **opts: other options to use to parse the input expressions.
4497
4498    Returns:
4499        Not: the new condition
4500    """
4501    this = condition(
4502        expression,
4503        dialect=dialect,
4504        **opts,
4505    )
4506    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:
4509def paren(expression) -> Paren:
4510    return Paren(this=expression)
def to_identifier(name, quoted=None):
4526def to_identifier(name, quoted=None):
4527    """Builds an identifier.
4528
4529    Args:
4530        name: The name to turn into an identifier.
4531        quoted: Whether or not force quote the identifier.
4532
4533    Returns:
4534        The identifier ast node.
4535    """
4536
4537    if name is None:
4538        return None
4539
4540    if isinstance(name, Identifier):
4541        identifier = name
4542    elif isinstance(name, str):
4543        identifier = Identifier(
4544            this=name,
4545            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4546        )
4547    else:
4548        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4549    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:
4555def to_interval(interval: str | Literal) -> Interval:
4556    """Builds an interval expression from a string like '1 day' or '5 months'."""
4557    if isinstance(interval, Literal):
4558        if not interval.is_string:
4559            raise ValueError("Invalid interval string.")
4560
4561        interval = interval.this
4562
4563    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4564
4565    if not interval_parts:
4566        raise ValueError("Invalid interval string.")
4567
4568    return Interval(
4569        this=Literal.string(interval_parts.group(1)),
4570        unit=Var(this=interval_parts.group(2)),
4571    )

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]:
4584def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4585    """
4586    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4587    If a table is passed in then that table is returned.
4588
4589    Args:
4590        sql_path: a `[catalog].[schema].[table]` string.
4591
4592    Returns:
4593        A table expression.
4594    """
4595    if sql_path is None or isinstance(sql_path, Table):
4596        return sql_path
4597    if not isinstance(sql_path, str):
4598        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4599
4600    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4601    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:
4604def to_column(sql_path: str | Column, **kwargs) -> Column:
4605    """
4606    Create a column from a `[table].[column]` sql path. Schema is optional.
4607
4608    If a column is passed in then that column is returned.
4609
4610    Args:
4611        sql_path: `[table].[column]` string
4612    Returns:
4613        Table: A column expression
4614    """
4615    if sql_path is None or isinstance(sql_path, Column):
4616        return sql_path
4617    if not isinstance(sql_path, str):
4618        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4619    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts):
4622def alias_(
4623    expression: ExpOrStr,
4624    alias: str | Identifier,
4625    table: bool | t.Sequence[str | Identifier] = False,
4626    quoted: t.Optional[bool] = None,
4627    dialect: DialectType = None,
4628    **opts,
4629):
4630    """Create an Alias expression.
4631
4632    Example:
4633        >>> alias_('foo', 'bar').sql()
4634        'foo AS bar'
4635
4636        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4637        '(SELECT 1, 2) AS bar(a, b)'
4638
4639    Args:
4640        expression: the SQL code strings to parse.
4641            If an Expression instance is passed, this is used as-is.
4642        alias: the alias name to use. If the name has
4643            special characters it is quoted.
4644        table: Whether or not to create a table alias, can also be a list of columns.
4645        quoted: whether or not to quote the alias
4646        dialect: the dialect used to parse the input expression.
4647        **opts: other options to use to parse the input expressions.
4648
4649    Returns:
4650        Alias: the aliased expression
4651    """
4652    exp = maybe_parse(expression, dialect=dialect, **opts)
4653    alias = to_identifier(alias, quoted=quoted)
4654
4655    if table:
4656        table_alias = TableAlias(this=alias)
4657        exp.set("alias", table_alias)
4658
4659        if not isinstance(table, bool):
4660            for column in table:
4661                table_alias.append("columns", to_identifier(column, quoted=quoted))
4662
4663        return exp
4664
4665    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4666    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4667    # for the complete Window expression.
4668    #
4669    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4670
4671    if "alias" in exp.arg_types and not isinstance(exp, Window):
4672        exp = exp.copy()
4673        exp.set("alias", alias)
4674        return exp
4675    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):
4678def subquery(expression, alias=None, dialect=None, **opts):
4679    """
4680    Build a subquery expression.
4681
4682    Example:
4683        >>> subquery('select x from tbl', 'bar').select('x').sql()
4684        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4685
4686    Args:
4687        expression (str | Expression): the SQL code strings to parse.
4688            If an Expression instance is passed, this is used as-is.
4689        alias (str | Expression): the alias name to use.
4690        dialect (str): the dialect used to parse the input expression.
4691        **opts: other options to use to parse the input expressions.
4692
4693    Returns:
4694        Select: a new select with the subquery expression included
4695    """
4696
4697    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4698    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

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

Select: a new select with the subquery expression included

def column( col: str | sqlglot.expressions.Identifier, table: Union[str, sqlglot.expressions.Identifier, NoneType] = None, db: Union[str, sqlglot.expressions.Identifier, NoneType] = None, catalog: Union[str, sqlglot.expressions.Identifier, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
4701def column(
4702    col: str | Identifier,
4703    table: t.Optional[str | Identifier] = None,
4704    db: t.Optional[str | Identifier] = None,
4705    catalog: t.Optional[str | Identifier] = None,
4706    quoted: t.Optional[bool] = None,
4707) -> Column:
4708    """
4709    Build a Column.
4710
4711    Args:
4712        col: column name
4713        table: table name
4714        db: db name
4715        catalog: catalog name
4716        quoted: whether or not to force quote each part
4717    Returns:
4718        Column: column instance
4719    """
4720    return Column(
4721        this=to_identifier(col, quoted=quoted),
4722        table=to_identifier(table, quoted=quoted),
4723        db=to_identifier(db, quoted=quoted),
4724        catalog=to_identifier(catalog, quoted=quoted),
4725    )

Build a Column.

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

Column: column instance

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
4728def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4729    """Cast an expression to a data type.
4730
4731    Example:
4732        >>> cast('x + 1', 'int').sql()
4733        'CAST(x + 1 AS INT)'
4734
4735    Args:
4736        expression: The expression to cast.
4737        to: The datatype to cast to.
4738
4739    Returns:
4740        A cast node.
4741    """
4742    expression = maybe_parse(expression, **opts)
4743    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:
4746def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4747    """Build a Table.
4748
4749    Args:
4750        table (str | Expression): column name
4751        db (str | Expression): db name
4752        catalog (str | Expression): catalog name
4753
4754    Returns:
4755        Table: table instance
4756    """
4757    return Table(
4758        this=to_identifier(table, quoted=quoted),
4759        db=to_identifier(db, quoted=quoted),
4760        catalog=to_identifier(catalog, quoted=quoted),
4761        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4762    )

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:
4765def values(
4766    values: t.Iterable[t.Tuple[t.Any, ...]],
4767    alias: t.Optional[str] = None,
4768    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4769) -> Values:
4770    """Build VALUES statement.
4771
4772    Example:
4773        >>> values([(1, '2')]).sql()
4774        "VALUES (1, '2')"
4775
4776    Args:
4777        values: values statements that will be converted to SQL
4778        alias: optional alias
4779        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4780         If either are provided then an alias is also required.
4781         If a dictionary is provided then the first column of the values will be casted to the expected type
4782         in order to help with type inference.
4783
4784    Returns:
4785        Values: the Values expression object
4786    """
4787    if columns and not alias:
4788        raise ValueError("Alias is required when providing columns")
4789    table_alias = (
4790        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4791        if columns
4792        else TableAlias(this=to_identifier(alias) if alias else None)
4793    )
4794    expressions = [convert(tup) for tup in values]
4795    if columns and isinstance(columns, dict):
4796        types = list(columns.values())
4797        expressions[0].set(
4798            "expressions",
4799            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4800        )
4801    return Values(
4802        expressions=expressions,
4803        alias=table_alias,
4804    )

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:
4807def var(name: t.Optional[ExpOrStr]) -> Var:
4808    """Build a SQL variable.
4809
4810    Example:
4811        >>> repr(var('x'))
4812        '(VAR this: x)'
4813
4814        >>> repr(var(column('x', table='y')))
4815        '(VAR this: x)'
4816
4817    Args:
4818        name: The name of the var or an expression who's name will become the var.
4819
4820    Returns:
4821        The new variable node.
4822    """
4823    if not name:
4824        raise ValueError("Cannot convert empty name into var.")
4825
4826    if isinstance(name, Expression):
4827        name = name.name
4828    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:
4831def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4832    """Build ALTER TABLE... RENAME... expression
4833
4834    Args:
4835        old_name: The old name of the table
4836        new_name: The new name of the table
4837
4838    Returns:
4839        Alter table expression
4840    """
4841    old_table = to_table(old_name)
4842    new_table = to_table(new_name)
4843    return AlterTable(
4844        this=old_table,
4845        actions=[
4846            RenameTable(this=new_table),
4847        ],
4848    )

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:
4851def convert(value) -> Expression:
4852    """Convert a python value into an expression object.
4853
4854    Raises an error if a conversion is not possible.
4855
4856    Args:
4857        value (Any): a python object
4858
4859    Returns:
4860        Expression: the equivalent expression object
4861    """
4862    if isinstance(value, Expression):
4863        return value
4864    if value is None:
4865        return NULL
4866    if isinstance(value, bool):
4867        return Boolean(this=value)
4868    if isinstance(value, str):
4869        return Literal.string(value)
4870    if isinstance(value, float) and math.isnan(value):
4871        return NULL
4872    if isinstance(value, numbers.Number):
4873        return Literal.number(value)
4874    if isinstance(value, tuple):
4875        return Tuple(expressions=[convert(v) for v in value])
4876    if isinstance(value, list):
4877        return Array(expressions=[convert(v) for v in value])
4878    if isinstance(value, dict):
4879        return Map(
4880            keys=[convert(k) for k in value],
4881            values=[convert(v) for v in value.values()],
4882        )
4883    if isinstance(value, datetime.datetime):
4884        datetime_literal = Literal.string(
4885            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4886        )
4887        return TimeStrToTime(this=datetime_literal)
4888    if isinstance(value, datetime.date):
4889        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4890        return DateStrToDate(this=date_literal)
4891    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):
4894def replace_children(expression, fun, *args, **kwargs):
4895    """
4896    Replace children of an expression with the result of a lambda fun(child) -> exp.
4897    """
4898    for k, v in expression.args.items():
4899        is_list_arg = type(v) is list
4900
4901        child_nodes = v if is_list_arg else [v]
4902        new_child_nodes = []
4903
4904        for cn in child_nodes:
4905            if isinstance(cn, Expression):
4906                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4907                    new_child_nodes.append(child_node)
4908                    child_node.parent = expression
4909                    child_node.arg_key = k
4910            else:
4911                new_child_nodes.append(cn)
4912
4913        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):
4916def column_table_names(expression):
4917    """
4918    Return all table names referenced through columns in an expression.
4919
4920    Example:
4921        >>> import sqlglot
4922        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4923        ['c', 'a']
4924
4925    Args:
4926        expression (sqlglot.Expression): expression to find table names
4927
4928    Returns:
4929        list: A list of unique names
4930    """
4931    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:
4934def table_name(table) -> str:
4935    """Get the full name of a table as a string.
4936
4937    Args:
4938        table (exp.Table | str): table expression node or string.
4939
4940    Examples:
4941        >>> from sqlglot import exp, parse_one
4942        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
4943        'a.b.c'
4944
4945    Returns:
4946        The table name.
4947    """
4948
4949    table = maybe_parse(table, into=Table)
4950
4951    if not table:
4952        raise ValueError(f"Cannot parse {table}")
4953
4954    return ".".join(
4955        part
4956        for part in (
4957            table.text("catalog"),
4958            table.text("db"),
4959            table.name,
4960        )
4961        if part
4962    )

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):
4965def replace_tables(expression, mapping):
4966    """Replace all tables in expression according to the mapping.
4967
4968    Args:
4969        expression (sqlglot.Expression): expression node to be transformed and replaced.
4970        mapping (Dict[str, str]): mapping of table names.
4971
4972    Examples:
4973        >>> from sqlglot import exp, parse_one
4974        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
4975        'SELECT * FROM c'
4976
4977    Returns:
4978        The mapped expression.
4979    """
4980
4981    def _replace_tables(node):
4982        if isinstance(node, Table):
4983            new_name = mapping.get(table_name(node))
4984            if new_name:
4985                return to_table(
4986                    new_name,
4987                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
4988                )
4989        return node
4990
4991    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):
4994def replace_placeholders(expression, *args, **kwargs):
4995    """Replace placeholders in an expression.
4996
4997    Args:
4998        expression (sqlglot.Expression): expression node to be transformed and replaced.
4999        args: positional names that will substitute unnamed placeholders in the given order.
5000        kwargs: keyword arguments that will substitute named placeholders.
5001
5002    Examples:
5003        >>> from sqlglot import exp, parse_one
5004        >>> replace_placeholders(
5005        ...     parse_one("select * from :tbl where ? = ?"),
5006        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5007        ... ).sql()
5008        "SELECT * FROM foo WHERE str_col = 'b'"
5009
5010    Returns:
5011        The mapped expression.
5012    """
5013
5014    def _replace_placeholders(node, args, **kwargs):
5015        if isinstance(node, Placeholder):
5016            if node.name:
5017                new_name = kwargs.get(node.name)
5018                if new_name:
5019                    return convert(new_name)
5020            else:
5021                try:
5022                    return convert(next(args))
5023                except StopIteration:
5024                    pass
5025        return node
5026
5027    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

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

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy=True) -> sqlglot.expressions.Expression:
5030def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression:
5031    """Transforms an expression by expanding all referenced sources into subqueries.
5032
5033    Examples:
5034        >>> from sqlglot import parse_one
5035        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5036        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5037
5038    Args:
5039        expression: The expression to expand.
5040        sources: A dictionary of name to Subqueryables.
5041        copy: Whether or not to copy the expression during transformation. Defaults to True.
5042
5043    Returns:
5044        The transformed expression.
5045    """
5046
5047    def _expand(node: Expression):
5048        if isinstance(node, Table):
5049            name = table_name(node)
5050            source = sources.get(name)
5051            if source:
5052                subquery = source.subquery(node.alias or name)
5053                subquery.comments = [f"source: {name}"]
5054                return subquery
5055        return node
5056
5057    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:
5060def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5061    """
5062    Returns a Func expression.
5063
5064    Examples:
5065        >>> func("abs", 5).sql()
5066        'ABS(5)'
5067
5068        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5069        'CAST(5 AS DOUBLE)'
5070
5071    Args:
5072        name: the name of the function to build.
5073        args: the args used to instantiate the function of interest.
5074        dialect: the source dialect.
5075        kwargs: the kwargs used to instantiate the function of interest.
5076
5077    Note:
5078        The arguments `args` and `kwargs` are mutually exclusive.
5079
5080    Returns:
5081        An instance of the function of interest, or an anonymous function, if `name` doesn't
5082        correspond to an existing `sqlglot.expressions.Func` class.
5083    """
5084    if args and kwargs:
5085        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5086
5087    from sqlglot.dialects.dialect import Dialect
5088
5089    converted = [convert(arg) for arg in args]
5090    kwargs = {key: convert(value) for key, value in kwargs.items()}
5091
5092    parser = Dialect.get_or_raise(dialect)().parser()
5093    from_args_list = parser.FUNCTIONS.get(name.upper())
5094
5095    if from_args_list:
5096        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5097    else:
5098        kwargs = kwargs or {"expressions": converted}
5099        function = Anonymous(this=name, **kwargs)
5100
5101    for error_message in function.error_messages(converted):
5102        raise ValueError(error_message)
5103
5104    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():
5107def true():
5108    """
5109    Returns a true Boolean expression.
5110    """
5111    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5114def false():
5115    """
5116    Returns a false Boolean expression.
5117    """
5118    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5121def null():
5122    """
5123    Returns a Null expression.
5124    """
5125    return Null()

Returns a Null expression.